Esempio n. 1
0
def main() :

    global samplesPhoton

    baseDirPhoton  = '/data/users/jkunkle/RecoPhoton/Photon_2015_11_23'

    treename = 'tupel/EventTree'
    filename = 'tree.root'

    sampleConfPhoton = 'Modules/SinglePhoton15.py'
    xsfile = 'cross_sections/photon15.py'

    lumi=2093.

    samplesPhoton   = SampleManager(baseDirPhoton, treename, filename=filename, xsFile=xsfile, lumi=lumi, quiet=options.quiet)

    samplesPhoton    .ReadSamples( sampleConfPhoton )

    if options.save :
        ROOT.gROOT.SetBatch(True)

    if options.outputDir is not None :
        samplesPhoton.start_command_collection()

    if options.makeAll or options.makePhotonComp :
        MakePhotonCompPlots( save=options.save, detail=options.detailLevel )

    samplesPhoton.run_commands(nFilesPerJob=1, treeName=treename)
Esempio n. 2
0
def main():

    global samples

    if not options.baseDir.count('/eos/') and not os.path.isdir(
            options.baseDir):
        print 'baseDir not found!'
        return

    samples = SampleManager(options.baseDir,
                            options.treeName,
                            mcweight=options.mcweight,
                            treeNameModel=options.treeNameModel,
                            filename=options.fileName,
                            base_path_model=options.baseDirModel,
                            xsFile=options.xsFile,
                            lumi=options.lumi,
                            readHists=options.readHists,
                            quiet=options.quiet)

    if options.samplesConf is not None:

        samples.ReadSamples(options.samplesConf)

        print 'Samples ready.\n'

        print 'The draw syntax follows that of TTree.Draw.  Examples : '

        print 'samples.Draw(\'met_et\', \'EventWeight && passcut_ee==1\', \'(300, 0, 300)\'\n'

        print 'The first argument is a branch in the tree to draw'
        print 'The second argument is a set of cuts and/or weights to apply'
        print 'The third argument are the bin limits to use \n'

        print 'To see all available branches do ListBranches()'
Esempio n. 3
0
def run_sp(num_path, den_path, num_conf, den_conf):

    samples_num = SampleManager(num_path, 1.0, 'photons')
    samples_den = SampleManager(den_path, 1.0, 'photons')

    read_samples(samples_num, num_conf)
    read_samples(samples_den, den_conf)

    draw_command_num_incljet_0conv = 'EventWeight * ( ph_n == 1 && ph_pt > 25.0 && ph_nConvTrk == 0 && ph_pass_tight && ph_corriso_30 < 2000  )'
    draw_command_num_incljet_2conv = 'EventWeight * ( ph_n == 1 && ph_pt > 25.0 && ph_nConvTrk == 2 && ph_pass_tight && ph_corriso_30 < 2000  )'

    num_dist = 'ph_pt'
    den_dist = 'ph_pt'

    binning = [
        25, 35, 45, 55, 65, 75, 85, 105, 125, 150, 175, 200, 250, 300, 400,
        1000
    ]

    MakeRatio(samples_num, samples_den, num_dist, den_dist,
              draw_command_num_incljet_0conv, draw_command_num_incljet_0conv,
              binning, options.outputDir + '/AllJet/Conv0/hist.root')
    MakeRatio(samples_num, samples_den, num_dist, den_dist,
              draw_command_num_incljet_2conv, draw_command_num_incljet_2conv,
              binning, options.outputDir + '/AllJet/Conv2/hist.root')
Esempio n. 4
0
def main() :

    global samplesMuMu
    global samplesElEl

    baseDirMuMu = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/TAndPMuMu_2014_11_27'
    baseDirElEl = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/TAndPElEl_2014_11_27'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConf = 'Modules/TAndPSampleConf.py'

    samplesMuMu = SampleManager(baseDirMuMu, treename, filename=filename, xsFile=options.xsFile, lumi=options.lumi, quiet=options.quiet)
    samplesElEl = SampleManager(baseDirElEl, treename, filename=filename, xsFile=options.xsFile, lumi=options.lumi, quiet=options.quiet)

    samplesMuMu .ReadSamples( sampleConf )
    samplesElEl .ReadSamples( sampleConf )

    if options.outputDir is not None :
        ROOT.gROOT.SetBatch(True)

    samplesMuMu.start_command_collection()
    samplesElEl.start_command_collection()

    MakeMuMuPlots( )
    MakeElElPlots( )

    samplesMuMu.run_commands()
    samplesElEl.run_commands()
Esempio n. 5
0
def main() :

    global sampManLG
    global sampManLLG
    global sampManFit

    base_dir_lg = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaNoPhID_2015_06_29/'
    base_dir_llg = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_06_29/'
    fit_dir  = options.fitPath

    sampManLG    = SampleManager(base_dir_lg, options.treeName,filename=options.fileName, xsFile=options.xsFile, lumi=options.lumi, quiet=options.quiet)
    sampManLLG   = SampleManager(base_dir_llg, options.treeName,filename=options.fileName, xsFile=options.xsFile, lumi=options.lumi, quiet=options.quiet)
    sampManFit = SampleManager(fit_dir, options.treeName,filename=options.fileName, xsFile=options.xsFile, lumi=options.lumi, quiet=options.quiet)


    if options.samplesConf is not None :

        sampManLG.ReadSamples( options.samplesConf )
        sampManLLG.ReadSamples( options.samplesConf )
        sampManFit.ReadSamples( options.samplesConf )

    if options.outputDir is not None :
        if not os.path.isdir( options.outputDir ) :
            os.makedirs( options.outputDir )

    #RunClosureFitting( outputDir = None )

    if options.syst_file is not None :
        load_syst_file( options.syst_file )

    RunNomFitting( outputDir = options.outputDir, ch=options.channel, fitvar=options.fitvar, pid=options.pid)
Esempio n. 6
0
def main() :

    global samplesLLG

    baseDirLLG = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_07_16'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConfLLG = 'Modules/ZJetsTemplates.py'

    samplesLLG     = SampleManager(baseDirLLG , treename, filename=filename, xsFile='cross_sections/wgamgam.py', lumi=19400)

    samplesLLG    .ReadSamples( sampleConfLLG )

    ROOT.gROOT.SetBatch(True)

    binning = { 'EB' : ( 30, 0, 0.03 ), 'EE' : ( 30, 0, 0.09 ) }

    pt_bins = [(15, 25), (25,40), (40,70), (70,1000000)]


    all_hists = []

    for eta in ['EB', 'EE'] :
        for ptmin, ptmax in pt_bins :

            samplesLLG.Draw('ph_sigmaIEIE[0]', 'PUWeight * ( mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoSIEIE_n==1 && ph_HoverE12[0] < 0.05 && fabs( m_leplep-91.2 ) < 5 && leadPhot_sublLepDR >1 && leadPhot_leadLepDR>1 && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] ) ' %( ptmin, ptmax, eta ), binning[eta] )


            hist_data = samplesLLG.get_samples( name='Muon' )[0]
            hist_bkg = samplesLLG.get_samples( name='RealPhotonsZg' )[0]

            hist_subtracted = hist_data.hist.Clone( 'Subtracted_%s_%d-%d' %( eta, ptmin, ptmax ))

            hist_subtracted.Add( hist_bkg.hist, -1 )

            all_hists.append( hist_data.hist.Clone( 'Data_%s_%d-%d' %( eta, ptmin, ptmax ) ) )
            all_hists.append( hist_bkg.hist.Clone( 'Zg_%s_%d-%d' %( eta, ptmin, ptmax ) ) )
            all_hists.append( hist_subtracted)


    out_file = ROOT.TFile.Open( options.outputFile, 'RECREATE' )

    for hist in all_hists :
        hist.Write()

    out_file.Close()

    print '^_^ Finished ^_^'
Esempio n. 7
0
def run_caf(dil_path, gj_path, dil_conf, gj_conf):

    samples_dil_ee = SampleManager(options.dil_path, 1.0, 'HWWTree_ee')
    samples_dil_mm = SampleManager(options.dil_path, 1.0, 'HWWTree_mm')
    samples_gj = SampleManager(options.gj_path,
                               1.0,
                               'photons',
                               filename='ntuple.root')

    read_samples(samples_dil_ee, options.dil_conf)
    read_samples(samples_dil_mm, options.dil_conf)
    read_samples(samples_gj, options.gj_conf)

    draw_command_dil_ee_incldphi_incljet = 'mcEventWeight * ( isLowPtCand==0 && Mll > 12000 && Mll < 60000 && Ptll > 30 && (lepID0*lepID1==-121) )'
    draw_command_dil_mm_incldphi_incljet = 'mcEventWeight * ( isLowPtCand==0 && Mll > 12000 && Mll < 60000 && Ptll > 30 &&  (lepID0*lepID1==-169) )'
    draw_command_dil_ee_incldphi_jetcut = 'mcEventWeight * ( isLowPtCand==0 && Mll > 12000 && Mll < 60000 && Ptll > 30 &&  (lepID0*lepID1==-121) && m_jet_n>1  )'
    draw_command_dil_mm_incldphi_jetcut = 'mcEventWeight * ( isLowPtCand==0 && Mll > 12000 && Mll < 60000 && Ptll > 30 &&  (lepID0*lepID1==-169) && m_jet_n>1  )'

    draw_command_gj_incljet = 'EventWeight * ( ph_pt > 30.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
    draw_command_gj_jetcut = 'EventWeight * ( ph_pt > 30.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_n > 1 )'

    dil_dist = 'Ptll'
    gj_dist = 'ph_pt'

    binning_incljet = range(30, 80) + [
        80, 85, 90, 95, 100, 110, 120, 130, 150, 200, 300, 500, 1000
    ]
    binning_jetcut = range(30, 80) + [
        80, 85, 90, 95, 100, 110, 120, 130, 150, 200, 300, 500, 1000
    ]

    MakeRatio(samples_dil_ee, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_incldphi_incljet, draw_command_gj_incljet,
              binning_incljet, options.outputDir + '/AllJet/EE/hist.root')

    MakeRatio(samples_dil_mm, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_incldphi_incljet, draw_command_gj_incljet,
              binning_incljet, options.outputDir + '/AllJet/MM/hist.root')

    MakeRatio(samples_dil_ee, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_incldphi_jetcut, draw_command_gj_jetcut,
              binning_jetcut, options.outputDir + '/NJet2/EE/hist.root')

    MakeRatio(samples_dil_mm, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_incldphi_jetcut, draw_command_gj_jetcut,
              binning_jetcut, options.outputDir + '/NJet2/MM/hist.root')
Esempio n. 8
0
def main():

    global samplesWgg
    global samplesWggComb
    global samplesWggBkgSub

    sampleConfWgg = 'Modules/WggFinal.py'
    sampleConfWggBkgSub = 'Modules/WggFinalBkgSub.py'

    samplesWgg = SampleManager(options.baseDir,
                               filename='hist.root',
                               xsFile='cross_sections/wgamgam.py',
                               lumi=19400,
                               readHists=True)
    samplesWggComb = SampleManager(options.baseDirComb,
                                   filename='hist.root',
                                   xsFile='cross_sections/wgamgam.py',
                                   lumi=19400,
                                   readHists=True)
    samplesWggBkgSub = SampleManager(options.baseDirComb,
                                     filename='hist.root',
                                     xsFile='cross_sections/wgamgam.py',
                                     lumi=19400,
                                     readHists=True)

    samplesWgg.ReadSamples(sampleConfWgg)
    samplesWggComb.ReadSamples(sampleConfWgg)
    samplesWggBkgSub.ReadSamples(sampleConfWggBkgSub)

    if options.outputDir is not None:
        ROOT.gROOT.SetBatch(True)

    if options.electron:
        MakeElectronPlots(options.outputDir, suffix='', ylabel='Events / bin')
        MakeElectronPlots(options.outputDir,
                          suffix='_perGeV',
                          ylabel='Events / 5 GeV',
                          logy=1)
    if options.muon:
        MakeMuonPlots(options.outputDir, suffix='', ylabel='Events / bin')
        MakeMuonPlots(options.outputDir,
                      suffix='_perGeV',
                      ylabel='Events / 5 GeV',
                      logy=1)
    if options.combined:
        MakeCombinedPlots(options.outputDir)

    print '^.^ FINSHED ^.^'
Esempio n. 9
0
def main() :
    #sampManMuG= SampleManager( options.baseDirMuG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManElG= SampleManager( baseDirElG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )

    #sampManMuG.ReadSamples( _SAMPCONF )
    sampManElG.ReadSamples( _SAMPCONF )

    #sampManMuG.outputs = {}
    sampManElG.outputs = {}

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1'
    #sel_base_el = 'ph_n==1 && el_n==1'
    #sel_base_el = 'ph_n>=1 && el_n>=1'
    sel_base_el = '1'
    sel_base_el = 'ph_n>=1 && el_n==1 &&ph_pt[0]>50'
    sel_base_el = 'ph_n>=1 && el_n==1 &&!( ph_eta[0]<0&&ph_phi[0]>2.3&&ph_phi[0]<2.7)&&!(ph_phi[0]>1.2&&ph_phi[0]<1.5) '
    sel_base_el = 'ph_n>=1 && el_n==1' 
    samp = 'Z+jets'
    if options.data:
            samp='Data'

    #eta_cuts = ['EB', 'EE']
    eta_cuts = ['EB']

    workspaces_to_save = {}

    selections = { 'base'    : { 
                               # 'mu' : {'selection' : sel_base_mu }, 
                                'el' : { 'selection' : sel_base_el }, 
                               },
                  }

    elefake            = ROOT.RooWorkspace( 'elefake' )

    #make_efake( sampManElG, 'Z+jets', sel_base_el,'EB', 'ph_eta', suffix='noOvLrm', closure=False, workspace=elefake, overlaprm=0)


    f1 = ROOT.TFile("%s/output.root"%(options.outputDir),"RECREATE")

    #undo scaling by cross section
#   print "scale ", sampManElG.get_samples(name="DYJetsToLL_M-50")[0].scale
    if not options.data: sampManElG.get_samples(name="DYJetsToLL_M-50")[0].scale=1.
    #closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',var = "ph_eta",varbins=np.linspace(-1.4,1.4,15),xtitle="photon #eta",mode=2)
#   closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',var = "ph_phi",varbins=np.linspace(-3.1416,3.1416,21),xtitle="photon #phi",mode=2)
#   closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[-2.4,-1.8,-1.4,-1,-0.6,-0.3,0,0.3,0.6,1,1.4,1.8,2.4], var="ph_eta")
    #closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=range(20,100,10)+[150,160], mode=1)
    #closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[20,30,40,70,100,110], mode=1)
    #sampManElG.closure( samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[20,30,40,50,70,90,110,150,160], mode=1)
    sampManElG.closure( samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[0,30,40,50,60,80], mode=1)
    #closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[40,1000])
#    closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[20,1000])
#   closure( sampManElG, samp, sel_base_el,'EB', plot_var = 'm_lep_ph',var="jet_n",varbins=range(0,10), mode=2)
#   closure( sampManElG, 'Wgamma', sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[0,50,250])

    #elefake.writeToFile( '%s/%s.root' %( options.outputDir,elefake.GetName() ) )
    #for key, can in sampManElG.outputs.iteritems() :
    f1.Write()
    f1.Close()
Esempio n. 10
0
def makeMetPlots(baseDir, sampleConf, outputDir=None):

    sampMan = SampleManager(baseDir, _TREENAME, filename=_FILENAME)
    sampMan.ReadSamples(sampleConf)

    samp_name = 'Comb'

    samp = sampMan.get_samples(name=samp_name)

    if not samp:
        print('Could not find sample!')
        return

    binning_x = list(range(0, 50, 5)) + list(range(50, 300, 10)) + list(
        range(300, 600, 20)) + list(range(600, 2000, 100)) + [2000, 3000]
    binning_y = list(range(-1000, 1000, 10))

    var = 'truemet_pt-recomet_pt:truemet_pt'

    sampMan.create_hist(samp[0], var, '', (binning_x, binning_y))

    thishist = samp[0].hist.Clone('met')

    thishist_px = thishist.ProfileX('met_px')

    can = ROOT.TCanvas('metRes', 'metRes')

    thishist_px.Draw()
    can.SetLogx()
    if outputDir:
        can.SaveAs('%s/MetResolution.pdf' % (outputDir))
    else:
        input('cont')
Esempio n. 11
0
def main() :
    #if options.outputDir: f1 = ROOT.TFile("%s/output.root"%(options.outputDir),"RECREATE")

    sampManMuG= SampleManager( options.baseDirMuG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI, readHists=True , weightHistName = "weighthist")
    sampManMuG.ReadSamples( _SAMPCONF )
    sampManElG= SampleManager( options.baseDirElG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI ,readHists=True , weightHistName = "weighthist")
    sampManElG.ReadSamples( _SAMPCONF )
    print options.baseDirElG
    #samples = sampManMuG

    for ch, samples in zip(["mu","el"],[sampManMuG,sampManElG]):
    #for ch, samples in [("el",sampManElG),]:
        #hname = samples[0].walk_text()
        #hname =  [h[:-7] for h in hname if "_before" in h] # choose cut histograms
        hname = hnames
        labelname = "%i Muon Channel" %options.year if ch == "mu" else "%i Electron Channel" %options.year
        #samplname = "WGToLNuG-amcatnloFXFX"
        samplname = "AllTop"

        for h in hname:
            ## prepare config
            xlabel = h.split("/Filter")[-1]
            hist_config   = {"colors":[4,2],"drawopt":"hist","logy":True,"xunit":"","xlabel":xlabel, "ymax_scale":1.4}
            label_config  = {"extra_label":labelname, "extra_label_loc":(.17,.82)}
            legend_config = {"legend_entries":[samplname+" before",samplname+" after"]}

            ## draw histogram
            samples.CompareHists([h+"_before", h+"_after"],[samplname]*2,
                                "",hist_config=hist_config, label_config=label_config, legend_config=legend_config)

            #samples[-1].hist.GetYaxis().UnZoom()

            ## save histogram
            samples.SaveStack(xlabel+"%i%s.pdf" %(options.year, ch), options.outputDir, "base")
Esempio n. 12
0
def ReadMuElSamples(baseDirMu=None, baseDirEl=None):

    if baseDirMu is None:
        baseDirMu = options.baseDirMu
    if baseDirEl is None:
        baseDirEl = options.baseDirEl

    sampManMu = SampleManager(baseDirMu,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI)
    sampManEl = SampleManager(baseDirEl,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI)

    if options.samplesConf is not None:

        sampManMu.ReadSamples(options.samplesConf)
        sampManEl.ReadSamples(options.samplesConf)
    else:
        print 'Must provide a sample configuration.  Exiting'
        return

    return sampManMu, sampManEl
Esempio n. 13
0
def makeMuPlots(baseDirMu, sampleConf, outputDir=None, trig=False):

    sampMan = SampleManager(baseDirMu, _TREENAME, filename=_FILENAME)
    sampMan.ReadSamples(sampleConf)

    samp_name = 'Comb'

    samp = sampMan.get_samples(name=samp_name)

    if not samp:
        print('Could not find sample!')
        return

    #binning = range( 0, 50, 5) + range( 50, 500, 10 ) + range( 500, 2000, 100 )
    binning = list(range(0, 50, 5)) + list(range(50, 300, 10)) + list(
        range(300, 600, 20)) + list(range(600, 2000, 100)) + [2000, 3000]

    var = 'truemu_pt'

    name = 'MuonEff'

    if trig:
        labels = [
            'IsoMu24', 'IsoTkMu24', 'IsoTkMu24 || IsoMu24', 'Mu17_Photon30'
        ]
        colors = [ROOT.kBlack, ROOT.kRed, ROOT.kGreen, ROOT.kBlue]
        selections = [
            '', 'passTrig_IsoMu24', 'passTrig_IsoTkMu24',
            'passTrig_IsoMu24 || passTrig_IsoTkMu24 ',
            'passTrig_Mu17_Photon30_CaloIdL_L1ISO'
        ]
        name += 'Trig'

    else:
        #labels = ['Container Muons', 'Triggered Muons', 'Tight Muons', 'Triggered Tight Muons']
        labels = ['Container Muons', 'Tight Muons']
        colors = [ROOT.kBlack, ROOT.kRed]
        selections = [
            '', 'hasTruthMatch', 'hasTruthMatch && muprobe_passTight '
        ]

    hists = []
    for idx, selection in enumerate(selections):
        sampMan.create_hist(samp[0], var, selection, binning)

        thissamp = sampMan.get_samples(name=samp_name)

        hists.append(thissamp[0].hist.Clone('hist_%d' % idx))

    print(hists)

    canvas = ROOT.TCanvas(name, name)

    DrawHists(canvas, hists, colors, labels, outputDir)
Esempio n. 14
0
def main() :

    global samples
    sampleConf = 'Modules/StudyWgammaFinal.py'

    samples = SampleManager(options.baseDir, filename='hist.root', readHists=True)

    for dirname in os.listdir( options.baseDir ) :
        if os.path.isdir( '%s/%s' %( options.baseDir, dirname ) ) :
            samples.AddSample( dirname, path=dirname )

    sample_list = samples.get_samples()

    sample_pairs = []

    for s in sample_list :
        if s.name.count('chIsoCorr') :

            samp_sieie = s.name.replace( 'chIsoCorr', 'sigmaIEIE' )

            sample_pairs.append( ( s.name, samp_sieie ) ) 

    output_dir = options.baseDir
    #output_dir = None

    MakeRatioComparisons( sample_pairs, ['elz_sb_fine_medium_CutMet0', 'elz_sb_fine_tight_CutMet0', 'elz_sb_two_tight_CutMet0'], ['Medium range', 'Tight range', 'Two bin fit'], output_dir, name_postfix = 'comp_elz_fitmethods' )
    MakeRatioComparisons( sample_pairs, ['muz_sb_fine_medium_CutMet0', 'muz_sb_fine_tight_CutMet0', 'muz_sb_two_tight_CutMet0'], ['Medium range', 'Tight range', 'Two bin fit'], output_dir,name_postfix = 'comp_muz_fitmethods' )

    MakeRatioComparisons( sample_pairs, ['mu_cr_fine_medium_CutMet0', 'mu_cr_fine_tight_CutMet0', 'mu_cr_two_medium_CutMet0'], ['Medium range', 'Tight range', 'Two bin fit'], output_dir, name_postfix='comp_mu_fitmethods' )
    MakeRatioComparisons( sample_pairs, ['el_cr_fine_medium_CutMet0', 'el_cr_fine_tight_CutMet0', 'el_cr_two_medium_CutMet0'], ['Medium range', 'Tight range', 'Two bin fit'], output_dir, name_postfix='comp_el_fitmethods' )
    MakeRatioComparisons( sample_pairs, ['mu_cr_fine_tight_CutMet0', 'mu_sb_fine_tight_CutMet0', ], ['Control region template', 'Sideband template'], output_dir, name_postfix='comp_mu_faketemplates' )
    MakeRatioComparisons( sample_pairs, ['el_cr_fine_tight_CutMet0', 'el_sb_fine_tight_CutMet0', ], ['Control region template', 'Sideband template'], output_dir, name_postfix='comp_el_faketemplates' )

    MakeRatioComparisons( sample_pairs, ['mu_cr_two_tight_CutMet0', 'mu_sb_two_tight_CutMet0', ], ['Control region template', 'Sideband template'], output_dir, name_postfix='comp_mu_twobin_faketemplates' )
    MakeRatioComparisons( sample_pairs, ['el_cr_two_tight_CutMet0', 'el_sb_two_tight_CutMet0', ], ['Control region template', 'Sideband template'], output_dir, name_postfix='comp_el_twobin_faketemplates' )

    MakeComparison( sample_pairs, 'muz_sb_fine_tight_CutMet0', output_dir=output_dir )
    MakeComparison( sample_pairs, 'mu_sb_fine_tight_CutMet0', output_dir=output_dir )
Esempio n. 15
0
def main():

    global samplesLLG

    baseDirLLG = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_07_16'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConfLLG = 'Modules/ZJetsTemplates.py'

    samplesLLG = SampleManager(baseDirLLG,
                               treename,
                               filename=filename,
                               xsFile='cross_sections/wgamgam.py',
                               lumi=19400)

    samplesLLG.ReadSamples(sampleConfLLG)

    ROOT.gROOT.SetBatch(True)

    binning = {'EB': (30, 0, 0.03), 'EE': (30, 0, 0.09)}

    pt_bins = [(15, 25), (25, 40), (40, 70), (70, 1000000)]

    all_hists = []

    for eta in ['EB', 'EE']:
        for ptmin, ptmax in pt_bins:

            samplesLLG.Draw(
                'ph_sigmaIEIE[0]',
                'PUWeight * ( mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoSIEIE_n==1 && ph_HoverE12[0] < 0.05 && fabs( m_leplep-91.2 ) < 5 && leadPhot_sublLepDR >1 && leadPhot_leadLepDR>1 && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] ) '
                % (ptmin, ptmax, eta), binning[eta])

            hist_data = samplesLLG.get_samples(name='Muon')[0]
            hist_bkg = samplesLLG.get_samples(name='RealPhotonsZg')[0]

            hist_subtracted = hist_data.hist.Clone('Subtracted_%s_%d-%d' %
                                                   (eta, ptmin, ptmax))

            hist_subtracted.Add(hist_bkg.hist, -1)

            all_hists.append(
                hist_data.hist.Clone('Data_%s_%d-%d' % (eta, ptmin, ptmax)))
            all_hists.append(
                hist_bkg.hist.Clone('Zg_%s_%d-%d' % (eta, ptmin, ptmax)))
            all_hists.append(hist_subtracted)

    out_file = ROOT.TFile.Open(options.outputFile, 'RECREATE')

    for hist in all_hists:
        hist.Write()

    out_file.Close()

    print '^_^ Finished ^_^'
Esempio n. 16
0
def main():
    parent_dir = handle_arguments()

    # Parse parent dir
    samples = setup_samples(parent_dir)

    # Create sample manager
    sample_manager = SampleManager(samples)

    # Print global stats
    #sample_manager.print_global_summary()
    #sample_manager.print_module_stats()

    # Wait for input
    read_input(sample_manager)
Esempio n. 17
0
def main():

    global samples

    baseDir = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/SingleLepton_2014_09_03/'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConf = 'Modules/Wgamgam.py'

    samples = SampleManager(baseDir,
                            treename,
                            filename=filename,
                            xsFile=options.xsFile,
                            lumi=options.lumi,
                            quiet=options.quiet)

    samples.ReadSamples(sampleConf)

    #if options.save :
    #    ROOT.gROOT.SetBatch(True)

    MakePredictions(save=False)
def main() :

    width_colors = { '0.01' : ROOT.kRed, '1' : ROOT.kBlack, '5' : ROOT.kGreen, '10' : ROOT.kBlue, '20' : ROOT.kMagenta }

    mass_colors = { 200 : ROOT.kBlack, 250 : ROOT.kRed, 300 : ROOT.kBlue, 350 : ROOT.kGreen, 400 : ROOT.kMagenta, 450 : ROOT.kOrange, 500 : ROOT.kCyan,
                   600 : ROOT.kBlack, 700 : ROOT.kRed, 800 : ROOT.kBlue, 900 : ROOT.kGreen, 1000 : ROOT.kMagenta, 1200 : ROOT.kOrange, 1400 : ROOT.kCyan,
                   1600 : ROOT.kBlack, 1800: ROOT.kRed, 2000 : ROOT.kBlue, 2200 : ROOT.kGreen, 2400 : ROOT.kMagenta, 2600 : ROOT.kOrange, 2800 : ROOT.kCyan, 3000 : ROOT.kBlack,
                   3500 : ROOT.kRed, 4000 : ROOT.kBlue, 

                  }

    sampMan       = SampleManager(options.baseDir, filename='validation.root', readHists=True)
    sampManMass   = SampleManager(options.baseDir, filename='validation.root', readHists=True)

    samples_lepnu = []
    samples_qq = []

    dirBaseName = 'MadGraphChargedResonance'
    if options.pythia :
        dirBaseName = 'PythiaChargedResonance'



    for dirname in os.listdir( options.baseDir ) :
        res = re.match( '%s_(WGToLNuG|WGToJJG)_M(\d{3,4})_width(0p01|\d{1,2})' %dirBaseName, dirname )

        if res is not None :

            mass = int( res.group(2) )
            print(dirname)
            print(res.group(3))
            if res.group(3) == '0p01' :
                width = '0.01'
            else :
                width = res.group(3)

            if res.group(1) == 'WGToLNuG' :
                continue
                samples_lepnu.append( {'name' : dirname, 'mass' : mass, 'width' :  width} )
            elif res.group(1) == 'WGToJJG'  :
                samples_qq.append( {'name' : dirname, 'mass' : mass, 'width' :  width} )


            sampMan.AddSample( dirname, path=dirname, isActive=False, isSignal=True, sigLineStyle=1, sigLineWidth=1, plotColor=width_colors[width] )
            sampManMass.AddSample( dirname, path=dirname, isActive=False, isSignal=True, sigLineStyle=1, sigLineWidth=1, plotColor=mass_colors[mass] )

    if options.pythia :
        samples_qq = samples_lepnu

    # make the list of masses unique

    draw_width_comp_hists( sampMan, 'm_lep_nu_ph', samples_lepnu, prefix='WidthCompare_ChargedResonance_WGToLNuG', xlabel='Resonance Mass [GeV]' )
    draw_width_comp_hists( sampMan, 'm_q_q_ph', samples_qq, prefix='WidthCompare_ChargedResonance_WGToJJG', xlabel='Resonance Mass [GeV]' )
    draw_mass_comp_hists( sampManMass, 'm_lep_nu_ph', samples_lepnu, prefix='MassCompare_ChargedResonance_WGToLNuG', xlabel='Resonance Mass [GeV]' )
    draw_mass_comp_hists( sampManMass, 'm_q_q_ph', samples_qq, prefix='MassCompare_ChargedResonance_WGToJJG', xlabel='Resonance Mass [GeV]' )
Esempio n. 19
0
def makeElPlots(baseDir, sampleConf, outputDir=None, trig=False):

    sampMan = SampleManager(baseDir, _TREENAME, filename=_FILENAME)
    sampMan.ReadSamples(sampleConf)

    samp_name = 'Comb'

    samp = sampMan.get_samples(name=samp_name)

    if not samp:
        print('Could not find sample!')
        return

    #binning = range( 0, 50, 5) + range( 50, 500, 10 ) + range( 500, 2000, 100 )
    binning = list(range(0, 50, 5)) + list(range(50, 300, 10)) + list(
        range(300, 600, 20)) + list(range(600, 2000, 100)) + [2000, 3000]

    var = 'trueel_pt'

    name = 'ElectronEff'

    if trig:
        labels = ['Ele24_eta2p1_WPTight_Gsf']
        colors = [ROOT.kBlack]
        selections = ['', 'passTrig_Ele27_eta2p1_WPTight_Gsf']
        name += 'Trig'
    else:
        labels = [
            'Container Electrons', 'Loose Electrons', 'Medium Electrons',
            'Tight Electrons'
        ]
        colors = [ROOT.kBlack, ROOT.kRed, ROOT.kGreen, ROOT.kBlue]
        selections = [
            '', 'hasTruthMatch', 'hasTruthMatch && elprobe_passLoose ',
            'hasTruthMatch && elprobe_passMedium ',
            'hasTruthMatch && elprobe_passTight '
        ]

    hists = []
    for idx, selection in enumerate(selections):
        sampMan.create_hist(samp[0], var, selection, binning)

        thissamp = sampMan.get_samples(name=samp_name)

        hists.append(thissamp[0].hist.Clone('hist_%d' % idx))

    canvas = ROOT.TCanvas(name, name)

    DrawHists(canvas, hists, colors, labels, outputDir)
Esempio n. 20
0
def main() :

    sampMan = SampleManager( options.baseDir, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )

    if options.samplesConf is not None :

        sampMan.ReadSamples( options.samplesConf )
    else :
        print 'Must provide a sample configuration.  Exiting'
        return


    var = 'mt_res'
    selection = 'mu_n==1 && ph_n==1'
    binning = ( 100, 0, 5000 )
    bkg_samp = 'MCBackground'
    sampMan.create_hist( bkg_samp, var,  selection, binning )

    bkg_hist = sampMan.get_samples( name=bkg_samp)[0].hist

    sig_normalizations = {}
    for samp in sampMan.get_samples( )  :
        if samp.name.count ( 'ResonanceMass' ) and samp.name.count( 'width0p01' ) :

            sampMan.create_hist( samp, var,  selection, binning )

            samp_bins = []

            for ibin in range( 0, samp.hist.GetNbinsX()  ) :

                samp_bins.append( (samp.hist.GetBinContent( ibin+1 ), ibin+1 ) )

            samp_bins.sort()
            print samp_bins

            peak_sum = samp_bins[-1][0] 
            bkg_sum = bkg_hist.GetBinContent( samp_bins[-1][1] ) 
            print 'Samp = %s, sig = %f, bkg = %f' %(samp.name, peak_sum, bkg_sum )


            sig_normalizations[samp.name] = float( bkg_sum )/peak_sum

    print sig_normalizations
Esempio n. 21
0
invzlt = '&& abs(m_lep_ph-91)>%i'
csvmed = " && jet_CSVMedium_n>1"

nophmatch = "&& !(ph_truthMatchPh_dr[0]<ph_truthMatchEl_dr[0])"
phmatch = "&& (ph_truthMatchPh_dr[0]<ph_truthMatchEl_dr[0])"
flatphi = "ph_phi[0]+3.1416*(1+2*(ph_eta[0]>0))"

UNBLIND = "ph_hasPixSeed[0]==1 || met_pt<40"
weight = "PUWeight*NLOWeight"
pie = 3.1416

## read MuG samples
sampManMuG = SampleManager(options.baseDirMuG,
                           _TREENAME,
                           filename=_FILENAME,
                           xsFile=_XSFILE,
                           lumi=_LUMI * lumiratio,
                           readHists=False,
                           weightHistName="weighthist",
                           dataFrame=options.dataFrame)

## read ElG samples
sampManElG = SampleManager(options.baseDirElG,
                           _TREENAME,
                           filename=_FILENAME,
                           xsFile=_XSFILE,
                           lumi=_LUMI * lumiratio,
                           readHists=False,
                           weightHistName="weighthist",
                           dataFrame=options.dataFrame)

## read MuMu samples
Esempio n. 22
0
def main():

    #sampManMuG = SampleManager( options.baseDirMuG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManMuG = SampleManager(options.baseDirMuG,
                               _TREENAME,
                               filename=_FILENAME)
    #sampManElG = SampleManager( options.baseDirElG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManElG = SampleManager(options.baseDirElG,
                               _TREENAME,
                               filename=_FILENAME)

    sampManMuG.ReadSamples(_SAMPCONF)
    sampManElG.ReadSamples(_SAMPCONF)

    sampManMuG.outputs = OrderedDict()
    sampManMuG.fitresults = OrderedDict()
    sampManMuG.chi2 = OrderedDict()
    sampManMuG.chi2prob = OrderedDict()

    sampManElG.outputs = OrderedDict()
    sampManElG.fitresults = OrderedDict()
    sampManElG.chi2 = OrderedDict()
    sampManElG.chi2prob = OrderedDict()

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1'
    sel_base_el = 'el_pt30_n==1 && el_n==1'

    sel_jetveto_mu = sel_base_mu + ' && jet_n == 0 '
    sel_jetveto_el = sel_base_el + ' && jet_n == 0 '

    #eta_cuts = ['EB', 'EE']
    eta_cuts = ['EB']

    workspaces_to_save = {}

    xmin_m = 60
    xmax_m = 4000
    bin_width_m = 20

    xmin_pt = xmin_m / 2
    if xmin_pt < 50:
        xmin_pt = 50
    xmax_pt = xmax_m / 2
    bin_width_pt = bin_width_m / 2.

    binning_m = ((xmax_m - xmin_m) / bin_width_m, xmin_m, xmax_m)

    binning_pt = ((xmax_pt - xmin_pt) / bin_width_pt, xmin_pt, xmax_pt)

    xvar_m = ROOT.RooRealVar('x_m', 'x_m', xmin_m, xmax_m)

    xvar_pt = ROOT.RooRealVar('x_pt', 'x_pt', xmin_pt, xmax_pt)

    signal_binning_m_width1 = {
        200: ((xmax_m) / 4, 0, xmax_m),
        250: ((xmax_m) / 4, 0, xmax_m),
        300: ((xmax_m) / 4, 0, xmax_m),
        350: ((xmax_m) / 4, 0, xmax_m),
        400: ((xmax_m) / 4, 0, xmax_m),
        450: ((xmax_m) / 5, 0, xmax_m),
        500: ((xmax_m) / 8, 0, xmax_m),
        600: ((xmax_m) / 10, 0, xmax_m),
        700: ((xmax_m) / 10, 0, xmax_m),
        800: ((xmax_m) / 10, 0, xmax_m),
        900: ((xmax_m) / 10, 0, xmax_m),
        1000: ((xmax_m) / 10, 0, xmax_m),
        1200: (int((xmax_m) / 15), 0, xmax_m),
        1400: (int((xmax_m) / 15), 0, xmax_m),
        1600: (int((xmax_m) / 15), 0, xmax_m),
        1800: (int((xmax_m) / 15), 0, xmax_m),
        2000: ((xmax_m) / 20, 0, xmax_m),
        2200: ((xmax_m) / 20, 0, xmax_m),
        2400: ((xmax_m) / 20, 0, xmax_m),
        2600: ((xmax_m) / 20, 0, xmax_m),
        2800: (int((xmax_m) / 25), 0, xmax_m),
        3000: (int((xmax_m) / 25), 0, xmax_m),
        3500: (int((xmax_m) / 40), 0, xmax_m),
        4000: (int((xmax_m) / 40), 0, xmax_m),
    }

    signal_binning_m_width2 = {
        200: ((xmax_m) / 4, 0, xmax_m),
        250: ((xmax_m) / 4, 0, xmax_m),
        300: ((xmax_m) / 4, 0, xmax_m),
        350: ((xmax_m) / 5, 0, xmax_m),
        400: ((xmax_m) / 5, 0, xmax_m),
        450: ((xmax_m) / 8, 0, xmax_m),
        500: ((xmax_m) / 8, 0, xmax_m),
        600: ((xmax_m) / 8, 0, xmax_m),
        700: ((xmax_m) / 10, 0, xmax_m),
        800: ((xmax_m) / 10, 0, xmax_m),
        900: (int((xmax_m) / 15), 0, xmax_m),
        1000: (int((xmax_m) / 15), 0, xmax_m),
        1200: ((xmax_m) / 20, 0, xmax_m),
        1400: ((xmax_m) / 25, 0, xmax_m),
        1600: ((xmax_m) / 25, 0, xmax_m),
        1800: (int((xmax_m) / 30), 0, xmax_m),
        2000: (int((xmax_m) / 30), 0, xmax_m),
        2200: (int((xmax_m) / 30), 0, xmax_m),
        2400: (int((xmax_m) / 30), 0, xmax_m),
        2600: (int((xmax_m) / 35), 0, xmax_m),
        2800: (int((xmax_m) / 35), 0, xmax_m),
        3000: (int((xmax_m) / 35), 0, xmax_m),
        3500: (int((xmax_m) / 40), 0, xmax_m),
        4000: (int((xmax_m) / 40), 0, xmax_m),
    }

    signal_binning_m = [signal_binning_m_width1, signal_binning_m_width2]

    signal_binning_pt = {}
    for mass, binning in signal_binning_m_width1.iteritems():
        pt_min = binning[1] / 2.
        if pt_min < 50:
            pt_min = 50
        signal_binning_pt[mass] = (binning[0] / 2., pt_min, binning[2] / 2.)

    kine_vars = {  #'mt_incl_lepph_z' : { 'var' : 'mt_lep_met_ph'   , 'xvar' : xvar_m  , 'binning' : binning_m, 'signal_binning' : signal_binning_m },
        #'m_incl_lepph_z'  : { 'var' : 'm_lep_met_ph'    , 'xvar' : xvar_m  , 'binning' : binning_m, 'signal_binning' : signal_binning_m },
        ##'mt_rotated'      : { 'var' : 'mt_rotated'      , 'xvar' : xvar_m  , 'binning' : binning_m, 'signal_binning' : signal_binning_m },
        'mt_fulltrans': {
            'var': 'mt_res',
            'xvar': xvar_m,
            'binning': binning_m,
            'signal_binning': signal_binning_m
        },
        #'mt_constrwmass'  : { 'var' : 'recoM_lep_nu_ph' , 'xvar' : xvar_m  , 'binning' : binning_m, 'signal_binning' : signal_binning_m },
        #'ph_pt'           : { 'var' : 'ph_pt[0]'        , 'xvar' : xvar_pt , 'binning' : binning_pt, 'signal_binning' : signal_binning_pt },
    }

    selections = {
        'base': {
            'mu': {
                'selection': sel_base_mu
            },
            'el': {
                'selection': sel_base_el
            },
        },
        #'jetVeto' : { 'mu' : {'selection' : sel_jetveto_mu },
        #              'el' : { 'selection' : sel_jetveto_el } ,
        #            },
    }

    lepg_samps = {'mu': sampManMuG, 'el': sampManElG}
    #lepg_samps = {'mu' : sampManMuG }

    for seltag, chdic in selections.iteritems():

        print "seltag: ", seltag, "chdic: ", chdic
        for ch, seldic in chdic.iteritems():

            print "ch:", ch, "seldic", seldic
            for name, vardata in kine_vars.iteritems():
                print "name", name, "vardata", vardata  #['signal_binning']

                make_signal_fits(lepg_samps[ch],
                                 seldic['selection'],
                                 eta_cuts,
                                 vardata['var'],
                                 vardata['xvar'],
                                 vardata['signal_binning'],
                                 workspaces_to_save,
                                 suffix='%s_%s_%s' % (ch, name, seltag),
                                 plots_dir=options.outputDir + "/plots")

    if options.outputDir is not None:

        for fileid, ws in workspaces_to_save.iteritems():
            #for idx, ws in enumerate(ws_list) :
            #if idx == 0 :
            #    recreate = True
            #else  :
            #    recreate = False

            ws.writeToFile('%s/%s.root' % (options.outputDir, fileid))
Esempio n. 23
0
def main() :

    global samplesWgg
    global samplesZgg
    global samplesWggComb
    global samplesWggBkgSub

    sampleConfWgg = 'Modules/WggFinal.py'
    if options.zgg :
        sampleConfWgg = 'Modules/ZggFinal.py'
    sampleConfWggBkgSub = 'Modules/WggFinalBkgSub.py'

    samplesWgg       = SampleManager(options.baseDir, filename='hist.root', readHists=True)
    samplesWggComb   = SampleManager(options.baseDirComb, filename='hist.root', readHists=True)
    #samplesWggBkgSub = SampleManager(options.baseDirComb, filename='hist.root', xsFile='cross_sections/wgamgam.py', lumi=19400, readHists=True)

    samplesWgg        .ReadSamples( sampleConfWgg )
    samplesWggComb    .ReadSamples( sampleConfWgg )
    #samplesWggBkgSub  .ReadSamples( sampleConfWggBkgSub )

    if options.outputDir is not None :
        ROOT.gROOT.SetBatch(True)

    dumpStack=True
    samplesWgg.activate_sample( 'AllBkg')
    samplesWgg.activate_sample( 'ZggNoSyst')
    samplesWgg.activate_sample( 'OtherDiPhotonNoSyst')
    samplesWgg.activate_sample( 'AllBkgPlusSig')
    samplesWgg.activate_sample('DiTopDiPhoton')
    samplesWgg.activate_sample('SingleTopDiPhoton')
    samplesWgg.activate_sample('TriBosonDiPhoton')
    samplesWgg.activate_sample('TTVDiPhoton')
    samplesWgg.activate_sample('WWDiPhoton')
    samplesWgg.activate_sample('WZlvjjDiPhoton')
    samplesWgg.activate_sample('WZlvllDiPhoton')
    samplesWgg.activate_sample('WZjjllDiPhoton')
    samplesWgg.activate_sample('WZlvvvDiPhoton')
    samplesWgg.activate_sample('ZZDiPhoton')

    if options.zgg and not options.money : 
        MakeZggPlots( options.outputDir, selection='muZgg', var='pt_leadph12', suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
        MakeZggPlots( options.outputDir, selection='elZgg', var='pt_leadph12', suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
        #MakeZggPlots( options.outputDir, selection='muZgg', var='m_ph1_ph2'  , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
        #MakeZggPlots( options.outputDir, selection='muZgg', var='pt_ph1_ph2' , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
        #MakeZggPlots( options.outputDir, selection='elZgg', var='m_ph1_ph2'  , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
        #MakeZggPlots( options.outputDir, selection='elZgg', var='pt_ph1_ph2' , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack )
    if options.electron :
        MakeElectronPlots(options.outputDir, selection='elfullhighmt', var='pt_leadph12', suffix='', ylabel='Events / bin',label_style='fancy', dumpStack=dumpStack  )
        #MakeElectronPlots(options.outputDir, selection='elfullhighmt', var='m_ph1_ph2'  , suffix='', ylabel='Events / bin',label_style='fancy', dumpStack=dumpStack  )
        #MakeElectronPlots(options.outputDir, selection='elfullhighmt', var='pt_ph1_ph2' , suffix='', ylabel='Events / bin',label_style='fancy', dumpStack=dumpStack  )
    if options.muon :
        MakeMuonPlots(options.outputDir, selection='muhighmt', var='pt_leadph12', suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack  )
        #MakeMuonPlots(options.outputDir, selection='muhighmt', var='m_ph1_ph2'  , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack  )
        #MakeMuonPlots(options.outputDir, selection='muhighmt', var='pt_ph1_ph2' , suffix='', ylabel='Events / bin', label_style='fancy', dumpStack=dumpStack  )

    dumpStack=False
    samplesWgg.deactivate_sample( 'AllBkg' )
    samplesWgg.deactivate_sample( 'ZggNoSyst')
    samplesWgg.deactivate_sample( 'OtherDiPhotonNoSyst')
    samplesWgg.deactivate_sample( 'AllBkgPlusSig')
    samplesWgg.deactivate_sample('DiTopDiPhoton')
    samplesWgg.deactivate_sample('SingleTopDiPhoton')
    samplesWgg.deactivate_sample('TriBosonDiPhoton')
    samplesWgg.deactivate_sample('TTVDiPhoton')
    samplesWgg.deactivate_sample('WWDiPhoton')
    samplesWgg.deactivate_sample('WZlvjjDiPhoton')
    samplesWgg.deactivate_sample('WZlvllDiPhoton')
    samplesWgg.deactivate_sample('WZjjllDiPhoton')
    samplesWgg.deactivate_sample('WZlvvvDiPhoton')
    samplesWgg.deactivate_sample('ZZDiPhoton')

    xlabel_ptg = 'p_{T}^{lead #gamma} [GeV]'
    xlabel_ptgg = 'p_{T}^{#gamma #gamma} [GeV]'
    xlabel_mgg = 'M_{#gamma #gamma} [GeV]'
    xlabel_mee = 'M_{ee} [GeV]'
    xlabel_mmm = 'M_{#mu#mu} [GeV]'
    xlabel_meegg = 'M_{ee#gamma#gamma} [GeV]'
    xlabel_mmmgg = 'M_{#mu#mu#gamma#gamma} [GeV]'


    selections_wgg_mu = [ 
        #------------------------------------
        # Subl pT bins
        #------------------------------------
        #{'selection' : 'muhighmt'     , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 200, 'ymax_pergev' : 100 , 'ymin_logy' : 0.1, 'ymax_logy':200   },
        #{'selection' : 'mulowmt'      , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 140, 'ymax_pergev' : 80 , 'ymin_logy' : 0.1, 'ymax_logy' :200   },

        #------------------------------------
        # Nominal pT bins
        #------------------------------------
        {'selection' : 'muhighmt'     , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 80, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'mulowmt'      , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 40, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },

        #------------------------------------
        # From OneBin 
        #------------------------------------
        #{'selection' : 'muhighmt'     , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 60, 'ymax_pergev' : 5  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'muhighmt'     , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 45, 'ymax_pergev' : 7  , 'ymin_logy' : 0.5, 'ymax_logy' :30   },
        #{'selection' : 'mulowmt'      , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 40, 'ymax_pergev' : 4  , 'ymin_logy' : 0.01, 'ymax_logy' :20   },
        #{'selection' : 'mulowmt'      , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 45, 'ymax_pergev' : 7  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
    ]

    selections_wgg_el = [ 
        #------------------------------------
        # Subl pT bins
        #------------------------------------
        #{'selection' : 'elfullhighmt' , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 140, 'ymax_pergev' : 50 , 'ymin_logy' : 0.1, 'ymax_logy' :100   },
        #{'selection' : 'elfulllowmt'  , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 100, 'ymax_pergev' : 30 , 'ymin_logy' : 0.1, 'ymax_logy' :100   },
        #{'selection' : 'ellooselowmt' , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 240, 'ymax_pergev' : 100 , 'ymin_logy' : 0.1, 'ymax_logy' :200   },
        ##{'selection' : 'elzcrhighmt'  , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 80, 'ymax_pergev' : 30 , 'ymin_logy' : 0.1, 'ymax_logy' :100   },

        #------------------------------------
        # Nominal pT bins
        #------------------------------------
        {'selection' : 'elfullhighmt' , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 50, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'elfulllowmt'  , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 50, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'ellooselowmt' , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 80, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        ##{'selection' : 'elzcrhighmt'  , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 40, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },

        #------------------------------------
        # From OneBin 
        #------------------------------------
        #{'selection' : 'elfullhighmt' , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 30, 'ymax_pergev' : 2.5, 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'elfullhighmt' , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 30, 'ymax_pergev' : 5  , 'ymin_logy' : 0.5, 'ymax_logy' :30   },
        #{'selection' : 'elfulllowmt'  , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 30, 'ymax_pergev' : 3  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'elfulllowmt'  , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 30, 'ymax_pergev' : 5  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'ellooselowmt' , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 50, 'ymax_pergev' : 5  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'ellooselowmt' , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 50, 'ymax_pergev' : 7  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        ##{'selection' : 'elzcrhighmt'  , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg  , 'ymax' : 30, 'ymax_pergev' : 5  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        ##{'selection' : 'elzcrhighmt'  , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg , 'ymax' : 20, 'ymax_pergev' : 7  , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
    ]

    selections_zgg = [
        #{'selection' : 'elZgg'        , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 60, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },
        #{'selection' : 'muZgg'        , 'var' : 'pt_leadph12' , 'xlabel' : xlabel_ptg  , 'ymax' : 60, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :20   },

        {'selection' : 'elZgg'        , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg   , 'ymax' : 40, 'ymax_pergev' : 10 , 'ymin_logy' : 0.1, 'ymax_logy' :30   },
        {'selection' : 'elZgg'        , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg  , 'ymax' : 50, 'ymax_pergev' : 13, 'ymin_logy' : 0.1, 'ymax_logy' :30   },
        {'selection' : 'elZgg'        , 'var' : 'm_leplepphph', 'xlabel' : xlabel_meegg , 'ymax' : 50, 'ymax_pergev' : 5 , 'ymin_logy' : 0.1, 'ymax_logy' :10   },
        {'selection' : 'elZgg'        , 'var' : 'm_elel'      , 'xlabel' : xlabel_mee   , 'ymax' : 50, 'ymax_pergev' : 12 , 'ymin_logy' : 0.1, 'ymax_logy' :30   },
        {'selection' : 'muZgg'        , 'var' : 'm_ph1_ph2'   , 'xlabel' : xlabel_mgg   , 'ymax' : 50, 'ymax_pergev' : 12 , 'ymin_logy' : 0.1, 'ymax_logy' :30  },
        {'selection' : 'muZgg'        , 'var' : 'pt_ph1_ph2'  , 'xlabel' : xlabel_ptgg  , 'ymax' : 60, 'ymax_pergev' : 15 , 'ymin_logy' : 0.1, 'ymax_logy' :30   },
        {'selection' : 'muZgg'        , 'var' : 'm_leplepphph', 'xlabel' : xlabel_mmmgg , 'ymax' : 60, 'ymax_pergev' : 6 , 'ymin_logy' : 0.1, 'ymax_logy' :10   },
        {'selection' : 'muZgg'        , 'var' : 'm_mumu'      , 'xlabel' : xlabel_mmm   , 'ymax' : 60, 'ymax_pergev' : 12 , 'ymin_logy' : 0.1, 'ymax_logy' :30   },
    ]

    conf_wgg_mu =  make_full_configs( selections_wgg_mu, options.outputDir, dumpStack )
    conf_wgg_el =  make_full_configs( selections_wgg_el, options.outputDir, dumpStack )
    conf_zgg    =  make_full_configs( selections_zgg   , options.outputDir, dumpStack )


    if options.aqgc :
        MakeCombinedAQGCPlots( options.outputDir, dumpStack=dumpStack )
        #MakeCombinedAQGCPlots( options.outputDir, var='m_ph1_ph2', dumpStack=dumpStack )
    elif options.money :
        if options.zgg :
            MakeCombinedMoneyPlots( options.outputDir, var='pt_ph1_ph2', dumpStack=dumpStack, zgg=options.zgg, ymax=30)
            MakeCombinedMoneyPlots( options.outputDir, var='m_ph1_ph2', dumpStack=dumpStack, zgg=options.zgg, ymax=20)
            MakeCombinedMoneyPlots( options.outputDir, var='m_leplepphph', dumpStack=dumpStack, zgg=options.zgg, ymax=130)
            #MakeCombinedMoneyPlots( options.outputDir, var='m_elel', dumpStack=dumpStack, zgg=options.zgg, ymax=130)
            #MakeCombinedMoneyPlots( options.outputDir, var='m_mumu', dumpStack=dumpStack, zgg=options.zgg, ymax=130)
        else :
            MakeCombinedMoneyPlots( options.outputDir, var='pt_ph1_ph2', dumpStack=dumpStack, zgg=options.zgg, ymax=13)
            MakeCombinedMoneyPlots( options.outputDir, var='m_ph1_ph2', dumpStack=dumpStack, zgg=options.zgg, ymax=8)

    elif options.zgg : 
        for conf in conf_zgg :
            MakeZggPlots( **conf )
    else :
        if options.electron :
            for conf in conf_wgg_el :
                MakeElectronPlots( **conf )
        if options.muon:
            for conf in conf_wgg_mu :
                MakeMuonPlots( **conf )

    print '^.^ FINSHED ^.^'
Esempio n. 24
0
def main():

    #sampManNoFilt  = SampleManager( options.baseDir, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManLepFilt = SampleManager(options.baseDirLepFilt,
                                   _TREENAME,
                                   filename=_FILENAME)

    if options.samplesConf is not None:

        #sampManNoFilt.ReadSamples( options.samplesConf )
        sampManLepFilt.ReadSamples(options.samplesConf)
    else:
        print('Must provide a sample configuration.  Exiting')
        return

    mode_cuts = {
        'electron': 'isWElDecay == 1',
        'muon': 'isWMuDecay == 1',
        'tau': 'isWTauDecay == 1',
        'tauel': 'isWTauDecay == 1 && isWTauElDecay == 1',
        'taumu': 'isWTauDecay == 1 && isWTauMuDecay == 1'
    }
    cuts_nofilt = OrderedDict()

    #cuts_nofilt  = { 'electron' : OrderedDict(), 'muon' : OrderedDict() }
    cuts_lepfilt = {'electron': OrderedDict(), 'muon': OrderedDict()}

    cuts_lepfilt['electron'][
        'pass trigger'] = 'passTrig_HLT_Ele27_eta2p1_WPTight_Gsf'
    cuts_lepfilt['muon'][
        'pass trigger'] = '(passTrig_HLT_IsoTkMu24 || passTrig_HLT_IsoMu24 )'

    cuts_lepfilt['electron']['At least one medium electron'] = 'el_n > 0'
    cuts_lepfilt['muon']['At least one tight muon'] = 'mu_n > 0'

    cuts_lepfilt['electron'][
        'Electron trigger match'] = ' Sum$( el_hasTrigMatch ) > 0 && Sum$( el_pt > 30 ) > 0'
    cuts_lepfilt['muon'][
        'Muon trigger match'] = ' Sum$( mu_hasTrigMatch ) > 0 && Sum$( mu_pt > 25 ) > 0'

    cuts_lepfilt['electron']['Second Lepton Veto'] = 'Sum$( el_pt > 10 ) == 1'
    cuts_lepfilt['muon']['Second Lepton Veto'] = 'Sum$( mu_pt > 10 ) == 1'

    cuts_lepfilt['electron'][
        'At least one Medium Photon'] = 'Sum$( ph_passMedium ) > 0'
    cuts_lepfilt['muon'][
        'At least one Medium Photon'] = 'Sum$( ph_passMedium ) > 0'

    cuts_lepfilt['electron'][
        'At least one Photon with pt $>$ 30'] = 'Sum$( ph_pt > 30 ) > 0'
    cuts_lepfilt['muon'][
        'At least one Photon with pt $>$ 30'] = 'Sum$( ph_pt > 30 ) > 0'

    cut_efficiencies = {}
    selected_samples = []

    for samp in sampManLepFilt.get_samples():

        res = re.match('ResonanceMass(\d+)_width(\d+)', samp.name)

        print(samp.name)

        if res is not None:

            width = int(res.group(2))
            mass = int(res.group(1))

            cut_efficiencies.setdefault(width, {})
            cut_efficiencies[width].setdefault(mass, {})
            selected_samples.append(samp.name)

            eff_ele = get_efficiencies(sampManLepFilt, samp.name, mode_cuts,
                                       cuts_lepfilt['electron'])
            eff_mu = get_efficiencies(sampManLepFilt, samp.name, mode_cuts,
                                      cuts_lepfilt['muon'])

            cut_efficiencies[width][mass] = {
                'muon': eff_mu,
                'electron': eff_ele
            }

    if options.outputFile is not None:

        dirpath = os.path.dirname(options.outputFile)

        if not os.path.isdir(dirpath):
            os.makedirs(dirpath)

        ofile = open(options.outputFile, 'w')

        pickle.dump(cut_efficiencies, ofile)

        ofile.close()
Esempio n. 25
0
def run_tnt(dil_path, gj_path, dil_conf, gj_conf):

    samples_dil = SampleManager(options.dil_path, 1.0, 'events')
    samples_gj = SampleManager(options.gj_path, 1.0, 'photons', 'ntuple.root')

    read_samples(samples_dil, options.dil_conf)
    read_samples(samples_gj, options.gj_conf)

    draw_command_dil_ee_incldphi_incljet = 'EventWeight * ( ( passtrig_electron ) && IsEE && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 )'
    draw_command_dil_mm_incldphi_incljet = 'EventWeight * ( ( passtrig_muon )     && IsMM && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 )'
    draw_command_dil_ee_cutdphi_incljet = 'EventWeight * ( ( passtrig_electron ) && IsEE && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && passcut_dphill )'
    draw_command_dil_mm_cutdphi_incljet = 'EventWeight * ( ( passtrig_muon )     && IsMM && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && passcut_dphill )'
    draw_command_dil_ee_incldphi_jetcut = 'EventWeight * ( ( passtrig_electron ) && IsEE && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && jet_eta25Pt25_n == 0 )'
    draw_command_dil_mm_incldphi_jetcut = 'EventWeight * ( ( passtrig_muon )     && IsMM && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && jet_eta25Pt25_n == 0 )'
    draw_command_dil_ee_cutdphi_jetcut = 'EventWeight * ( ( passtrig_electron ) && IsEE && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && jet_eta25Pt25_n == 0 && passcut_dphill )'
    draw_command_dil_mm_cutdphi_jetcut = 'EventWeight * ( ( passtrig_muon )     && IsMM && passcut_os && passcut_thirdlepveto && passcut_mll && Ptll > 25.0 && jet_eta25Pt25_n == 0 && passcut_dphill )'

    if options.distribution == 'pt':
        dil_dist = 'Ptll'
        gj_dist = 'ph_pt'

        draw_command_gj_ee_incldphi_incljet = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_ee_incldphi_jetcut = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_ee_cutdphi_incljet = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_ee_cutdphi_jetcut = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_mm_incldphi_incljet = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_mm_incldphi_jetcut = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_mm_cutdphi_incljet = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_mm_cutdphi_jetcut = 'EventWeight * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'

        binning_incljet = [
            25, 30, 40, 50, 60, 70, 80, 100, 120, 150, 200, 1000
        ]
        binning_jetcut = [25, 30, 40, 50, 60, 70, 80, 100, 150, 1000]
        binning_dphill_incljet = [
            25, 30, 35, 40, 45, 50, 55, 60, 70, 80, 100, 120, 150, 200, 1000
        ]
        binning_dphill_jetcut = [
            25, 30, 35, 40, 45, 50, 55, 60, 70, 80, 100, 150, 1000
        ]
    elif options.distribution == 'll_dphi_met':
        dil_dist = 'LL_DPhi_Met'
        gj_dist = 'ph_dphi_met'

        draw_command_gj_ee_incldphi_incljet = 'EventWeight * PtWeightEE * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_ee_incldphi_jetcut = 'EventWeight * PtWeightEE0J * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_ee_cutdphi_incljet = 'EventWeight * PtWeightDPhillEE * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_ee_cutdphi_jetcut = 'EventWeight * PtWeightDPhillEE0J * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_mm_incldphi_incljet = 'EventWeight * PtWeightMM * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_mm_incldphi_jetcut = 'EventWeight * PtWeightMM0J * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'
        draw_command_gj_mm_cutdphi_incljet = 'EventWeight * PtWeightDPhillMM * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 )'
        draw_command_gj_mm_cutdphi_jetcut = 'EventWeight * PtWeightDPhillMM0J * ( ph_pt > 25.0 && lep_n == 0 && ph_n==1 && ph_nConvTrk==0 && jet_eta25Pt25_n == 0 )'

        binning_incljet = [x * 0.01 for x in range(-315, 325, 10)]
        binning_jetcut = [x * 0.01 for x in range(-315, 330, 15)]
        binning_dphill_incljet = [x * 0.01 for x in range(-315, 345, 30)]
        binning_dphill_jetcut = [x * 0.01 for x in range(-315, 345, 30)]

    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_incldphi_incljet,
              draw_command_gj_ee_incldphi_incljet, binning_incljet,
              options.outputDir + '/AllJet/EE/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_incldphi_incljet,
              draw_command_gj_mm_incldphi_incljet, binning_incljet,
              options.outputDir + '/AllJet/MM/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_cutdphi_incljet,
              draw_command_gj_ee_cutdphi_incljet, binning_dphill_incljet,
              options.outputDir + '/DPhill_AllJet/EE/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_cutdphi_incljet,
              draw_command_gj_mm_cutdphi_incljet, binning_dphill_incljet,
              options.outputDir + '/DPhill_AllJet/MM/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_incldphi_jetcut,
              draw_command_gj_ee_incldphi_jetcut, binning_jetcut,
              options.outputDir + '/NJet0/EE/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_incldphi_jetcut,
              draw_command_gj_mm_incldphi_jetcut, binning_jetcut,
              options.outputDir + '/NJet0/MM/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_ee_cutdphi_jetcut,
              draw_command_gj_ee_cutdphi_jetcut, binning_dphill_jetcut,
              options.outputDir + '/DPhill_NJet0/EE/hist.root')
    MakeRatio(samples_dil, samples_gj, dil_dist, gj_dist,
              draw_command_dil_mm_cutdphi_jetcut,
              draw_command_gj_mm_cutdphi_jetcut, binning_dphill_jetcut,
              options.outputDir + '/DPhill_NJet0/MM/hist.root')
def main():

    global samplesLLG
    global samplesLG

    baseDirLLG = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_06_29'
    baseDirLG = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaNoPhID_2015_06_29'
    #baseDirLG   = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaJJNoPhID_2015_05_05'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConfLLG = 'Modules/Wgamgam.py'

    samplesLLG = SampleManager(baseDirLLG,
                               treename,
                               filename=filename,
                               xsFile='cross_sections/wgamgam.py',
                               lumi=19400)
    samplesLG = SampleManager(baseDirLG,
                              treename,
                              filename=filename,
                              xsFile='cross_sections/wgamgam.py',
                              lumi=19400)

    samplesLLG.ReadSamples(sampleConfLLG)
    samplesLG.ReadSamples(sampleConfLLG)

    #file_bin_map = {'ElectronFakeFitsRatio' : [(15,20), (20,25), (25,30), (30,40), (40,50), (50,70), (70, 'max')] }
    #file_bin_map_syst = {'ElectronFakeFitsRatioExpBkg' : [(15,20), (20,25), (25,30), (30,40), (40,50), (50,70), (70, 'max') ] }
    #file_bin_map = {'ElectronFakeFitsRatioMCTemplateNDKeys' : [(15,20), (20,25), (25,30), (30, 35), (35, 40), (40, 45), (45, 50), (50,60), (60,70), (70,100), (100,'max') ] }
    #file_bin_map = {'ElectronFakeFitsRatioExpBkg' : [(15,20), (20,25), (25,30), (30, 35), (35, 40), (40, 45), (45, 50), (50,60), (60,70), (70,100), (100,'max') ] }
    #file_bin_map_syst = {'ElectronFakeFitsRatioExpBkg' : [(15,20), (20,25), (25,30), (30, 35), (35, 40), (40, 45), (45, 50), (50,60), (60,70), (70,100), (100,'max')] }
    #file_bin_map = {'ElectronFakeFitsRatioMCTemplateNDKeys' : [(15,20), (20,25), (25,30), (30, 35), (35, 40), (40, 45), (45, 50), (50,60), (60,70), (70,100), (100,'max')] }
    #file_bin_map_syst = {'ElectronFakeFitsRatioMCTemplateNDKeys' : [(15,20), (20,25), (25,30), (30, 35), (35, 40), (40, 45), (45, 50), (50,60), (60,70), (70,100), (100,'max')] }
    #file_bin_map = {'ElectronFakeFitsRatio' : [(_ptbins[0], _ptbins[1]), (_ptbins[1], _ptbins[2]), (_ptbins[2], _ptbins[3]), (_ptbins[3], 'max')] }
    #file_bin_map_syst = {'ElectronFakeFitsRatioExpBkg' : [(_ptbins[0], _ptbins[1]), (_ptbins[1], _ptbins[2]), (_ptbins[2], _ptbins[3]),(_ptbins[3], 'max') ] }
    #file_bin_map = {'ElectronFakeFitsRatioMCTemplateNDKeys' : [(_ptbins[0], _ptbins[1]), (_ptbins[1], _ptbins[2]), (_ptbins[2], _ptbins[3]), (_ptbins[3], 'max')] }
    #file_bin_map = {'ElectronFakeFitsRatioMCTemplateNDKeysSubtractZgamma' : [(_ptbins[0], _ptbins[1]), (_ptbins[1], _ptbins[2]), (_ptbins[2], _ptbins[3]), (_ptbins[3], 'max')] }
    #file_bin_map_syst = {'ElectronFakeFitsRatioExpBkg' : [(_ptbins[0], _ptbins[1]), (_ptbins[1], _ptbins[2]), (_ptbins[2], _ptbins[3]),(_ptbins[3], 'max') ] }

    if options.wcr:

        suffix = ''
        path_nom = 'ElectronFakeFitsRatio%s' % suffix
        path_mctemp = 'ElectronFakeFitsRatio%sMCTemplateNDKeys' % suffix

        file_bin_map = {}
        file_bin_map_syst = {}

        # go up to the second-to-last bin
        for bidx in range(0, len(_ptbins) - 2):
            file_bin_map.setdefault(path_mctemp, []).append(
                (_ptbins[bidx], _ptbins[bidx + 1]))
            file_bin_map_syst.setdefault(path_mctemp, []).append(
                (_ptbins[bidx], _ptbins[bidx + 1]))

        # do the last bin
        file_bin_map[path_nom] = [(_ptbins[-2], 'max')]
        file_bin_map_syst[path_nom] = [(_ptbins[-2], 'max')]

        for typedir in os.listdir('%s/SinglePhotonResults' % options.baseDir):
            base_dir_ele_single = options.baseDir
            base_dir_jet_single = '%s/SinglePhotonResults/%s' % (
                options.baseDir, typedir)
            outputDirSingle = '%s/SinglePhotonWCRBackgroundEstimates/%s' % (
                options.baseDir, typedir)

            #MakeSingleJetBkgEstimate( base_dir_jet_single, channels=['elwzcr', 'elwzcrinvpixlead'],outputDir=outputDirSingle )
            #MakeSingleEleBkgEstimate( base_dir_ele_single, base_dir_jet_single, file_bin_map, file_bin_map_syst, el_selection='elw', outputDir=outputDirSingle )
            MakeSingleEleBkgEstimate(base_dir_ele_single,
                                     base_dir_jet_single,
                                     file_bin_map,
                                     file_bin_map_syst,
                                     el_selection='elwzcr',
                                     outputDir=outputDirSingle,
                                     namePostfix='__zcr')
            #MakeSingleJetBkgEstimate( base_dir_jet_single, channels=['muw'],outputDir=outputDirSingle )

            MakeSingleBkgEstimatePlots(outputDirSingle,
                                       options.plotDir,
                                       channels=['elwzcr'])
            #MakeSingleBkgEstimatePlots( outputDirSingle, options.plotDir, channels=['muw'] )

    if options.zcr:

        for typedir in os.listdir('%s/SinglePhotonResults' % options.baseDir):

            base_dir_jet_single = '%s/SinglePhotonResults/%s' % (
                options.baseDir, typedir)
            outputDirSingle = '%s/SinglePhotonZCRBackgroundEstimates/%s' % (
                options.baseDir, typedir)

            #MakeSingleJetBkgEstimate( base_dir_jet_single, channels=['mu', 'el', 'murealcr', 'elrealcr'], outputDir=outputDirSingle )
            #MakeSingleBkgEstimatePlots( outputDirSingle, options.plotDir, channels=['mu', 'el', 'murealcr', 'elrealcr'], makeEleFake=False )
            MakeSingleJetBkgEstimate(base_dir_jet_single,
                                     channels=['mu'],
                                     outputDir=outputDirSingle)
            MakeSingleBkgEstimatePlots(outputDirSingle,
                                       options.plotDir,
                                       channels=['mu'],
                                       makeEleFake=False)

    print '^_^ FINSISHED ^_^'
    print 'It is safe to kill the program if it is hanging'
Esempio n. 27
0
import ROOT
from SampleManager import SampleManager

ROOT.gROOT.SetBatch(False)

baseDir = 'root://eoscms//eos/cms/store/user/jkunkle/Wgamgam/RecoOutput_2015_04_05'

treename = 'ggNtuplizer/EventTree'
filename = 'tree.root'
sampleConf = '/afs/cern.ch/user/j/jkunkle/usercode/Plotting/Modules/LepLep.py'

samples = SampleManager(
    baseDir,
    treename,
    filename=filename,
    xsFile=
    '/afs/cern.ch/user/j/jkunkle/usercode/Plotting/cross_sections/wgamgam.py',
    lumi=19400.)

samples.ReadSamples(sampleConf)

samples.start_command_collection()

samples.Draw('el_pfiso40[0]/el_pt[0]',
             'el_n==1 && el_triggerMatch[0] && el_pt[0] > 30', (100, 0, 5))
samples.SaveStack('el_relpfiso',
                  '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST')

samples.Draw('el_pfiso40[0]/el_pt[0]',
             'el_n==1 && el_triggerMatch[0] && el_pt[0] > 30', [0, 1.5, 5])
samples.SaveStack('el_relpfiso__varBins',
Esempio n. 28
0
def main() :

    global samplesLLG
    global samplesLG

    baseDirLGG = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaGammaNoPhID_2015_11_09'
    baseDirLLG = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_11_09'
    baseDirLG  = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaNoPhID_2015_11_09'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'

    sampleConfLLG = 'Modules/ZJetsTemplates.py'

    samplesLLG     = SampleManager(baseDirLLG , treename, filename=filename, xsFile='cross_sections/wgamgam.py', lumi=19400)
    samplesLG     = SampleManager(baseDirLG , treename, filename=filename, xsFile='cross_sections/wgamgam.py', lumi=19400)
    samplesLGG     = SampleManager(baseDirLGG , treename, filename=filename, xsFile='cross_sections/wgamgam.py', lumi=19400)

    samplesLLG    .ReadSamples( sampleConfLLG )
    samplesLG    .ReadSamples( sampleConfLLG )
    samplesLGG    .ReadSamples( sampleConfLLG )

    ROOT.gROOT.SetBatch(True)

    binning = { 'sigmaIEIE'  : { 'EB' : (30, 0, 0.03), 'EE' : (30, 0, 0.09) },
                'chIsoCorr'  : { 'EB' : (30, 0, 45), 'EE' : (35, 0, 42) },
                'neuIsoCorr' : { 'EB' : (40, -2, 38), 'EE' : (30, -2, 43) },
                'phoIsoCorr' : { 'EB' : (53, -2.1, 35), 'EE' : (42, -2, 40) }
              }

    pt_bins = [(15, 25), (25,40), (40,70), (70,1000000)]

    _sieie_cuts  = { 'EB' : (0.011,0.029), 'EE' : (0.033, 0.087) }
    _chIso_cuts  = { 'EB' : (1.5, 19.5)  , 'EE' : (1.2,20.4) }
    _neuIso_cuts = { 'EB' : (1.0,20)     , 'EE' : (1.5,20.5) }
    _phoIso_cuts = { 'EB' : (0.7,20.3)   , 'EE' : (1.0,20) }

    vars = ['sigmaIEIE', 'chIsoCorr', 'phoIsoCorr']

    all_hists = []


    for var in vars :
        for eta in ['EB', 'EE'] :
            for ptmin, ptmax in pt_bins :

                draw_str_fake=None
                if var == 'sigmaIEIE' :
                    draw_str_fake = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoSIEIENoEleVeto_n==1 && ph_HoverE12[0] < 0.05 && fabs( m_leplep-91.2 ) < 5 && leadPhot_sublLepDR >1 && leadPhot_leadLepDR>1 && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %( ptmin, ptmax, eta, var, _sieie_cuts[eta][1] )
                elif var == 'chIsoCorr' :
                    draw_str_fake = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoChIsoNoEleVeto_n==1 && ph_HoverE12[0] < 0.05 && fabs( m_leplep-91.2 ) < 5 && leadPhot_sublLepDR >1 && leadPhot_leadLepDR>1  && ph_passSIEIEMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %( ptmin, ptmax, eta, var, _chIso_cuts[eta][1] )
                elif var == 'phoIsoCorr' :
                    draw_str_fake = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoPhoIsoNoEleVeto_n==1 && ph_HoverE12[0] < 0.05 && fabs( m_leplep-91.2 ) < 5 && leadPhot_sublLepDR >1 && leadPhot_leadLepDR>1  && ph_passSIEIEMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passChIsoCorrMedium[0] && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %( ptmin, ptmax, eta, var, _phoIso_cuts[eta][1] )


                samplesLLG.Draw('ph_%s[0]'%var, draw_str_fake, binning[var][eta] )


                hist_data = samplesLLG.get_samples( name='Muon' )[0]
                hist_bkg = samplesLLG.get_samples( name='Zg' )[0]

                hist_subtracted = hist_data.hist.Clone( '%s_Subtracted_%s_%d-%d' %( var, eta, ptmin, ptmax ))

                hist_subtracted.Add( hist_bkg.hist, -1 )

                all_hists.append( hist_data.hist.Clone( '%s_Data_%s_%d-%d' %( var, eta, ptmin, ptmax ) ) )
                all_hists.append( hist_bkg.hist.Clone( '%s_Zg_%s_%d-%d' %( var, eta, ptmin, ptmax ) ) )
                all_hists.append( hist_subtracted)

                draw_str_real = None
                if var=='sigmaIEIE' :
                    #draw_str_real = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoSIEIEPassCSEV_n==1  && m_elel > 40 && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0] && abs(ph_truthMatchMotherPID_ph[0]) < 25  && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _sieie_cuts[eta][1]) 
                    draw_str_real = 'mu_passtrig25_n>0 && mu_n==1 && ph_mediumNoSIEIENoEleVeto_n==1  && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0] && (fabs(ph_pt[0]-ph_truthMatchPt_ph[0])/ph_truthMatchPt_ph[0]) < 2 && (ph_truthMatchParentage_ph[0] & 4 ) == 0 && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _sieie_cuts[eta][1]) 
                elif var == 'chIsoCorr' :                                                                            
                    #draw_str_real = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoChIsoPassCSEV_n==1  && m_elel > 40 && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0] && abs(ph_truthMatchMotherPID_ph[0]) < 25  && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _chIso_cuts[eta][1]) 
                    draw_str_real = 'mu_passtrig25_n>0 && mu_n==1 && ph_mediumNoChIsoNoEleVeto_n==1  && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0] && (fabs(ph_pt[0]-ph_truthMatchPt_ph[0])/ph_truthMatchPt_ph[0]) < 2 && (ph_truthMatchParentage_ph[0] & 4 ) == 0  && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _chIso_cuts[eta][1]) 
                elif var == 'phoIsoCorr' :                                                                            
                    #draw_str_real = 'mu_passtrig25_n>0 && mu_n==2 && ph_mediumNoPhoIsoPassCSEV_n==1 && m_elel > 40 && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0] && abs(ph_truthMatchMotherPID_ph[0]) < 25  && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _phoIso_cuts[eta][1]) 
                    draw_str_real = 'mu_passtrig25_n>0 && mu_n==1 && ph_mediumNoPhoIsoNoEleVeto_n==1 && leadPhot_leadLepDR>0.4 && ph_truthMatch_ph[0]  && (fabs(ph_pt[0]-ph_truthMatchPt_ph[0])/ph_truthMatchPt_ph[0]) < 2 && (ph_truthMatchParentage_ph[0] & 4 ) == 0  && ph_pt[0] > %d && ph_pt[0] < %d && ph_Is%s[0] && ph_%s[0] < %f ' %(ptmin, ptmax,eta, var, _phoIso_cuts[eta][1]) 

                samplesLG.create_hist( 'Wg', 'ph_%s[0]' %var, draw_str_real, binning[var][eta],)

                newhist = samplesLG.get_samples( name='Wg' )[0].hist.Clone( '%s_Wg_%s_%d-%d' %( var, eta, ptmin, ptmax ) )

                all_hists.append(newhist)

    #for var in vars :
    #    for etalead in ['EB', 'EE'] :
    #        for etasubl in ['EB', 'EE'] :
    #            if etalead=='EE' and etasubl=='EE' :
    #                continue
    #            for ptmin, ptmax in pt_bins :

    #                draw_str_2d = None
    #                draw_var = None
    #                if var == 'sigmaIEIE' :
    #                    draw_str_2d = 'mu_passtrig25_n>0  && ph_HoverE12[0] < 0.05 && ph_HoverE12[1] < 0.05 && dr_ph1_ph2 > 0.4 && m_ph1_ph2 > 0.0  && ph_noSIEIEiso1299_n == 2 && chIsoCorr_leadph12 > %f && chIsoCorr_sublph12 > %f && chIsoCorr_leadph12 < 12 && chIsoCorr_sublph12 < 12 && ph_passNeuIsoCorrMedium[0] && ph_passNeuIsoCorrMedium[1] && phoIsoCorr_leadph12 > %f && phoIsoCorr_leadph12 < 9 && phoIsoCorr_sublph12 > %f && phoIsoCorr_sublph12 < 9  && is%s_leadph12 && is%s_sublph12 && pt_leadph12 > %d && pt_leadph12 < %d && sieie_leadph12 < %f && sieie_sublph12 < %f ' %( _chIso_cuts[etalead][0], _chIso_cuts[etasubl][0], _phoIso_cuts[etalead][0], _phoIso_cuts[etasubl][0], etalead, etasubl, ptmin, ptmax, _sieie_cuts[etalead][1], _sieie_cuts[etasubl][1] )
    #                    draw_var = 'sieie_sublph12:sieie_leadph12' # y:x
    #                elif var == 'chIsoCorr' :
    #                    draw_str_2d = 'mu_passtrig25_n>0  && ph_HoverE12[0] < 0.05 && ph_HoverE12[1] < 0.05 && dr_ph1_ph2 > 0.4 && m_ph1_ph2 > 0.0  && ph_n==2 && sieie_leadph12 > %f && sieie_sublph12 > %f && ph_passNeuIsoCorrMedium[0] && ph_passNeuIsoCorrMedium[1] && phoIsoCorr_leadph12 > %f && phoIsoCorr_sublph12 > %f && phoIsoCorr_leadph12 < 5 && phoIsoCorr_sublph12 < 5 && is%s_leadph12 && is%s_sublph12 && pt_leadph12 > %d && pt_leadph12 < %d && chIsoCorr_leadph12 < %f && chIsoCorr_sublph12 < %f ' %( _sieie_cuts[etalead][0], _sieie_cuts[etasubl][0], _phoIso_cuts[etalead][0], _phoIso_cuts[etasubl][0], etalead, etasubl, ptmin, ptmax, _chIso_cuts[etalead][1], _chIso_cuts[etasubl][1] )
    #                    draw_var = 'chIsoCorr_sublph12:chIsoCorr_leadph12' # y:x
    #                elif var == 'phoIsoCorr' :
    #                    draw_str_2d = 'mu_passtrig25_n>0  && ph_HoverE12[0] < 0.05 && ph_HoverE12[1] < 0.05 && dr_ph1_ph2 > 0.4 && m_ph1_ph2 > 0.0  && ph_n==2 && sieie_leadph12 > %f && sieie_sublph12 > %f && ph_passNeuIsoCorrMedium[0] && ph_passNeuIsoCorrMedium[1] && chIsoCorr_leadph12 > %f && chIsoCorr_sublph12 > %f && chIsoCorr_leadph12 < 10 && chIsoCorr_sublph12 < 10  && is%s_leadph12 && is%s_sublph12 && pt_leadph12 > %d && pt_leadph12 < %d && phoIsoCorr_leadph12 < %f && phoIsoCorr_sublph12 < %f ' %( _sieie_cuts[etalead][0], _sieie_cuts[etasubl][0], _chIso_cuts[etalead][0], _chIso_cuts[etasubl][0], etalead, etasubl, ptmin, ptmax, _phoIso_cuts[etalead][1], _phoIso_cuts[etasubl][1] )
    #                    draw_var = 'phoIsoCorr_sublph12:phoIsoCorr_leadph12' # y:x

    #                binning_2d = ( binning[var][etalead][0], binning[var][etalead][1], binning[var][etalead][2], binning[var][etasubl][0], binning[var][etasubl][1], binning[var][etasubl][2] )

    #                samplesLGG.create_hist( 'Muon', draw_var, draw_str_2d, binning_2d )
    #                newhist = samplesLGG.get_samples( name='Muon' )[0].hist.Clone( '%s_2DFakeFake_%s-%s_%d-%d' %( var, etalead, etasubl, ptmin, ptmax ) )

    #                all_hists.append(newhist)

    out_file = ROOT.TFile.Open( options.outputFile, 'RECREATE' )

    for hist in all_hists :
        hist.Write()

    out_file.Close()

    print '^_^ Finished ^_^'
Esempio n. 29
0
import ROOT
from SampleManager import SampleManager

ROOT.gROOT.SetBatch(False)

baseDir  = 'root://eoscms//eos/cms/store/user/jkunkle/Wgamgam/RecoOutput_2015_04_05'

treename = 'ggNtuplizer/EventTree'
filename = 'tree.root'
sampleConf= '/afs/cern.ch/user/j/jkunkle/usercode/Plotting/Modules/LepLep.py'

samples = SampleManager( baseDir, treename, filename=filename, xsFile='/afs/cern.ch/user/j/jkunkle/usercode/Plotting/cross_sections/wgamgam.py', lumi=19400. )

samples.ReadSamples( sampleConf )

samples.start_command_collection()

samples.Draw( 'el_pfiso40[0]/el_pt[0]', 'el_n==1 && el_triggerMatch[0] && el_pt[0] > 30', (100, 0, 5) )
samples.SaveStack( 'el_relpfiso', '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' )

samples.Draw( 'el_pfiso40[0]/el_pt[0]', 'el_n==1 && el_triggerMatch[0] && el_pt[0] > 30', [0, 1.5, 5] )
samples.SaveStack( 'el_relpfiso__varBins', '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' )
samples.DumpStack( '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' ,'el_relpfiso__varBins' )

samples.Draw( 'mu_corrIso[0]/mu_pt[0]', 'mu_n==1 && mu_triggerMatch[0] && mu_passTightNoIso[0] && mu_pt[0] > 25', (100, 0, 5) )
samples.SaveStack( 'mu_relpfiso', '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' )

samples.Draw( 'mu_corrIso[0]/mu_pt[0]', 'mu_n==1 && mu_triggerMatch[0] && mu_passTightNoIso[0] && mu_pt[0] > 25', [0, 2, 5] )
samples.SaveStack( 'mu_relpfiso__varBins', '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' )
samples.DumpStack( '/afs/cern.ch/work/j/jkunkle/private/CMS/Plots/TEST' ,'mu_relpfiso__varBins' )
Esempio n. 30
0
def main() :

    #sampManNoFilt  = SampleManager( options.baseDir, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManLepFilt = SampleManager( options.baseDirLepFilt, _TREENAME, filename=_FILENAME )

    if options.samplesConf is not None :

        #sampManNoFilt.ReadSamples( options.samplesConf )
        sampManLepFilt.ReadSamples( options.samplesConf )
    else :
        print 'Must provide a sample configuration.  Exiting'
        return


    mode_cuts = { 'electron' : 'isWElDecay == 1', 'muon' : 'isWMuDecay == 1', 'tau' : 'isWTauDecay == 1' , 'tauel' : 'isWTauDecay == 1 && isWTauElDecay == 1'  , 'taumu' : 'isWTauDecay == 1 && isWTauMuDecay == 1' }
    cuts_nofilt = OrderedDict()

    #cuts_nofilt  = { 'electron' : OrderedDict(), 'muon' : OrderedDict() }
    cuts_lepfilt = { 'electron' : OrderedDict(), 'muon' : OrderedDict() }

    cuts_lepfilt['electron']['pass trigger'] = 'passTrig_HLT_Ele27_eta2p1_WPTight_Gsf'
    cuts_lepfilt['muon']    ['pass trigger'] = '(passTrig_HLT_IsoTkMu24 || passTrig_HLT_IsoMu24 )'

    cuts_lepfilt['electron']['At least one medium electron'] = 'el_n > 0'
    cuts_lepfilt['muon']    ['At least one tight muon']      = 'mu_n > 0'

    cuts_lepfilt['electron']['Electron trigger match'] = ' Sum$( el_hasTrigMatch ) > 0 && Sum$( el_pt > 30 ) > 0'
    cuts_lepfilt['muon']    ['Muon trigger match']      = ' Sum$( mu_hasTrigMatch ) > 0 && Sum$( mu_pt > 25 ) > 0'

    cuts_lepfilt['electron']['Second Lepton Veto'] = 'Sum$( el_pt > 10 ) == 1'
    cuts_lepfilt['muon']    ['Second Lepton Veto'] = 'Sum$( mu_pt > 10 ) == 1'

    cuts_lepfilt['electron']['At least one Medium Photon'] = 'Sum$( ph_passMedium ) > 0'
    cuts_lepfilt['muon']    ['At least one Medium Photon'] = 'Sum$( ph_passMedium ) > 0'

    cuts_lepfilt['electron']['At least one Photon with pt $>$ 30'] = 'Sum$( ph_pt > 30 ) > 0'
    cuts_lepfilt['muon']    ['At least one Photon with pt $>$ 30'] = 'Sum$( ph_pt > 30 ) > 0'

    cut_efficiencies = {}
    selected_samples = []

    for samp in sampManLepFilt.get_samples() :

        res = re.match( 'ResonanceMass(\d+)_width(\d+)', samp.name )

        print samp.name

        if res is not None :

            width = int(res.group(2))
            mass  = int(res.group(1))

            cut_efficiencies.setdefault( width, {})
            cut_efficiencies[width].setdefault( mass, {} )
            selected_samples.append( samp.name )


            eff_ele = get_efficiencies( sampManLepFilt, samp.name, mode_cuts, cuts_lepfilt['electron'] )
            eff_mu  = get_efficiencies( sampManLepFilt, samp.name, mode_cuts, cuts_lepfilt['muon'] )

            cut_efficiencies[width][mass] = {'muon' : eff_mu, 'electron' : eff_ele}

    if options.outputFile is not None :

        dirpath = os.path.dirname( options.outputFile )

        if not os.path.isdir( dirpath ) :
            os.makedirs( dirpath )

        ofile = open( options.outputFile, 'w' )

        pickle.dump( cut_efficiencies, ofile )

        ofile.close()
Esempio n. 31
0
def main():

    # Parse command-line options
    from argparse import ArgumentParser
    p = ArgumentParser()

    p.add_argument('--outputDir',
                   default=None,
                   type=str,
                   dest='outputDir',
                   help='output directory for histograms')

    options = p.parse_args()

    if options.outputDir is not None:
        ROOT.gROOT.SetBatch(True)
    else:
        ROOT.gROOT.SetBatch(False)

    global sampManMMG
    global sampManMG

    base_dir_mmg = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepLepGammaNoPhID_2015_04_11'
    base_dir_mg = '/afs/cern.ch/work/j/jkunkle/public/CMS/Wgamgam/Output/LepGammaNoPhID_2015_04_11'

    treename = 'ggNtuplizer/EventTree'
    filename = 'tree.root'
    xsFile = 'cross_sections/wgamgam.py'
    lumi = 19400

    sampManMMG = SampleManager(base_dir_mmg,
                               treeName=treename,
                               filename=filename,
                               xsFile=xsFile,
                               lumi=lumi)
    sampManMG = SampleManager(base_dir_mg,
                              treeName=treename,
                              filename=filename,
                              xsFile=xsFile,
                              lumi=lumi)

    samplesConf = 'Modules/TAndPSampleConf.py'

    sampManMMG.ReadSamples(samplesConf)
    sampManMG.ReadSamples(samplesConf)

    if options.outputDir is not None:
        if not os.path.isdir(options.outputDir):
            os.makedirs(options.outputDir)

        subdir = 'PhotonEfficiencies'
        outputDir = options.outputDir + '/' + subdir

        pt_bins = [15, 20, 25, 30, 40, 50, 70]

        #eff_medium_data = GetPhotonEfficiencies( data_sample='Muon'  , numerator = 'mmg_medium', denominator='mmg_loose' , pt_bins=pt_bins, bkg_sample='DYJetsToLLPhOlap', outputDir=outputDir+'/DataLLCut' )
        eff_eveto_data = GetPhotonEfficiencies(data_sample='Muon',
                                               numerator='mmg_eveto',
                                               denominator='mmg_medium',
                                               pt_bins=pt_bins,
                                               bkg_sample='DYJetsToLLPhOlap',
                                               outputDir=outputDir +
                                               '/DataLLCut')
        #eff_medium_mc   = GetPhotonEfficiencies( data_sample='Zgamma', numerator = 'mmg_medium', denominator='mmg_loose' , pt_bins=pt_bins, bkg_sample=None, outputDir=outputDir+'/MCLLCut' )
        eff_eveto_mc = GetPhotonEfficiencies(data_sample='Zgamma',
                                             numerator='mmg_eveto',
                                             denominator='mmg_medium',
                                             pt_bins=pt_bins,
                                             bkg_sample=None,
                                             outputDir=outputDir + '/MCLLCut')

        pt_bins_high = [70]

        #eff_medium_data = GetPhotonEfficienciesHighPt( data_sample='Muon'  , numerator='mmg_medium', denominator='mmg_loose' , pt_min=pt_min_high, outputDir=outputDir+'/DataLLCut' )
        eff_eveto_data_highpt = GetPhotonEfficienciesHighPt(
            data_sample='Muon',
            numerator='mg_eveto_highpt',
            denominator='mg_medium_highpt',
            ptbins=pt_bins_high,
            useBkgEstimate=True,
            outputDir=outputDir + '/DataLLCut')
        #eff_medium_mc   = GetPhotonEfficienciesHighPt( data_sample='Zgamma', numerator='mmg_medium', denominator='mmg_loose' , pt_min=pt_min_high, outputDir=outputDir+'/MCLLCut' )
        eff_eveto_mc_highpt = GetPhotonEfficienciesHighPt(
            data_sample='Wgamma',
            numerator='mg_eveto_highpt',
            denominator='mg_medium_highpt',
            ptbins=pt_bins_high,
            useBkgEstimate=False,
            outputDir=outputDir + '/MCLLCut')

        for bin, eff in eff_eveto_data_highpt.iteritems():
            eff_eveto_data[bin] = eff
        for bin, eff in eff_eveto_mc_highpt.iteritems():
            eff_eveto_mc[bin] = eff

        print 'Eveto data '
        for bin, eff in eff_eveto_data.iteritems():
            print 'Bin = %s, eff = %s' % (bin, eff)

        print 'Eveto MC '
        for bin, eff in eff_eveto_mc.iteritems():
            print 'Bin = %s, eff = %s' % (bin, eff)

        #MakeScaleFactor( eff_medium_data, eff_medium_mc, tag='sf_medium_nom' , binning=_photon_hist_eta_pt_bins, outputDir=outputDir )
        MakeScaleFactor(eff_eveto_data,
                        eff_eveto_mc,
                        tag='sf_eveto_nom',
                        binning=_photon_hist_eta_pt_bins,
                        outputDir=outputDir)
Esempio n. 32
0
def makePhPlots(baseDir,
                sampleConf,
                outputDir=None,
                elevetoid=None,
                trig=False):

    sampMan = SampleManager(baseDir, _TREENAME, filename=_FILENAME)
    sampMan.ReadSamples(sampleConf)

    samp_name = 'Comb'

    samp = sampMan.get_samples(name=samp_name)

    if not samp:
        print('Could not find sample!')
        return

    #binning = range( 0, 50, 5) + range( 50, 500, 10 ) + range( 500, 2000, 100 )
    binning = list(range(0, 50, 5)) + list(range(50, 300, 10)) + list(
        range(300, 600, 20)) + list(range(600, 2000, 100)) + [2000, 3000]

    var = 'truephot_pt'

    name = 'PhotonEff'

    if trig:
        labels = ['Mu17_Photon30']
        colors = [ROOT.kBlack]
        selections = ['', 'passTrig_Mu17_Photon30_CaloIdL_L1ISO']
        name += 'Trig'
    elif elevetoid is None:
        labels = [
            'Container Photons', 'Loose Photons', 'Medium Photons',
            'Tight Photons'
        ]
        colors = [ROOT.kBlack, ROOT.kRed, ROOT.kGreen, ROOT.kBlue]
        selections = [
            '', 'hasTruthMatch', 'hasTruthMatch && phprobe_passLoose ',
            'hasTruthMatch && phprobe_passMedium ',
            'hasTruthMatch && phprobe_passTight '
        ]
        name += 'EleVeto%s' % elevetoid
    else:
        labels = [
            '%s Photons' % elevetoid,
            '%s Photons + CSEV' % elevetoid,
            '%s Photons + PSV' % elevetoid
        ]
        colors = [ROOT.kBlack, ROOT.kRed, ROOT.kGreen]
        selections = [
            '', 'hasTruthMatch',
            'hasTruthMatch && phprobe_pass%s && phprobe_eleVeto ' % elevetoid,
            'hasTruthMatch && phprobe_pass%s && !phprobe_hasPixSeed ' %
            elevetoid
        ]

    hists = []
    for idx, selection in enumerate(selections):
        sampMan.create_hist(samp[0], var, selection, binning)

        thissamp = sampMan.get_samples(name=samp_name)

        hists.append(thissamp[0].hist.Clone('hist_%d' % idx))

    canvas = ROOT.TCanvas(name, name)

    DrawHists(canvas, hists, colors, labels, outputDir)
Esempio n. 33
0
def main() :

    global sampManFake
    global sampManReal
    global sampManSignal

    base_dir_fake = '/data/users/jkunkle/RecoPhoton/FakePhotonProbeWithTrig_2015_11_27'
    base_dir_real = '/data/users/jkunkle/RecoPhoton/LepLepNoPhID_2015_11_26'
    base_dir_sig = '/data/users/jkunkle/RecoPhoton/LepLepNoPhID_2015_11_26'

    treeName = 'tupel/EventTree'
    xsfile = 'cross_sections/photon15.py'
    lumi = 2093.

    sampManFake   = SampleManager( base_dir_fake, treeName, filename='tree.root', xsFile=xsfile, lumi=lumi )
    sampManReal   = SampleManager( base_dir_real, treeName, filename='tree.root', xsFile=xsfile, lumi=lumi )
    sampManSignal = SampleManager( base_dir_sig, treeName, filename='tree.root', xsFile=xsfile, lumi=lumi )

    conf_fake = 'Modules/SinglePhoton15.py'
    conf_real = 'Modules/LepLep15.py'
    conf_signal = 'Modules/LepLep15.py'

    sampManFake.ReadSamples( conf_fake )
    sampManReal.ReadSamples( conf_real )
    sampManSignal.ReadSamples( conf_signal )

    channels = ['Muon',]
    #channels = ['Muon', 'Electron']


    fitvars = ['ph_chIsoCorr']
    #fitvars = ['ph_sigmaIEIE']

    # make fake photon templ

    for fv in fitvars :
        for reg in regions :

            for ptmin, ptmax in ptbins :

                fake_str_data = get_fake_draw_str( 'data', fv, reg, ptmin, ptmax )
                fake_str_mc = get_fake_draw_str( 'mc', fv, reg, ptmin, ptmax )
                draw_var_fake = get_fake_draw_var( fv )
                draw_var_real = get_real_draw_var( fv )

                real_str = get_real_draw_str( 'template', fv, reg, ptmin, ptmax )

                data_samp_fake = sampManFake.get_samples(name='SinglePhoton')[0]
                mc_samp_fake = sampManFake.get_samples(name='DiPhoton')[0]

                mc_samp_real = sampManReal.get_samples(name='Zgamma')[0]

                    
                data_template_fake = clone_sample_and_draw( data_samp_fake, draw_var_fake, fake_str_data, binnings[reg][fv],sampManFake )
                mc_template_fake = clone_sample_and_draw( mc_samp_fake, draw_var_fake, fake_str_mc, binnings[reg][fv],sampManFake )

                mc_template_real = clone_sample_and_draw( mc_samp_real, draw_var_real, real_str, binnings[reg][fv], sampManReal )

                data_template_fake.Add( mc_template_fake, -1 )

                #data_template_fake.Draw()
                #raw_input('cont')
                #mc_template_real.Draw()
                #raw_input('cont')


                for ch in channels :

                    signal_str = get_real_draw_str( 'signal', fv, reg, ptmin, ptmax, channel=ch )

                    data_samp_sig = sampManReal.get_samples(name=ch)[0]

                    sig_data = clone_sample_and_draw( data_samp_sig, draw_var_real, signal_str, binnings[reg][fv], sampManSignal )

                    xvar = ROOT.RooRealVar( 'xvar', 'xvar', 0, binnings[reg][fv][2] )

                    fakefrac = ROOT.RooRealVar( 'fakefrac', 'fakefrac', 0.5, 0., 1. )



                    sig_templatehist = ROOT.RooDataHist( 'sig_hist', 'sig_hist', ROOT.RooArgList(xvar), mc_template_real ) 
                    bkg_templatehist = ROOT.RooDataHist( 'bkg_hist', 'bkg_hist', ROOT.RooArgList(xvar), data_template_fake) 

                    sig_template = ROOT.RooHistPdf( 'sig_template', 'sig_template', ROOT.RooArgSet( xvar), sig_templatehist )
                    bkg_template = ROOT.RooHistPdf( 'bkg_template', 'bkg_template', ROOT.RooArgSet( xvar), bkg_templatehist)

                    model = ROOT.RooAddPdf( 'model', 'model', ROOT.RooArgList( sig_template, bkg_template), ROOT.RooArgList( fakefrac ) )

                    target_template = ROOT.RooDataHist( 'target_template', 'target_template', ROOT.RooArgList( xvar ), sig_data )

                    print 'RUN FIT'

                    result = model.fitTo( target_template, ROOT.RooFit.Range(0, loose_cuts[reg][fv]),ROOT.RooFit.Save()  )
                    if result is not None :
                        result.Print()
                        print 'Integral bins = 1 - %d' %(mc_template_real.FindBin(cut_values[reg][fv]))

                        print 'Predictd bkg = ', mc_template_real.Integral( 1, mc_template_real.FindBin(cut_values[reg][fv])-1 ) * fakefrac.getValV()

                    frame = xvar.frame()
                    target_template.plotOn(frame)
                    model.plotOn( frame )
                    model.plotOn( frame , ROOT.RooFit.Components('sig_template'), ROOT.RooFit.LineStyle(ROOT.kDashed))
                    model.plotOn( frame , ROOT.RooFit.Components('bkg_template'), ROOT.RooFit.LineStyle(ROOT.kDashed), ROOT.RooFit.LineColor( ROOT.kRed ) )

                    frame.Draw()
                    raw_input('cont')

                    print result
Esempio n. 34
0
def main():

    sampManMu = SampleManager(options.baseDirMu,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI)
    sampManEl = SampleManager(options.baseDirEl,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI)

    sampManMu.ReadSamples(_SAMPCONF)
    sampManEl.ReadSamples(_SAMPCONF)

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1 && ph_n==1'
    sel_base_el = 'el_pt30_n==1 && el_n==1 && ph_n==1'
    plot_var = 'mt_res'

    configs = [
        {
            'tag': 'mug',
            'sampMan': sampManMu,
            'selection': sel_base_mu
        },
        {
            'tag': 'elg',
            'sampMan': sampManEl,
            'selection': sel_base_el
        },
    ]

    sig_samples = []

    for samp in sampManMu.get_samples():
        print samp.name
        if samp.name.count('ResonanceMass') > 0:

            res = re.match(
                '(MadGraph|Pythia)ResonanceMass(\d+)_width(\w+|\d+)',
                samp.name)

            sig_samples.append(
                (samp.name, res.group(1), int(res.group(2)), res.group(3)))

    for conf in configs:

        for samp, samptype, mass, width in sig_samples:

            suffix = '_m%d_width%s' % (mass, width)

            fit_xmin = int(mass * 0.6)
            xmax = mass * 1.5
            nbins = 100

            var = ROOT.RooRealVar('m_res%s' % suffix, 'Transverse mass [GeV]',
                                  0.0, xmax)

            var.setBins(10000, 'cache')
            var.setMin('cache', -100)
            var.setMax('cache', 1500)

            if width == '0p01':
                width_factor = 0.01
            else:
                width_factor = float(width)

            #------------------------------
            # create the model
            #------------------------------

            #if width == '0p01' :
            #    #------------------------------
            #    # crystal ball, has four parameters
            #    #------------------------------
            #    cb_cut = ROOT.RooRealVar('cb_cut'      , 'Cut'  , 0.2 , 0, 2 , '')
            #    cb_sigma = ROOT.RooRealVar('cb_sigma' , 'Width', 2., 0  , 60, 'GeV')
            #    cb_power = ROOT.RooRealVar('cb_power'      , 'Power', 7.1, 0    , 100 , '')
            #    cb_m0 = ROOT.RooRealVar('cb_mass' , 'mass' , mass , mass*0.8, mass*1.2,'GeV')

            #    model = ROOT.RooCBShape('sig_model%s'%suffix, 'A  Crystal Ball Lineshape', var, cb_m0, cb_sigma,cb_cut,cb_power)
            #else :

            ##------------------------------
            ## Breit-Wigner, has two parameters, the resonance mass and the width
            #------------------------------
            bw_width_val = mass * 0.01 * width_factor
            #if bw_width_val < 2. :
            bw_width_val = 2.
            bw_m = ROOT.RooRealVar('bw_mass', 'Resonance  Mass', mass,
                                   mass * 0.8, mass * 1.2, 'GeV')
            bw_w = ROOT.RooRealVar('bw_width', 'Breit-Wigner width',
                                   bw_width_val, -100, 100, 'GeV')
            bw_m.setConstant()
            bw_w.setConstant()
            bw = ROOT.RooBreitWigner('bw%s' % suffix,
                                     'A Breit-Wigner Distribution', var, bw_m,
                                     bw_w)

            ##------------------------------
            ## Gaussian, has two parameters, the resonance mass and the width
            ##------------------------------
            #gaus_width_val = mass*0.01*width_factor
            #if gaus_width_val < 2. :
            #    gaus_width_val = 2.0
            #gaus_m = ROOT.RooRealVar('bw_mass' , 'Resonance  Mass', mass, mass*0.8, mass*1.2,'GeV')
            #gaus_w = ROOT.RooRealVar('bw_width', 'Breit-Wigner width',gaus_width_val , -100, 100,'GeV')
            #gaus_m.setConstant()
            ##gaus_w.setConstant()
            #gaus = ROOT.RooGaussian('gaus%s' %suffix,'A Gaussian Distribution', var, gaus_m,gaus_w)

            #------------------------------
            # crystal ball, has four parameters
            #------------------------------
            cb_cut = ROOT.RooRealVar('cb_cut', 'Cut', 0.2, 0, 2, '')
            cb_sigma = ROOT.RooRealVar('cb_sigma', 'Width', 2., 0, 60, 'GeV')
            cb_power = ROOT.RooRealVar('cb_power', 'Power', 7.1, 0, 100, '')
            cb_m0 = ROOT.RooRealVar('cb_mass', 'mass', 0, -200, 200, 'GeV')

            cb = ROOT.RooCBShape('cb%s' % suffix, 'A  Crystal Ball Lineshape',
                                 var, cb_m0, cb_sigma, cb_cut, cb_power)

            #------------------------------
            # FFT convolve them to make the model
            #------------------------------
            model = ROOT.RooFFTConvPdf('sig_model%s' % suffix, 'Convolution',
                                       var, bw, cb)

            #------------------------------
            # create the data histogram
            #------------------------------
            conf['sampMan'].create_hist(samp, plot_var, conf['selection'],
                                        (nbins, 0, xmax))

            hist = conf['sampMan'].get_samples(name=samp)[0].hist.Clone(
                'data_muon%s' % suffix)
            data_hist = ROOT.RooDataHist('target_data', 'target_data',
                                         ROOT.RooArgList(var), hist)

            model.fitTo(data_hist, ROOT.RooFit.Range(fit_xmin, mass * 1.3),
                        ROOT.RooFit.SumW2Error(True))

            can = ROOT.TCanvas(str(uuid.uuid4()), '')
            can.SetTitle('')

            frame = var.frame()
            frame.SetTitle('')

            data_hist.plotOn(frame)
            model.plotOn(frame)
            model.paramOn(
                frame, ROOT.RooFit.ShowConstants(True),
                ROOT.RooFit.Layout(0.1, 0.5, 0.9),
                ROOT.RooFit.Format("NEU", ROOT.RooFit.AutoPrecision(3)))

            frame.Draw()
            frame.Print()
            #if width != '0p01' :
            print 'bw_m = %f, err up = %f, err dn = %f ' % (
                bw_m.getValV(), bw_m.getErrorHi(), bw_m.getErrorLo())
            print 'bw_w = %f, err up = %f, err dn = %f ' % (
                bw_w.getValV(), bw_w.getErrorHi(), bw_w.getErrorLo())
            print 'cb_cut = %f, err up = %f, err dn = %f ' % (
                cb_cut.getValV(), cb_cut.getErrorHi(), cb_cut.getErrorLo())
            print 'cb_sigma = %f, err up = %f, err dn = %f ' % (
                cb_sigma.getValV(), cb_sigma.getErrorHi(),
                cb_sigma.getErrorLo())
            print 'cb_power = %f, err up = %f, err dn = %f ' % (
                cb_power.getValV(), cb_power.getErrorHi(),
                cb_power.getErrorLo())
            print 'cb_m0 = %f, err up = %f, err dn = %f ' % (
                cb_m0.getValV(), cb_m0.getErrorHi(), cb_m0.getErrorLo())

            #chi2 = frame.chiSquare( 'sig_model%s' %suffix, 'target_data', 4 )
            chi2 = frame.chiSquare(4)
            print 'Chi^2 = ', chi2

            chi2_text = ROOT.TLatex()
            chi2_text.SetNDC()
            chi2_text.SetText(0.12, 0.45, 'Chi^2/ndf = %.01f' % chi2)

            chi2_text.Draw()

            result_dic = {}
            result_dic['bw_m'] = (bw_m.getValV(), bw_m.getErrorHi(),
                                  bw_m.getErrorLo())
            result_dic['bw_w'] = (bw_w.getValV(), bw_w.getErrorHi(),
                                  bw_w.getErrorLo())
            result_dic['cb_cut'] = (cb_cut.getValV(), cb_cut.getErrorHi(),
                                    cb_cut.getErrorLo())
            result_dic['cb_sigma'] = (cb_sigma.getValV(),
                                      cb_sigma.getErrorHi(),
                                      cb_sigma.getErrorLo())
            result_dic['cb_power'] = (cb_power.getValV(),
                                      cb_power.getErrorHi(),
                                      cb_power.getErrorLo())
            result_dic['cb_m0'] = (cb_m0.getValV(), cb_m0.getErrorHi(),
                                   cb_m0.getErrorLo())
            result_dic['chi2'] = chi2

            if options.outputDir is not None:
                name = 'SignalFit_%s_%s_M%d_width%s' % (samptype, conf['tag'],
                                                        mass, width)
                can.SaveAs('%s/%s.pdf' % (options.outputDir, name))
                opfile = open('%s/%s.pickle' % (options.outputDir, name), 'w')
                pickle.dump(result_dic, opfile)
                opfile.close()
            else:
                raw_input("cont")
Esempio n. 35
0
def main():

    sampManMuNoG = SampleManager(options.baseDirMuNoG,
                                 _TREENAME,
                                 filename=_FILENAME,
                                 xsFile=_XSFILE,
                                 lumi=_LUMI)
    sampManElNoG = SampleManager(options.baseDirElNoG,
                                 _TREENAME,
                                 filename=_FILENAME,
                                 xsFile=_XSFILE,
                                 lumi=_LUMI)

    sampManMuNoG.ReadSamples(_SAMPCONF)
    sampManElNoG.ReadSamples(_SAMPCONF)

    sampManMuNoG.outputs = {}
    sampManElNoG.outputs = {}

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1'
    sel_base_el = 'el_pt35_n==1 && el_n==1'

    #eta_cuts = ['EB', 'EE']
    eta_cuts = ['EB']

    workspaces_to_save = {}

    xmin_m = 160
    xmax_m = 2000
    bin_width_m = 20

    xmin_pt = xmin_m / 2
    if xmin_pt < 50:
        xmin_pt = 50
    xmax_pt = xmax_m / 2
    bin_width_pt = bin_width_m / 2.

    binning_m = ((xmax_m - xmin_m) / bin_width_m, xmin_m, xmax_m)

    binning_pt = ((xmax_pt - xmin_pt) / bin_width_pt, xmin_pt, xmax_pt)

    #binning_leadjet_pt = (128, 0., 640.)
    xvar_m = ROOT.RooRealVar('x_m', 'x_m', xmin_m, xmax_m)

    xvar_pt = ROOT.RooRealVar('x_pt', 'x_pt', xmin_pt, xmax_pt)

    kine_vars = {  #'mt_incl_lepph_z' : { 'var' : 'mt_lep_met_ph'   , 'xvar' : xvar_m  , 'binning' : binning_m},
        #'m_incl_lepph_z'  : { 'var' : 'm_lep_met_ph'    , 'xvar' : xvar_m  , 'binning' : binning_m},
        'mt_fulltrans': {
            'var': 'mt_res',
            'xvar': xvar_m,
            'binning': binning_m
        },
        #'mt_constrwmass'  : { 'var' : 'recoM_lep_nu_ph' , 'xvar' : xvar_m  , 'binning' : binning_m},
        #'ph_pt'           : { 'var' : 'ph_pt[0]'        , 'xvar' : xvar_pt , 'binning' : binning_pt},
    }

    selections = {
        'base': {
            'mu': {
                'selection': sel_base_mu
            },
            #             'el' : { 'selection' : sel_base_el },
        },
        #'jetVeto' : { 'mu' : {'selection' : sel_jetveto_mu },
        #              'el' : { 'selection' : sel_jetveto_el } ,
        #            },
    }

    workspace_signal = ROOT.RooWorkspace('workspace_signal')
    workspace_wgamma = ROOT.RooWorkspace('workspace_wgamma')
    workspace_wgammalo = ROOT.RooWorkspace('workspace_wgammalo')
    workspace_top = ROOT.RooWorkspace('workspace_top')
    workspace_zgamma = ROOT.RooWorkspace('workspace_zgamma')
    wjets = ROOT.RooWorkspace('workspace_wjets')
    elefake = ROOT.RooWorkspace('elefake')

    for seltag, chdic in selections.items():

        for ch, seldic in chdic.items():

            for name, vardata in kine_vars.items():

                print('MC background k-factor calculation')
                make_kfactor_calc(sampManMuNoG,
                                  'Wjets',
                                  seldic['selection'],
                                  False,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)
                make_kfactor_calc(sampManMuNoG,
                                  'Wgamma',
                                  seldic['selection'],
                                  False,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)
                make_kfactor_calc(sampManMuNoG,
                                  'Zgamma',
                                  seldic['selection'],
                                  False,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)
                make_kfactor_calc(sampManMuNoG,
                                  'AllTop',
                                  seldic['selection'],
                                  False,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)
                make_kfactor_calc(sampManMuNoG,
                                  'Z+jets',
                                  seldic['selection'],
                                  False,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)
                make_kfactor_calc(sampManMuNoG,
                                  'Data',
                                  seldic['selection'],
                                  True,
                                  suffix='wjets_%s' % (ch),
                                  workspace=wjets)

    if options.outputDir is not None:

        wjets.writeToFile('%s/outfile_kfactor.root' % (options.outputDir))

        for fileid, ws_list in workspaces_to_save.items():
            for idx, ws in enumerate(ws_list):
                if idx == 0:
                    recreate = True
                else:
                    recreate = False

                ws.writeToFile(
                    '%s/workspace_%s.root' % (options.outputDir, fileid),
                    recreate)

        outputFile = ROOT.TFile(
            '%s/outfile_kfactor.root' % (options.outputDir), 'recreate')
        for key, can in sampManMuNoG.outputs.items():
            can.Write('%s' % (key))
        for key, can in sampManElNoG.outputs.items():
            can.Write('%s' % (key))
Esempio n. 36
0
def main():

    global samplesFF
    global samplesData

    if not options.baseDir.count('/eos/') and not os.path.isdir(
            options.baseDir):
        print 'baseDir not found!'
        return

    samplesFF = SampleManager(options.baseDir,
                              options.treeName,
                              mcweight=options.mcweight,
                              treeNameModel=options.treeNameModel,
                              filename=options.fileName,
                              base_path_model=options.baseDirModel,
                              xsFile=options.xsFile,
                              lumi=options.lumi,
                              readHists=options.readHists,
                              quiet=options.quiet)

    base_dir_data = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/LepGammaGammaNoPhID_2014_10_29'

    samplesData = SampleManager(base_dir_data,
                                options.treeName,
                                filename=options.fileName,
                                xsFile=options.xsFile,
                                lumi=options.lumi,
                                quiet=options.quiet)

    if options.samplesConf is not None:

        samplesFF.ReadSamples(options.samplesConf)
        samplesData.ReadSamples(options.samplesConf)

    #cuts_den = '!ph_passChIsoCorrMedium[0] && !ph_passNeuIsoCorrMedium[0] && !ph_passPhoIsoCorrMedium[0]  && ph_sigmaIEIE[0]>%f && ph_sigmaIEIE[0] < %f '
    #cuts_num = 'ph_passChIsoCorrMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && %s && ph_passSIEIEMedium[0] ' %(ec)

    loose_cuts = (12, 9, 9)
    #loose_cuts = (20, 15, 15)
    #loose_cuts = (1000000,1000000,1000000)

    cuts_den = 'ph_hasPixSeed[0]==0 && !ph_passNeuIsoCorrMedium[0] && !ph_passPhoIsoCorrMedium[0] && !ph_passSIEIEMedium[0] && !ph_passChIsoCorrMedium[0] && ph_chIsoCorr[0] < %d && ph_neuIsoCorr[0] < %d && ph_phoIsoCorr[0] < %d ' % (
        loose_cuts[0], loose_cuts[1], loose_cuts[2])
    cuts_num = 'ph_hasPixSeed[0]==0 && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && ph_passSIEIEMedium[0] && ph_passChIsoCorrMedium[0] && ph_HoverE12[0] < 0.05'

    regions = ['EB', 'EE']
    ptbins = [15, 25, 40, 70, 1000000]

    fake_factors = GetFakeFactors(cuts_den, cuts_num, regions, ptbins)

    #for key, val in fake_factors.iteritems() :
    #    print 'Fake factors for %s' %key
    #    val.Draw()
    #    raw_input('continue')

    #ApplySinglePhotonFF( cuts_den, sieie_cuts, eta_cuts, ptbins, fake_factors )

    gg_regions = [('EB', 'EB')]

    ApplyDiPhotonFF(loose_cuts, gg_regions, ptbins, fake_factors)
Esempio n. 37
0
def main() :

    if options.batch:
        ptbins = [0,30,40,50,60,80,1000]
        #ptbins = np.linspace(0,3.1416*4,37)
        regions = 'aABCD'
        regions = 'AB'
        if options.data: regions = 'ABD'
        with open('condor_template.jdl','r') as file1:
            filedata = file1.read()
        i=0
        for r in regions:
          for binlow,binhigh in zip(ptbins[0:-1],ptbins[1:]):
            pyoption = '%i %g %g %s' %(options.step,binlow,binhigh,r)
            if options.data: pyoption+=" --data"
            filedatawrite= filedata.replace('[REPLACE]',pyoption)
            writefilename = 'log/condor%i.jdl' %i
            with open(writefilename,'w') as file:
                file.write(filedatawrite)
            condor_command = 'condor_submit %s' %writefilename
            os.system(condor_command)
            i+=1
        return

    if options.baseDirElG ==None:
        options.baseDirElG = "/data/users/kakw/Resonances/LepGamma_elg_newblind_2018_09_23_beta/"
        options.baseDirElG = "/data2/users/kakw/Resonances2016/LepGamma_elg_2019_10_28"

    sampManElG= SampleManager( options.baseDirElG, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManElG.ReadSamples( _SAMPCONF )
    #sel_base_el = 'ph_n>=1 && el_n==1 &&!( ph_eta[0]<0&&ph_phi[0]>2.3&&ph_phi[0]<2.7)&&!(ph_phi[0]>1.2&&ph_phi[0]<1.5) '
    #sampManElG.deactivate_all_samples()
    #sampManElG.activate_sample(["Z+jets"])
    #sampManElG.get_samples(name="DYJetsToLL_M-50")[0].scale=1.

    #f1 = ROOT.TFile("%s/output.root"%(options.outputDir),"RECREATE")
#    elefake            = ROOT.RooWorkspace( 'elefake' )
    if options.step == 1:
       sampManElG.deactivate_all_samples()
       #sampManElG.activate_sample(["Z+jets","Zgamma"])
       sampManElG.activate_sample(["Z+jets"])
       sampManElG.get_samples(name="DYJetsToLL_M-50")[0].scale=1.
       #ptbins = np.linspace(0,3.1416*4)
       ptbins = [0,30,40,50,60,80,2000]
       #ptbins = [0,80,2000]
       if options.binlow:
           ptbins = [float(options.binlow), float(options.binhigh)]
       #sampManElG.closure( samp, sel_base_el,'EB', plot_var = 'm_lep_ph',varbins=[20,30,40,50,70,90,110,150,160], mode=1)
       #fitting(sampManElG,(50,80))
       #makevariableplots(sampManElG,[0,0.7,1.0,1.479,3],fitrange,basesel=base+"&&ph_pt[0]>80", tag="etaptgt80",var="abs(ph_sc_eta[0])")
       #makevariableplots(sampManElG,[0,0.7,1.0,1.479,3],fitrange,basesel=base+"&&ph_pt[0]<=80",tag="etaptlt80",var="abs(ph_sc_eta[0])")
       #makevariableplots(sampManElG,ptbins,fitrange,basesel=base+phmedium,tag="phi",var="(ph_phi[0]+3.1416+(ph_eta[0]>0)*3.1416*2)")
       makevariableplots(sampManElG,ptbins,fitrange,basesel=baseeta+phmedium,tag="all")
       #makevariableplots(sampManElG,[0,30,40,50,60,80,1000],fitrange,basesel=baseeta+passpix+ltmet,tag="regA")
       #makevariableplots(sampManElG,[0,30,40,50,60,80,1000],fitrange,basesel=baseeta+failpix+ltmet,tag="regB")
       #makevariableplots(sampManElG,[0,30,40,50,60,80,1000],fitrange,basesel=baseeta+passpix+gtmet,tag="regS")
       #makevariableplots(sampManElG,[0,30,40,50,60,80,1000],fitrange,basesel=baseeta+failpix+gtmet,tag="regD")
    elif options.step == 11:
       sampManElG.deactivate_all_samples()
       sampManElG.activate_sample(["Zgamma"])
       sampManElG.get_samples(name="ZGTo2LG")[0].scale=1.
       makevariableplots_simultaneous_zg(sampManElG,[0,30,40,50,60,80,1000],fitrange5,
               basesel=baseeta+phmedium,tag="zgamma",ic = dict(bkgd="gauszg",ext='simulzg'),dobkgd=False,donorm=False)
    elif options.step == 2:
       print "STEP 2 SIMULTANEOUS FIT"
       bkgd=["expo","gaus"]
       if options.data: doData, tbase = True, "_data"
       else: doData,tbase=False,""
       ic = dict(bkgd=["expo","gaus"],sig="dcbp2",bkgd2="gauszg2",ext="simul2")

       binvar = "ph_pt[0]"
       ptbins = [0,30,40,50,60,80,2000]
       #ptbins = [80,1000]
       ## flattened phi for both forward and backward detector. 10 degree in each bin
       #ptbins = np.linspace(0,3.1416*4,72)
       #binvar = "(ph_phi[0]+3.1416+(ph_eta[0]>0)*3.1416*2)"

       ## batch options
       if options.binlow:
           ptbins = [float(options.binlow), float(options.binhigh)]
           tbase+=options.binlow.replace('.',"p")
       if options.region: 
           doregions = options.region
       else:
           doregions = 'ABCDa'
       print 'DOregions: %s bins %f %f' %(doregions,ptbins[0],ptbins[1])
       #makevariableplots_simultaneous(sampManElG,[0,30,40,50,60,80,1000],fitrange1,basesel=baseeta,tag="all")
       #makevariableplots_simultaneous(sampManElG,[0,30,40,50,60,80,1000],fitrange2,
       #        basesel=baseeta,tag="all",ic = dict(bkgd="gaus"),maxtimes=20)
       if 'A' in doregions: makevariableplots_simultaneous(sampManElG,ptbins,fitrange4,
               basesel=baseeta+passpix+ltmet+phmedium,tag="regA"+tbase,ic = ic,maxtimes=50,doData=doData, var=binvar)
       if 'B' in doregions: makevariableplots_simultaneous(sampManElG,ptbins,fitrange4,
               basesel=baseeta+failpix+ltmet+phmedium,tag="regB"+tbase,ic = ic,maxtimes=50,doData=doData, var=binvar)
       if 'D' in doregions: makevariableplots_simultaneous(sampManElG,ptbins,fitrange4,
               basesel=baseeta+failpix+gtmet+phmedium,tag="regD"+tbase,ic = ic ,maxtimes=50,doData=doData, var=binvar)
       if not doData:
           if 'a' in doregions: makevariableplots_simultaneous(sampManElG,ptbins,fitrange4,
               basesel=baseeta              ,tag="all",ic = ic,maxtimes=50, var= binvar)
           if 'C' in doregions or 'S' in doregions:
             makevariableplots_simultaneous(sampManElG,ptbins,fitrange4,
               basesel=baseeta+passpix+gtmet+phmedium,tag="regS",ic = ic,maxtimes=50, var=binvar)
    return
Esempio n. 38
0
def main():
    print 'DEBUG:', options.dataFrame
    sampManMu = SampleManager(options.baseDirMu,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI,
                              weightHistName="weighthist",
                              dataFrame=options.dataFrame)
    sampManEl = SampleManager(options.baseDirEl,
                              _TREENAME,
                              filename=_FILENAME,
                              xsFile=_XSFILE,
                              lumi=_LUMI,
                              weightHistName="weighthist",
                              dataFrame=options.dataFrame)

    sampManMu.ReadSamples(_SAMPCONF)
    sampManEl.ReadSamples(_SAMPCONF)

    sampManMu.outputs = {}
    sampManEl.outputs = {}

    #Analysis signal region
    #val_sel_mu = 'mu_pt30_n==1 && mu_n==1 && el_n==0  && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 80 && ph_passHOverEMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0] && met_pt > 25 &&  (mt_res > 200 && mt_res < 2000 )'
    #val_sel_el = 'el_pt30_n==1 && el_n==1 && mu_n==0  && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 80 && ph_passHOverEMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0] && met_pt > 25 &&  (mt_res > 200 && mt_res < 2000 )'

    #Wgamma enriched
    val_sel_mu = 'mu_pt30_n==1 && mu_n==1 && el_n==0 && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 80 && ph_passHOverETight[0] && ph_passNeuIsoCorrTight[0] && ph_passPhoIsoCorrTight[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0] && met_pt > 40 && (m_lep_ph < 75 || m_lep_ph > 105)'
    val_sel_el = 'el_pt30_n==1 && el_n==1 && mu_n==0 && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 80 && ph_passHOverETight[0] && ph_passNeuIsoCorrTight[0] && ph_passPhoIsoCorrTight[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0] && met_pt > 40 && (m_lep_ph < 75 || m_lep_ph > 105)'

    #Zgamma enriched
    #val_sel_mu = 'mu_n==2 && m_ll < 130. && m_ll > 50. && mu_pt_rc[0] > 52. && mu_pt_rc[1] > 30. && mu_hasTrigMatch[0] && mu_passTight[0] && mu_hasTrigMatch[1] && mu_passTight[1] && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 40 && ph_passHOverETight[0] && ph_passNeuIsoCorrTight[0] && ph_passPhoIsoCorrTight[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0] && (ph_pt[0] > 40.*m_llph/150.)'
    #val_sel_el = ''

    #W+Jets enriched
    #val_sel_mu = 'mu_pt30_n==1 && mu_n==1 && mu_eta[0] > -2.4 && mu_eta[0] < 2.4 && mu_hasTrigMatch[0] && mu_passTight[0] && mt_lep_met > 50. && leadjet_pt > 30. && jet_n >= 1 && jet_eta[0] > -2.4 && jet_eta[0] < 2.4 && jet_CSVMedium_n == 0 && ph_n == 0'
    #val_sel_mu = 'mu_pt30_n==1 && mu_n==1 && el_n==0 && mu_eta[0] < 2.4 && mu_passTight[0] && mt_lep_met > 50. && ph_n==1 && ph_IsEB[0] && ph_pt[0] > 25 && ph_passHOverEMedium[0] && ph_passNeuIsoCorrMedium[0] && ph_passPhoIsoCorrMedium[0] && !ph_hasPixSeed[0] && ph_passEleVeto[0]'
    #val_sel_el = ''

    #eta_cuts = ['EB', 'EE']
    eta_cuts = ['EB']

    workspaces_to_save = {}

    selections = {
        'base': {
            'mu': {
                'selection': val_sel_mu
            },
            'el': {
                'selection': val_sel_el
            },
        },
    }

    #workspace_signal   = ROOT.RooWorkspace( 'workspace_signal' )
    #workspace_wgamma   = ROOT.RooWorkspace( 'workspace_wgamma' )
    #workspace_wgammalo = ROOT.RooWorkspace( 'workspace_wgammalo' )
    #workspace_top      = ROOT.RooWorkspace( 'workspace_top' )
    #workspace_zgamma   = ROOT.RooWorkspace( 'workspace_zgamma' )
    wjets = ROOT.RooWorkspace('workspace_wjets')
    #elefake            = ROOT.RooWorkspace( 'elefake' )

    for seltag, chdic in selections.iteritems():

        for ch, seldic in chdic.iteritems():
            for et in eta_cuts:
                if ch == 'mu':
                    print 'Jet fake rate: MC - %s' % (ch)
                    make_wjets_matrix(sampManMu,
                                      'WJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'WGamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'TTbar_DiLep',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'TTbar_SingleLep',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'Zgamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'ZJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'GJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'TTGJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManMu,
                                      'GammaGamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))

                    print 'Jet fake rate: data - %s' % (ch)
                    #make_wjets_matrix( sampManMu, 'Data', seldic['selection'], et, True, suffix='data_%s_%s' %(et,ch))
                if ch == 'el':
                    print 'Jet fake rate: MC - %s' % (ch)
                    make_wjets_matrix(sampManEl,
                                      'WJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'WGamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'TTbar_DiLep',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'TTbar_SingleLep',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'Zgamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'ZJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'GJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'TTGJets',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))
                    make_wjets_matrix(sampManEl,
                                      'GammaGamma',
                                      seldic['selection'],
                                      et,
                                      False,
                                      suffix='mc_%s_%s' % (et, ch))

                    print 'Jet fake rate: data - %s' % (ch)
                    #make_wjets_matrix( sampManEl, 'Data', seldic['selection'], et, True, suffix='data_%s_%s' %(et,ch))

    if options.outputDir is not None:

        wjets.writeToFile('%s/%s.root' % (options.outputDir, wjets.GetName()))

        #for fileid, ws_list in workspaces_to_save.iteritems() :
        #    for idx, ws in enumerate(ws_list) :
        #        if idx == 0 :
        #            recreate = True
        #        else  :
        #            recreate = False
        #        ws.writeToFile( '%s/workspace_%s.root' %( options.outputDir, fileid ), recreate )

        outputFile = ROOT.TFile(
            '%s/outfile_matrixFR_wgamma18_%s.root' %
            (options.outputDir, wjets.GetName()), 'recreate')
        for key, can in sampManMu.outputs.iteritems():
            can.Write('%s' % (key))
        for key, can in sampManEl.outputs.iteritems():
            can.Write('%s' % (key))
Esempio n. 39
0
def main() :

    sampManMu = SampleManager( options.baseDirMu, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManEl = SampleManager( options.baseDirEl, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )

    sampManMu.ReadSamples( _SAMPCONF )
    sampManEl.ReadSamples( _SAMPCONF )

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1 && ph_n==1'
    sel_base_el = 'el_pt30_n==1 && el_n==1 && ph_n==1'
    plot_var = 'mt_res'

    configs = [
                    {'tag' : 'mug', 'sampMan' : sampManMu, 'selection' : sel_base_mu },
                    {'tag' : 'elg', 'sampMan' : sampManEl, 'selection' : sel_base_el },
    ]


    sig_samples = []
    
    for samp in sampManMu.get_samples() :
        print samp.name
        if samp.name.count('ResonanceMass') > 0 :

            res = re.match('(MadGraph|Pythia)ResonanceMass(\d+)_width(\w+|\d+)', samp.name )

            sig_samples.append( ( samp.name, res.group(1), int(res.group(2)), res.group(3) ) )


    for conf in configs :

        for samp, samptype, mass, width in sig_samples :

            suffix = '_m%d_width%s' %( mass, width )

            fit_xmin = int(mass*0.6)
            xmax = mass * 1.5
            nbins = 100 

            var = ROOT.RooRealVar( 'm_res%s' %suffix, 'Transverse mass [GeV]', 0.0, xmax)
            
            var.setBins(10000,'cache')
            var.setMin('cache',-100)
            var.setMax('cache',1500)

            if width == '0p01' :
                width_factor = 0.01
            else :
                width_factor = float( width )


            #------------------------------
            # create the model
            #------------------------------

            #if width == '0p01' :
            #    #------------------------------
            #    # crystal ball, has four parameters
            #    #------------------------------
            #    cb_cut = ROOT.RooRealVar('cb_cut'      , 'Cut'  , 0.2 , 0, 2 , '')
            #    cb_sigma = ROOT.RooRealVar('cb_sigma' , 'Width', 2., 0  , 60, 'GeV')
            #    cb_power = ROOT.RooRealVar('cb_power'      , 'Power', 7.1, 0    , 100 , '')
            #    cb_m0 = ROOT.RooRealVar('cb_mass' , 'mass' , mass , mass*0.8, mass*1.2,'GeV')

            #    model = ROOT.RooCBShape('sig_model%s'%suffix, 'A  Crystal Ball Lineshape', var, cb_m0, cb_sigma,cb_cut,cb_power)
            #else :

            ##------------------------------
            ## Breit-Wigner, has two parameters, the resonance mass and the width
            #------------------------------
            bw_width_val = mass*0.01*width_factor
            #if bw_width_val < 2. :
            bw_width_val = 2.
            bw_m = ROOT.RooRealVar('bw_mass' , 'Resonance  Mass', mass, mass*0.8, mass*1.2,'GeV')
            bw_w = ROOT.RooRealVar('bw_width', 'Breit-Wigner width',bw_width_val , -100, 100,'GeV')
            bw_m.setConstant()
            bw_w.setConstant()
            bw = ROOT.RooBreitWigner('bw%s' %suffix,'A Breit-Wigner Distribution', var, bw_m,bw_w)

            ##------------------------------
            ## Gaussian, has two parameters, the resonance mass and the width
            ##------------------------------
            #gaus_width_val = mass*0.01*width_factor
            #if gaus_width_val < 2. :
            #    gaus_width_val = 2.0
            #gaus_m = ROOT.RooRealVar('bw_mass' , 'Resonance  Mass', mass, mass*0.8, mass*1.2,'GeV')
            #gaus_w = ROOT.RooRealVar('bw_width', 'Breit-Wigner width',gaus_width_val , -100, 100,'GeV')
            #gaus_m.setConstant()
            ##gaus_w.setConstant()
            #gaus = ROOT.RooGaussian('gaus%s' %suffix,'A Gaussian Distribution', var, gaus_m,gaus_w)


            #------------------------------
            # crystal ball, has four parameters
            #------------------------------
            cb_cut = ROOT.RooRealVar('cb_cut'      , 'Cut'  , 0.2 , 0, 2 , '')
            cb_sigma = ROOT.RooRealVar('cb_sigma' , 'Width', 2., 0  , 60, 'GeV')
            cb_power = ROOT.RooRealVar('cb_power'      , 'Power', 7.1, 0    , 100 , '')
            cb_m0 = ROOT.RooRealVar('cb_mass' , 'mass' , 0 , -200 , 200,'GeV')

            cb = ROOT.RooCBShape('cb%s'%suffix, 'A  Crystal Ball Lineshape', var, cb_m0, cb_sigma,cb_cut,cb_power)

            #------------------------------
            # FFT convolve them to make the model
            #------------------------------
            model = ROOT.RooFFTConvPdf('sig_model%s'%suffix,'Convolution', var, bw, cb)

            #------------------------------
            # create the data histogram
            #------------------------------
            conf['sampMan'].create_hist(samp, plot_var, conf['selection'], ( nbins, 0, xmax ) )

            hist = conf['sampMan'].get_samples(name=samp)[0].hist.Clone( 'data_muon%s' %suffix )
            data_hist = ROOT.RooDataHist( 'target_data', 'target_data', ROOT.RooArgList( var ), hist )

            model.fitTo( data_hist,ROOT.RooFit.Range(fit_xmin, mass*1.3),ROOT.RooFit.SumW2Error(True) )

            can = ROOT.TCanvas( str(uuid.uuid4()), '' )
            can.SetTitle('')

            frame = var.frame()
            frame.SetTitle('')

            data_hist.plotOn( frame )
            model.plotOn( frame )
            model.paramOn(frame, ROOT.RooFit.ShowConstants(True), ROOT.RooFit.Layout(0.1,0.5,0.9), ROOT.RooFit.Format("NEU",ROOT.RooFit.AutoPrecision(3)));

            frame.Draw()
            frame.Print()
            #if width != '0p01' :
            print 'bw_m = %f, err up = %f, err dn = %f ' %(bw_m.getValV(), bw_m.getErrorHi(), bw_m.getErrorLo() )
            print 'bw_w = %f, err up = %f, err dn = %f ' %(bw_w.getValV(), bw_w.getErrorHi(), bw_w.getErrorLo() )
            print 'cb_cut = %f, err up = %f, err dn = %f ' %(cb_cut.getValV(), cb_cut.getErrorHi(), cb_cut.getErrorLo() )
            print 'cb_sigma = %f, err up = %f, err dn = %f ' %(cb_sigma.getValV(), cb_sigma.getErrorHi(), cb_sigma.getErrorLo() )
            print 'cb_power = %f, err up = %f, err dn = %f ' %(cb_power.getValV(), cb_power.getErrorHi(), cb_power.getErrorLo() )
            print 'cb_m0 = %f, err up = %f, err dn = %f ' %(cb_m0.getValV(), cb_m0.getErrorHi(), cb_m0.getErrorLo() )

            #chi2 = frame.chiSquare( 'sig_model%s' %suffix, 'target_data', 4 )
            chi2 = frame.chiSquare(  4 )
            print 'Chi^2 = ',chi2

            chi2_text = ROOT.TLatex()
            chi2_text.SetNDC()
            chi2_text.SetText(0.12, 0.45, 'Chi^2/ndf = %.01f' %chi2 )

            chi2_text.Draw()

            result_dic = {}
            result_dic['bw_m'] = ( bw_m.getValV(), bw_m.getErrorHi(), bw_m.getErrorLo() )
            result_dic['bw_w'] = ( bw_w.getValV(), bw_w.getErrorHi(), bw_w.getErrorLo() )
            result_dic['cb_cut'] = ( cb_cut.getValV(), cb_cut.getErrorHi(), cb_cut.getErrorLo() )
            result_dic['cb_sigma'] = ( cb_sigma.getValV(), cb_sigma.getErrorHi(), cb_sigma.getErrorLo() )
            result_dic['cb_power'] = ( cb_power.getValV(), cb_power.getErrorHi(), cb_power.getErrorLo() )
            result_dic['cb_m0'] = ( cb_m0.getValV(), cb_m0.getErrorHi(), cb_m0.getErrorLo() )
            result_dic['chi2'] = chi2

            

            if options.outputDir is not None :
                name = 'SignalFit_%s_%s_M%d_width%s' %( samptype, conf['tag'], mass, width )
                can.SaveAs( '%s/%s.pdf' %( options.outputDir, name ) )
                opfile = open( '%s/%s.pickle' %(options.outputDir, name ) ,'w')
                pickle.dump( result_dic, opfile )
                opfile.close()
            else :
                raw_input("cont")
Esempio n. 40
0
def main() :

    sampManMu = SampleManager( options.baseDirMu, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManEl = SampleManager( options.baseDirEl, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManSigMu = SampleManager( options.baseDirSigMu, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )
    sampManSigEl = SampleManager( options.baseDirSigEl, _TREENAME, filename=_FILENAME, xsFile=_XSFILE, lumi=_LUMI )

    sampManMu.ReadSamples( _SAMPCONF )
    sampManEl.ReadSamples( _SAMPCONF )
    sampManSigMu.ReadSamples( _SAMPCONF )
    sampManSigEl.ReadSamples( _SAMPCONF )

    sampManMu.outputs = {}
    sampManEl.outputs = {}
    sampManSigMu.outputs = {}
    sampManSigEl.outputs = {}

    sel_base_mu = 'mu_pt30_n==1 && mu_n==1'
    sel_base_el = 'el_pt30_n==1 && el_n==1'

    eta_cuts = ['EB', 'EE']

    workspaces_to_save = {}

    xmin = 160
    xmax = 1000

    binning = ((xmax-xmin)/20, xmin, xmax)
    xvar = ROOT.RooRealVar( 'x', 'x',xmin , xmax)

    if options.doSignal : 

        workspace_signal = ROOT.RooWorkspace( 'workspace_signal' )

        make_signal_fits( sampManSigMu, sel_base_mu, eta_cuts, 'mt_lep_met_ph', workspace_signal, suffix='mu' )
        make_signal_fits( sampManSigEl, sel_base_el, eta_cuts, 'mt_lep_met_ph', workspace_signal, suffix='el' )

        workspaces_to_save['signal'] = []
        workspaces_to_save['signal'].append(workspace_signal )

    if options.doWGamma :

        workspace_wgamma = ROOT.RooWorkspace( 'workspace_wgamma' )

        wgamma_res_mu = get_wgamma_fit( sampManMu, sel_base_mu, eta_cuts, xvar, 'mt_lep_met_ph', binning, workspace_wgamma, suffix='mu' )
        wgamma_res_el = get_wgamma_fit( sampManEl, sel_base_el, eta_cuts, xvar, 'mt_lep_met_ph', binning, workspace_wgamma, suffix='el' )

        workspaces_to_save['wgamma'] = []
        workspaces_to_save['wgamma'].append(workspace_wgamma)

    if options.doWJets :

        wjets  = ROOT.RooWorkspace( 'wjets' )
        #wjets_mu_EB  = ROOT.RooWorkspace( 'wjets_mu_EB' )
        #wjets_el_EB  = ROOT.RooWorkspace( 'wjets_el_EB' )
        #wjets_mu_EE  = ROOT.RooWorkspace( 'wjets_mu_EE' )
        #wjets_el_EE  = ROOT.RooWorkspace( 'wjets_el_EE' )

        wjets_res_mu = make_wjets_fit( sampManMu, 'Data', sel_base_mu, 'EB', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='mu_EB', closure=False, workspace=wjets)
        wjets_res_el = make_wjets_fit( sampManEl, 'Data', sel_base_el, 'EB', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='el_EB', closure=False, workspace=wjets)
        #wjets_res_mu = make_wjets_fit( sampManMu, 'Data', sel_base_mu, 'EE', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='mu', closure=False, workspace=wjets_mu_EE )
        #wjets_res_el = make_wjets_fit( sampManEl, 'Data', sel_base_el, 'EE', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='el', closure=False, workspace=wjets_el_EE )

        workspaces_to_save['wjets'] = []
        workspaces_to_save['wjets'].append( wjets )

    if options.doClosure :

        closure_res_mu = make_wjets_fit( sampManMu, 'Wjets', sel_base_mu, 'EB', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='mu_EB', closure=True )
        closure_res_el = make_wjets_fit( sampManEl, 'Wjets', sel_base_el, 'EB', 'mt_lep_met_ph', 'chIso', 'sigmaIEIE', binning, xvar, suffix='el_EB', closure=True )

    if options.outputDir is not None :

        for fileid, ws_list in workspaces_to_save.iteritems() :
            for idx, ws in enumerate(ws_list) :
                if idx == 0 :
                    recreate = True
                else  :
                    recreate = False

                ws.writeToFile( '%s/workspace_%s.root' %( options.outputDir, fileid ), recreate )

        for key, can in sampManMu.outputs.iteritems() :
            print key
            can.SaveAs('%s/%s.pdf' %( options.outputDir, key ) )
        for key, can in sampManEl.outputs.iteritems() :
            can.SaveAs('%s/%s.pdf' %( options.outputDir, key ) )
        for key, can in sampManSigMu.outputs.iteritems() :
            can.SaveAs('%s/%s.pdf' %( options.outputDir, key ) )
        for key, can in sampManSigEl.outputs.iteritems() :
            can.SaveAs('%s/%s.pdf' %( options.outputDir, key ) )
Esempio n. 41
0
def main():
    print "Program start..."

    #ROOT.gROOT.ProcessLine('TFile* f_zpt = TFile::Open("results/zpt_weight.root")')
    #ROOT.gROOT.ProcessLine('TH1D* h_zpt_ratio  = (TH1D*)f_zpt->Get("h_zpt_ratio")')

    if doMuon:
        input_antiiso_data = "inputs/awmunu/input_data.txt"
        input_antiiso_wl0 = "inputs/awmunu/input_wm0.txt"
        input_antiiso_wl1 = "inputs/awmunu/input_wm1.txt"
        input_antiiso_wl2 = "inputs/awmunu/input_wm2.txt"
        input_antiiso_ttbar = "inputs/awmunu/input_ttbar_dilepton.txt"
        input_antiiso_ttbar_1lep = "inputs/awmunu/input_ttbar_singlelepton.txt"
        input_antiiso_ttbar_0lep = "inputs/awmunu/input_ttbar_hadronic.txt"
        input_antiiso_ww = "inputs/awmunu/input_ww.txt"
        input_antiiso_wz = "inputs/awmunu/input_wz.txt"
        input_antiiso_zz = "inputs/awmunu/input_zz.txt"
        input_antiiso_zxx = "inputs/awmunu/input_zxx.txt"
        input_antiiso_wx0 = "inputs/awmunu/input_wx0.txt"
        input_antiiso_wx1 = "inputs/awmunu/input_wx1.txt"
        input_antiiso_wx2 = "inputs/awmunu/input_wx2.txt"
    else:
        input_antiiso_data = "inputs/awenu/input_data.txt"
        input_antiiso_wl0 = "inputs/awenu/input_we0.txt"
        input_antiiso_wl1 = "inputs/awenu/input_we1.txt"
        input_antiiso_wl2 = "inputs/awenu/input_we2.txt"
        input_antiiso_ttbar = "inputs/awenu/input_ttbar_dilepton.txt"
        input_antiiso_ttbar_1lep = "inputs/awenu/input_ttbar_singlelepton.txt"
        input_antiiso_ttbar_0lep = "inputs/awenu/input_ttbar_hadronic.txt"
        input_antiiso_ww = "inputs/awenu/input_ww.txt"
        input_antiiso_wz = "inputs/awenu/input_wz.txt"
        input_antiiso_zz = "inputs/awenu/input_zz.txt"
        input_antiiso_zxx = "inputs/awenu/input_zxx.txt"
        input_antiiso_wx0 = "inputs/awenu/input_wx0.txt"
        input_antiiso_wx1 = "inputs/awenu/input_wx1.txt"
        input_antiiso_wx2 = "inputs/awenu/input_wx2.txt"

    ## for the QCD background estimation (data-driven)
    qcdnorm = -1.0
    DataAisoSamp = Sample(input_antiiso_data,
                          isMC=False,
                          name="Data_aiso",
                          isWSR=True,
                          additionalnorm=-1.0 * qcdnorm,
                          legend='QCD',
                          color='226')
    # W -> lnu
    Wl0AisoSamp = Sample(input_antiiso_wl0,
                         isMC=True,
                         name="wl0_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    Wl1AisoSamp = Sample(input_antiiso_wl1,
                         isMC=True,
                         name="wl1_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    Wl2AisoSamp = Sample(input_antiiso_wl2,
                         isMC=True,
                         name="wl2_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    # ttbar
    TTbarAisoSamp = Sample(input_antiiso_ttbar,
                           isMC=True,
                           name="ttbar_dilepton_aiso",
                           isWSR=True,
                           additionalnorm=-1.0 * qcdnorm)
    TT1LepAisoSamp = Sample(input_antiiso_ttbar_1lep,
                            isMC=True,
                            name="ttbar_1lepton_aiso",
                            isWSR=True,
                            additionalnorm=-1.0 * qcdnorm)
    TT0LepAisoSamp = Sample(input_antiiso_ttbar_0lep,
                            isMC=True,
                            name="ttbar_0lepton_aiso",
                            isWSR=True,
                            additionalnorm=-1.0 * qcdnorm)
    ## dibosons
    WWAisoSamp = Sample(input_antiiso_ww,
                        isMC=True,
                        name="WW_aiso",
                        isWSR=True,
                        additionalnorm=-1.0 * qcdnorm)
    WZAisoSamp = Sample(input_antiiso_wz,
                        isMC=True,
                        name="WZ_aiso",
                        isWSR=True,
                        additionalnorm=-1.0 * qcdnorm)
    ZZAisoSamp = Sample(input_antiiso_zz,
                        isMC=True,
                        name="ZZ_aiso",
                        isWSR=True,
                        additionalnorm=-1.0 * qcdnorm)
    # tau
    ZXXAisoSamp = Sample(input_antiiso_zxx,
                         isMC=True,
                         name="ZXX_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    Wx0AisoSamp = Sample(input_antiiso_wx0,
                         isMC=True,
                         name="wx0_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    Wx1AisoSamp = Sample(input_antiiso_wx1,
                         isMC=True,
                         name="wx1_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)
    Wx2AisoSamp = Sample(input_antiiso_wx2,
                         isMC=True,
                         name="wx2_aiso",
                         isWSR=True,
                         additionalnorm=-1.0 * qcdnorm)

    sampMan = SampleManager(DataAisoSamp, [
        Wl0AisoSamp, Wl1AisoSamp, Wl2AisoSamp, TTbarAisoSamp, TT1LepAisoSamp,
        TT0LepAisoSamp, WWAisoSamp, WZAisoSamp, ZZAisoSamp, ZXXAisoSamp,
        Wx0AisoSamp, Wx1AisoSamp, Wx2AisoSamp
    ])

    sampMan.groupMCs([
        "WW_aiso", "WZ_aiso", "ZZ_aiso", "ZXX_aiso", "wx0_aiso", "wx1_aiso",
        "wx2_aiso"
    ], "EWK", 216, "EWK")
    sampMan.groupMCs(
        ["ttbar_dilepton_aiso", "ttbar_1lepton_aiso", "ttbar_0lepton_aiso"],
        "ttbar", 96, "t#bar{t}")
    label = "W#rightarrow#mu#nu" if doMuon else "W#rightarrow e#nu"
    sampMan.groupMCs(['wl0_aiso', 'wl1_aiso', 'wl2_aiso'], "wlnu", 92, label)

    sampMan.DefineAll("Lep_pt", "lep.Pt()")
    sampMan.ApplyCutAll("Lep_pt > 25.0")

    sampMan.DefineAll("w_iso1", "(relIso > 0.15 && relIso < 0.30)")
    sampMan.DefineAll("w_iso2", "(relIso > 0.30 && relIso < 0.45)")
    sampMan.DefineAll("w_iso3", "(relIso > 0.45 && relIso < 0.55)")
    sampMan.DefineAll("w_iso4", "(relIso > 0.55 && relIso < 0.65)")

    # muon and electron isolation distributions are different
    # more coarse binning for electrons to make sure enough statistics
    if doMuon:
        sampMan.DefineAll("w_iso5", "(relIso > 0.20 && relIso < 0.25)")
        sampMan.DefineAll("w_iso6", "(relIso > 0.25 && relIso < 0.30)")
        sampMan.DefineAll("w_iso7", "(relIso > 0.30 && relIso < 0.35)")
        sampMan.DefineAll("w_iso8", "(relIso > 0.35 && relIso < 0.40)")
        sampMan.DefineAll("w_iso9", "(relIso > 0.40 && relIso < 0.45)")
        sampMan.DefineAll("w_iso10", "(relIso > 0.45 && relIso < 0.50)")
        sampMan.DefineAll("w_iso11", "(relIso > 0.50 && relIso < 0.55)")
        sampMan.DefineAll("w_iso12", "(relIso > 0.55 && relIso < 0.60)")
        sampMan.DefineAll("w_iso13", "(relIso > 0.60 && relIso < 0.65)")
        isobins = [
            "iso1", "iso2", "iso3", "iso4", "iso5", "iso6", "iso7", "iso8",
            "iso9", "iso10", "iso11", "iso12", "iso13"
        ]
    else:
        sampMan.DefineAll("w_iso5", "(relIso > 0.20 && relIso < 0.25)")
        sampMan.DefineAll("w_iso6", "(relIso > 0.25 && relIso < 0.30)")
        sampMan.DefineAll("w_iso7", "(relIso > 0.30 && relIso < 0.35)")
        sampMan.DefineAll("w_iso8", "(relIso > 0.35 && relIso < 0.40)")
        sampMan.DefineAll("w_iso9", "(relIso > 0.40 && relIso < 0.50)")
        sampMan.DefineAll("w_iso10", "(relIso > 0.50 && relIso < 0.70)")
        isobins = [
            "iso1", "iso2", "iso3", "iso4", "iso5", "iso6", "iso7", "iso8",
            "iso9", "iso10"
        ]

    sampMan.DefineAll("Lep_eta", "lep.Eta()")
    sampMan.DefineMC("met_pt", "metVars[1]", excludes=['Data_aiso'])
    sampMan.DefineMC("met_phi",
                     "TVector2::Phi_mpi_pi(metVarsPhi[1])",
                     excludes=['Data_aiso'])
    # Data does not run any recoil corrections
    DataAisoSamp.Define("met_pt", "metVars[0]")
    DataAisoSamp.Define("met_phi", "TVector2::Phi_mpi_pi(metVarsPhi[0])")
    sampMan.DefineAll("met_raw_pt", "metVars[0]")
    sampMan.DefineAll("met_raw_phi", "TVector2::Phi_mpi_pi(metVarsPhi[0])")

    #sampMan.DefineAll("weight_wplus", "weight_WoVpt * (q>0)", excludeGroups=['QCD'])
    #sampMan.DefineAll("weight_wminus", "weight_WoVpt * (q<0)", excludeGroups=['QCD'])
    #sampMan.DefineSpecificMCs("weight_wplus", "weight_WoVpt * (q>0)", sampgroupnames=['QCD'])
    #sampMan.DefineSpecificMCs("weight_wminus", "weight_WoVpt * (q<0)", sampgroupnames=['QCD'])
    sampMan.DefineAll("weight_wplus", "weight_WoVpt * (q>0)")
    sampMan.DefineAll("weight_wminus", "weight_WoVpt * (q<0)")

    #sampMan.DefineAll("weight_eta0to0p8",   "fabs(Lep_eta)<0.8")
    #sampMan.DefineAll("weight_eta0p8to1p4", "fabs(Lep_eta)>0.8 && fabs(Lep_eta)<1.4")
    #sampMan.DefineAll("weight_eta1p4to2",   "fabs(Lep_eta)<1.4 && fabs(Lep_eta)<2.0")
    #sampMan.DefineAll("weight_eta2to2p4",   "fabs(Lep_eta)>2.0 && fabs(Lep_eta)<2.4")

    # recoil variables
    sampMan.DefineAll("V2W", "UVec(lep.Pt(), lep.Phi(), met_pt, met_phi)")
    sampMan.DefineAll("WpT", "V2W.Mod()")
    sampMan.DefineAll("Wphi", "TVector2::Phi_mpi_pi(V2W.Phi())")

    # WpT bins
    sampMan.DefineAll("WpT_bin0", "WpT>0.0")
    sampMan.DefineAll("WpT_bin1", "WpT<8.0")
    sampMan.DefineAll("WpT_bin2", "WpT>8.0 &&  WpT<16.0")
    sampMan.DefineAll("WpT_bin3", "WpT>16.0 && WpT<24.0")
    sampMan.DefineAll("WpT_bin4", "WpT>24.0 && WpT<32.0")
    sampMan.DefineAll("WpT_bin5", "WpT>32.0 && WpT<40.0")
    sampMan.DefineAll("WpT_bin6", "WpT>40.0 && WpT<50.0")
    sampMan.DefineAll("WpT_bin7", "WpT>50.0 && WpT<70.0")
    sampMan.DefineAll("WpT_bin8", "WpT>70.0 && WpT<100.0")
    wptbins = [
        "WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5",
        "WpT_bin6", "WpT_bin7", "WpT_bin8"
    ]

    # eta bins for electrons: barral and endcap
    sampMan.DefineAll("lepEta_bin0", "1.0")
    sampMan.DefineAll("lepEta_bin1", "abs(lep.Eta()) <= 1.4442")
    sampMan.DefineAll("lepEta_bin2", "abs(lep.Eta()) > 1.4442")

    if doMuon:
        etabins = ["lepEta_bin0"]
    else:
        etabins = ["lepEta_bin0", "lepEta_bin1", "lepEta_bin2"]

    # pT_ell / mT
    sampMan.DefineAll("ptOvermT", "Lep_pt / mtCorr")

    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9', 'iso10', 'iso11', 'iso12', 'iso13']:
    for iso in isobins:
        for chg in ['WoVpt', 'wplus', 'wminus']:
            #for eta in ['0to0p8', '0p8to1p4', '1p4to2', '2to2p4']:
            #for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
            for wpt in wptbins:
                for lepeta in etabins:
                    sampMan.DefineAll(
                        "weight_{}_{}_{}_{}".format(chg, iso, wpt, lepeta),
                        "w_{} * weight_{} * {} * {}".format(
                            iso, chg, wpt, lepeta))

    met_pt_bins = np.array([
        0., 2.0, 4., 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 33, 36,
        39, 42, 45, 48, 51, 55, 60, 65, 70, 75, 80, 90, 100, 110, 120, 135,
        150, 165, 180, 200
    ])
    u1_bins = np.array([
        -40., -36., -32., -28., -25., -22.0, -20.0, -18, -16, -14, -12, -10,
        -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
        30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 53, 56, 59, 64, 68, 72, 76,
        80, 85, 90, 100
    ])
    u2_bins = np.array([
        -80., -70., -65., -60., -56., -52, -48, -44, -40, -37, -34, -31, -28,
        -25., -22., -20, -18, -16, -14, -12, -10, -8, -6, -4, -2, 0, 2, 4, 6,
        8, 10, 12, 16, 18, 20, 22, 25, 28, 31, 34, 37, 40, 44, 48, 52, 56, 60,
        65, 70, 80
    ])
    #u_bins = np.array([0., 2., 4., 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 43, 46, 49, 52, 56, 60, 64, 68, 72, 76, 80, 85, 90, 95, 100, 105, 110, 115, 120, 130, 140, 150])
    u_bins = np.concatenate((np.linspace(0, 20, 11), np.linspace(24, 60, 10)))
    phimin = -ROOT.TMath.Pi()
    phimax = ROOT.TMath.Pi()

    eta_bins = np.concatenate(
        (np.linspace(-2.4, -2.0,
                     3), np.linspace(-1.8, 1.8, 37), np.linspace(2.0, 2.4, 3)))
    pt_bins = np.concatenate(
        (np.linspace(0, 15, 6), np.linspace(17, 23, 4), np.linspace(25, 35, 6),
         np.linspace(36, 55, 20), np.linspace(57, 63,
                                              4), np.linspace(66, 70, 2),
         np.linspace(75, 100, 6)))
    mass_bins = np.concatenate(
        (np.linspace(0, 52, 14), np.linspace(55, 67,
                                             5), np.linspace(70, 76, 3),
         np.linspace(78, 86, 5), np.linspace(87, 96, 10),
         np.linspace(98, 104, 5), np.linspace(106, 110, 2)))
    u_bins = np.concatenate((np.linspace(0, 20, 11), np.linspace(24, 80, 15),
                             np.linspace(85, 109, 4), np.linspace(120, 150,
                                                                  3)))
    mt_bins = np.concatenate(
        (np.linspace(0, 20, 6), np.linspace(22, 38,
                                            9), np.linspace(40, 60, 21),
         np.linspace(62, 80, 10), np.linspace(84, 120, 10)))
    met_pt_bins = np.array([
        0., 2.0, 4., 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 33, 36,
        39, 42, 45, 48, 51, 55, 60, 65, 70, 75, 80
    ])

    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9']:
    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9', 'iso10', 'iso11', 'iso12', 'iso13']:
    for iso in isobins:
        for chg in ['WoVpt', 'wplus', 'wminus']:
            #for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
            for wpt in wptbins:
                for lepeta in etabins:
                    if chg == 'WoVpt':
                        continue
                    strname = "weight_{}_{}_{}_{}".format(
                        chg, iso, wpt, lepeta)
                    #outputname = "histo_wjetsAntiIso_mtcorr_" + strname
                    ##sampMan.cacheDraw("mtCorr", outputname, mt_bins, DrawConfig(xmin=0, xmax=120, xlabel="m_{T} [GeV]", dology=False, ymax=1.0e4), weightname = strname)
                    #sampMan.cacheDraw("mtCorr", outputname, 25, 40, 140, DrawConfig(xmin=40, xmax=140, xlabel="m_{T} [GeV]", dology=False, ymax=1e4, donormalizebin=False, addOverflow=False, addUnderflow=False, showratio=True), weightname = strname)

                    outputname = "histo_wjetsAntiIso_fullrange_mtcorr_" + strname
                    sampMan.cacheDraw("mtCorr",
                                      outputname,
                                      70,
                                      0,
                                      140,
                                      DrawConfig(xmin=0,
                                                 xmax=140,
                                                 xlabel="m_{T} [GeV]",
                                                 dology=False,
                                                 ymax=2e4,
                                                 donormalizebin=False,
                                                 addOverflow=False,
                                                 addUnderflow=False,
                                                 showratio=True),
                                      weightname=strname)
                    #outputname = "histo_wjetsAntiIso_WpTcorr_" + strname
                    #sampMan.cacheDraw("WpT", outputname, u_bins, DrawConfig(xmin=0, xmax=60, xlabel="p^{W}_{T} [GeV]", dology=False, ymax=1.0e4), weightname = strname)
                    #outputname = "histo_wjetsAntiIso_leppt_" + strname
                    #sampMan.cacheDraw("Lep_pt", outputname, pt_bins, DrawConfig(xmin=25, xmax=100, xlabel="p^{#mu}_{T} [GeV]", dology=False, ymax=1.0e4), weightname = strname)
                    #outputname = "histo_wjetsAntiIso_metpt_" + strname
                    #sampMan.cacheDraw("met_pt", outputname, met_pt_bins, DrawConfig(xmin=0, xmax=80, xlabel="PF MET [GeV]", dology=False, ymax=1e4), weightname = strname)

    sampMan.launchDraw()

    #hmts_comp = OrderedDict()
    ##for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9']:
    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9', 'iso10', 'iso11', 'iso12', 'iso13']:
    #    for chg in ['WoVpt', 'wplus', 'wminus']:
    #        for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
    #            for lepeta in etabins:
    #                if chg == "WoVpt":
    #                    continue
    #                strname = "weight_{}_{}_{}_{}".format(chg, iso, wpt, lepeta)

    #                outputname = "histo_wjetsAntiIso_mtcorr_" + strname
    #                hstacked = THStack2TH1(sampMan.hsmcs[outputname])
    #                for ibin in xrange(hstacked.GetNbinsX()+1):
    #                    # hstacked should always be above 0
    #                    hstacked.SetBinContent(ibin, max(hstacked.GetBinContent(ibin), 0))
    #                sampMan.hdatas[outputname].Add( hstacked, -1.0 )
    #                hmts_comp[strname] = sampMan.hdatas[outputname]
    #                hmts_comp[strname].SetName(outputname)

    #outfile = ROOT.TFile("output_qcdshape.root", "recreate")

    #for chg in ["wplus", "wminus"]:
    #    for i in xrange(1,13):
    #        for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
    #            iso = "iso" + str(i)
    #            iso_next = "iso" + str(i+1)
    #            strname = "weight_{}_{}_{}".format(chg, iso, wpt)
    #            strname_next = "weight_{}_{}_{}".format(chg, iso_next, wpt)

    #            outputname = "histo_wjetsAntiIso_mtcorr_" + strname

    #            hcenter = hmts_comp[strname]
    #            hup = hmts_comp[strname_next].Clone(outputname+"_shapeUp")
    #            hdown = hmts_comp[strname_next].Clone(outputname+"_shapeDown")

    #            hup.Scale(hcenter.Integral() / hup.Integral())

    #            for ibin in xrange(1, hcenter.GetNbinsX()+1):
    #                center = hcenter.GetBinContent(ibin)
    #                up = hup.GetBinContent(ibin)
    #                hdown.SetBinContent(ibin, max(2*center - up, 0))

    #                hcenter.SetBinContent(ibin, max(center, 0))
    #                hup.SetBinContent(ibin, max(up, 0))

    #            hcenter.SetDirectory(outfile)
    #            hcenter.Write()
    #            hup.SetDirectory(outfile)
    #            hup.Write()
    #            hdown.SetDirectory(outfile)
    #            hdown.Write()

    #outfile.Close()

    # repeat the same for the full mT one
    hmts_comp = OrderedDict()
    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9']:
    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9', 'iso10', 'iso11', 'iso12', 'iso13']:
    for iso in isobins:
        for chg in ['WoVpt', 'wplus', 'wminus']:
            #for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
            for wpt in wptbins:
                for lepeta in etabins:
                    if chg == "WoVpt":
                        continue
                    strname = "weight_{}_{}_{}_{}".format(
                        chg, iso, wpt, lepeta)

                    outputname = "histo_wjetsAntiIso_fullrange_mtcorr_" + strname
                    hstacked = THStack2TH1(sampMan.hsmcs[outputname])
                    for ibin in xrange(hstacked.GetNbinsX() + 1):
                        # hstacked should always be above 0
                        hstacked.SetBinContent(
                            ibin, max(hstacked.GetBinContent(ibin), 0))
                    sampMan.hdatas[outputname].Add(hstacked, -1.0)
                    hmts_comp[strname] = sampMan.hdatas[outputname]
                    hmts_comp[strname].SetName(outputname)

    lepname = "mu" if doMuon else "e"
    outfile = ROOT.TFile("output_qcdshape_fullrange_" + lepname + "nu.root",
                         "recreate")

    for chg in ["wplus", "wminus"]:
        #for i in xrange(1,13):
        #for i in xrange(1,10):
        for i in xrange(1, len(isobins)):
            #for wpt in ["WpT_bin0", "WpT_bin1", "WpT_bin2", "WpT_bin3", "WpT_bin4", "WpT_bin5", "WpT_bin6", "WpT_bin7", "WpT_bin8"]:
            for wpt in wptbins:
                for lepeta in etabins:
                    # skip iso10 as it is used for the uncertainty cal for iso9
                    iso = "iso" + str(i)
                    iso_next = "iso" + str(i + 1)
                    strname = "weight_{}_{}_{}_{}".format(
                        chg, iso, wpt, lepeta)
                    strname_next = "weight_{}_{}_{}_{}".format(
                        chg, iso_next, wpt, lepeta)

                    outputname = "histo_wjetsAntiIso_fullrange_mtcorr_" + strname

                    hcenter = hmts_comp[strname]
                    hup = hmts_comp[strname_next].Clone(outputname +
                                                        "_shapeUp")
                    hdown = hmts_comp[strname_next].Clone(outputname +
                                                          "_shapeDown")

                    hup.Scale(hcenter.Integral() / hup.Integral())

                    for ibin in xrange(1, hcenter.GetNbinsX() + 1):
                        center = hcenter.GetBinContent(ibin)
                        up = hup.GetBinContent(ibin)
                        hdown.SetBinContent(ibin, max(2 * center - up, 0))

                        hcenter.SetBinContent(ibin, max(center, 0))
                        hup.SetBinContent(ibin, max(up, 0))

                    hcenter.SetDirectory(outfile)
                    hcenter.Write()
                    hup.SetDirectory(outfile)
                    hup.Write()
                    hdown.SetDirectory(outfile)
                    hdown.Write()

    outfile.Close()

    # calculate the shape uncertainty and save them to root file
    #hmts_comp = OrderedDict()
    ##hwpts_comp = OrderedDict()
    ##hmupts_comp = OrderedDict()
    ##hmetpts_comp = OrderedDict()
    #for iso in ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso7', 'iso8', 'iso9']:
    #    for chg in ['WoVpt', 'wplus', 'wminus']:
    #        if chg == "WoVpt":
    #            continue
    #        strname = "weight_{}_{}".format(chg, iso)

    #        outputname = "histo_wjetsAntiIso_mtcorr_" + strname
    #        sampMan.hdatas[outputname].Add( THStack2TH1(sampMan.hsmcs[outputname]), -1 )
    #        hmts_comp[strname] = sampMan.hdatas[outputname]

    #outputname = "histo_wjetsAntiIso_WpTcorr_" + strname
    #sampMan.hdatas[outputname].Add( THStack2TH1(sampMan.hsmcs[outputname]), -1 )
    #hwpts_comp[strname] = sampMan.hdatas[outputname]

    #outputname = "histo_wjetsAntiIso_leppt_" + strname
    #sampMan.hdatas[outputname].Add( THStack2TH1(sampMan.hsmcs[outputname]), -1 )
    #hmupts_comp[strname] = sampMan.hdatas[outputname]

    #outputname = "histo_wjetsAntiIso_metpt_" + strname
    #sampMan.hdatas[outputname].Add( THStack2TH1(sampMan.hsmcs[outputname]), -1 )
    #hmetpts_comp[strname] = sampMan.hdatas[outputname]

    #labels = ["|#eta|<0.8", "0.8<|#eta|<1.4", "1.4<|#eta|<2.0", "2.0<|#eta|<2.4"]
    #DrawHistos(hmts_comp.values(), labels, 0, 120, 'm_{T} [GeV]', 2e-4, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_mT', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3, 4], ratiobase=1, drawoptions=["e", "e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hwpts_comp.values(), labels, 0, 60, 'p^{W}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_WpT', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3, 4], ratiobase=1, drawoptions=["e", "e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hmupts_comp.values(), labels, 25, 100, 'p^{#mu}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_mupt', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3, 4], ratiobase=1, drawoptions=["e", "e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hmetpts_comp.values(), labels, 0, 80, 'p^{miss}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_metpt', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3, 4], ratiobase=1, drawoptions=["e", "e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hmts_comp.values(), ['0.15<I<0.30', '0.30<I<0.45', '0.45<I<0.55'], 40, 120, 'm_{T} [GeV]', 2e-4, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_mT', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3], ratiobase=1, drawoptions=["e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hwpts_comp.values(), ['0.15<I<0.30', '0.30<I<0.45', '0.45<I<0.55'], 0, 60, 'p^{W}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_WpT', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3], ratiobase=1, drawoptions=["e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hmupts_comp.values(), ['0.15<I<0.30', '0.30<I<0.45', '0.45<I<0.55'], 25, 70, 'p^{#mu}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_mupt', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3], ratiobase=1, drawoptions=["e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #DrawHistos(hmetpts_comp.values(), ['0.15<I<0.30', '0.30<I<0.45', '0.45<I<0.55'], 0, 80, 'p^{W}_{T} [GeV]', 2e-3, 5e-1, 'A.U.', 'histo_wjetsAntiIso_comp_metpt', dology=True, showratio=True, donormalize=True, mycolors=[1,2,3], ratiobase=1, drawoptions=["e", "e", "e"], legendoptions=['LPE', 'LPE', 'LPE'], yrmin=0.71, yrmax=1.29)

    #sampMan.launchDraw()

    sampMan.dumpCounts()

    print "Program end..."

    raw_input()

    return
Esempio n. 42
0
def main():
    print "Program start..."

    #ROOT.gROOT.ProcessLine('TFile* f_zpt = TFile::Open("results/zpt_weight.root")')
    #ROOT.gROOT.ProcessLine('TH1D* h_zpt_ratio  = (TH1D*)f_zpt->Get("h_zpt_ratio")')

    if dotest:
        input_data = "inputs/zmumu/input_data.txt"
        input_dy = "inputs/zmumu/input_zjets.txt"
        input_ttbar = "inputs/zmumu/input_ttbar_dilepton.txt"
    else:
        input_data = "inputs/zmumu/input_data.txt"
        input_dy = "inputs/zmumu/input_zjets.txt"
        input_ttbar = "inputs/zmumu/input_ttbar_dilepton.txt"
        input_ttbar_1lep = "inputs/zmumu/input_ttbar_singlelepton.txt"
        input_ttbar_0lep = "inputs/zmumu/input_ttbar_hadronic.txt"
        input_ww = "inputs/zmumu/input_ww.txt"
        input_wz = "inputs/zmumu/input_wz.txt"
        input_zz = "inputs/zmumu/input_zz.txt"
        input_zxx = "inputs/zmumu/input_zxx.txt"

    DataSamp = Sample(input_data,
                      isMC=False,
                      legend="Data",
                      name="Data",
                      bjetVeto=VetoB)
    DYSamp = Sample(input_dy,
                    xsec=6077.22 * 1e3,
                    color=92,
                    reweightzpt=True,
                    legend="Z#rightarrow#mu#mu",
                    name="DY",
                    bjetVeto=VetoB,
                    nmcevt=311461009200.830078 / 128007. * 126620.8)
    TTbarSamp = Sample(input_ttbar,
                       xsec=831.76 * 0.105 * 1e3,
                       color=46,
                       reweightzpt=False,
                       legend="t#bar{t}",
                       name="ttbar2lep",
                       bjetVeto=VetoB,
                       nmcevt=360411094.548295 / 335.0 * 325.0)
    if not dotest:
        WWSamp = Sample(input_ww,
                        xsec=12.178 * 1e3,
                        color=38,
                        reweightzpt=False,
                        legend="WW2L",
                        name="WW",
                        bjetVeto=VetoB,
                        nmcevt=1000000.0)
        WZSamp = Sample(input_wz,
                        xsec=5.26 * 1e3,
                        color=39,
                        reweightzpt=False,
                        legend="WZ3L",
                        name="WZ",
                        bjetVeto=VetoB,
                        nmcevt=885000.00)
        ZZSamp = Sample(input_zz,
                        xsec=0.564 * 1e3,
                        color=37,
                        reweightzpt=False,
                        legend="ZZ2L",
                        name="ZZ",
                        bjetVeto=VetoB,
                        nmcevt=1000000.0)
        ZXXSamp = Sample(input_zxx,
                         xsec=1.0,
                         color=40,
                         reweightzpt=False,
                         legend="ZXX",
                         name="ZXX",
                         bjetVeto=VetoB,
                         nmcevt=3.1146101e+11)
        TT1LepSamp = Sample(input_ttbar_1lep,
                            xsec=831.76 * 0.219 * 1e3,
                            color=47,
                            reweightzpt=False,
                            legend="t#bar{t}",
                            name="ttbar1lep",
                            bjetVeto=VetoB,
                            nmcevt=1.2561491e+09 / 335.0 * 325.0)
        TT0LepSamp = Sample(input_ttbar_0lep,
                            xsec=831.76 * 0.219 * 1e3,
                            color=48,
                            reweightzpt=False,
                            legend="t#bar{t}",
                            name="ttbar0lep",
                            bjetVeto=VetoB,
                            nmcevt=6.2414786e+09 / 335.0 * 325)

    if not dotest:
        sampMan = SampleManager(DataSamp, [
            DYSamp, TTbarSamp, WWSamp, WZSamp, ZZSamp, ZXXSamp, TT1LepSamp,
            TT0LepSamp
        ])
    else:
        sampMan = SampleManager(DataSamp, [DYSamp, TTbarSamp])
    sampMan.groupMCs(["WW", "WZ", "ZZ", "ZXX"], "EWK", 216, "EWK")
    sampMan.groupMCs(["ttbar2lep", "ttbar1lep", "ttbar0lep"], "ttbar", 96,
                     "t#bar{t}")

    sampMan.DefineAll("zpt", "Z.Pt()")
    sampMan.DefineAll("zmass", "ZMass")
    sampMan.DefineAll("zy", "Z.Rapidity()")
    sampMan.DefineAll("zeta", "Z.Rapidity()")
    sampMan.DefineAll("zphi", "Z.Phi()")

    sampMan.DefineAll("urawvec", "UVec(zpt, zphi, met_raw_pt, met_raw_phi)")
    sampMan.DefineAll("uraw_pt", "urawvec.Mod()")
    sampMan.DefineAll("uraw_phi", "urawvec.Phi()")
    sampMan.DefineAll("uraw1",
                      "uraw_pt * TMath::Cos(uraw_phi + TMath::Pi() - zphi)")
    sampMan.DefineAll("uraw2",
                      "uraw_pt * TMath::Sin(uraw_phi + TMath::Pi() - zphi)")

    sampMan.DefineAll("uvec",
                      "UVec(zpt, zphi, met_corrected_pt, met_corrected_phi)")
    sampMan.DefineAll("u_pt", "uvec.Mod()")
    sampMan.DefineAll("u_phi", "uvec.Phi()")
    sampMan.DefineAll("ucor1", "u_pt * TMath::Cos(u_phi + TMath::Pi() - zphi)")
    sampMan.DefineAll("ucor2", "u_pt * TMath::Sin(u_phi + TMath::Pi() - zphi)")

    sampMan.DefineAll("nPV", "npv")

    sampMan.DefineAll("m1pt", "lep1_corr.Pt()")
    sampMan.DefineAll("m1eta", "lep1_corr.Eta()")
    sampMan.DefineAll("m2pt", "lep2_corr.Pt()")
    sampMan.DefineAll("m2eta", "lep2_corr.Eta()")

    sampMan.DefineAll("LeadMuon_pt", "(m1pt > m2pt ? m1pt : m2pt)")
    sampMan.DefineAll("LeadMuon_eta", "(m1pt > m2pt ? m1eta : m2eta)")
    sampMan.DefineAll("SubleadMuon_pt", "(m1pt > m2pt ? m2pt : m1pt)")
    sampMan.DefineAll("SubleadMuon_eta", "(m1pt > m2pt ? m2eta : m1eta)")

    #DYSamp.Define("u_pt_corr_central", "TMath::Sqrt(u1_corr_central*u1_corr_central + u2_corr_central*u2_corr_central)")
    #sampMan.DefineAll("u1_corr_central",     "u1"  , excludes=['DY'])

    met_pt_bins = np.array([
        0., 2.0, 4., 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 33, 36,
        39, 42, 45, 48, 51, 55, 60, 65, 70, 75, 80, 90, 100, 110, 120, 135,
        150, 165, 180, 200
    ])
    u1_bins = np.array([
        -20.0, -16, -12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16,
        18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 53,
        56, 59, 64, 68, 72, 76, 80, 85, 90, 100
    ])
    u2_bins = np.array([
        -40, -35, -30, -25., -22., -20, -18, -16, -14, -12, -10, -8, -6, -4,
        -2, 0, 2, 4, 6, 8, 10, 12, 16, 18, 20, 22, 25, 30, 35, 40
    ])
    #u_bins = np.array([0., 2., 4., 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 43, 46, 49, 52, 56, 60, 64, 68, 72, 76, 80, 85, 90, 95, 100, 105, 110, 115, 120, 130, 140, 150])
    phimin = -ROOT.TMath.Pi()
    phimax = ROOT.TMath.Pi()

    eta_bins = np.concatenate(
        (np.linspace(-2.4, -2.0,
                     3), np.linspace(-1.8, 1.8, 37), np.linspace(2.0, 2.4, 3)))
    pt_bins = np.concatenate((np.linspace(25, 35, 6), np.linspace(36, 55, 20),
                              np.linspace(57, 63, 4), np.linspace(66, 70, 2)))
    mass_bins = np.concatenate(
        (np.linspace(70, 76, 3), np.linspace(78, 86,
                                             5), np.linspace(87, 96, 10),
         np.linspace(98, 104, 5), np.linspace(106, 110, 2)))
    u_bins = np.concatenate((np.linspace(0, 20, 11), np.linspace(24, 80, 15),
                             np.linspace(85, 109, 4), np.linspace(120, 150,
                                                                  3)))

    # z pt befor and after pt reweighting
    sampMan.cacheDraw("zpt",
                      "histo_zjets_zpt_WoZptWeight_mumu",
                      u_bins,
                      DrawConfig(xmin=0,
                                 xmax=150,
                                 xlabel='p_{T}^{#mu#mu} [GeV]'),
                      weightname="weight_WoVpt")
    sampMan.cacheDraw("zmass", "histo_zjets_zmass_mumu", mass_bins,
                      DrawConfig(xmin=70, xmax=110, xlabel='m_{#mu#mu} [GeV]'))
    sampMan.cacheDraw(
        "zeta", "histo_zjets_zeta_mumu", eta_bins,
        DrawConfig(xmin=-2.5,
                   xmax=2.5,
                   xlabel='#eta_{#mu#mu} [GeV]',
                   ymax=1e7,
                   ylabel='Events / 1'))
    sampMan.cacheDraw(
        "zy", "histo_zjets_zrapidity_mumu", eta_bins,
        DrawConfig(xmin=-2.5,
                   xmax=2.5,
                   xlabel='y_{#mu#mu} [GeV]',
                   ymax=1e7,
                   ylabel='Events / 1'))

    sampMan.cacheDraw(
        "nPV", "histo_nPV_mumu", 10, 0, 10,
        DrawConfig(xmin=0, xmax=10, xlabel='# PV', ylabel='Events / 1'))

    sampMan.cacheDraw(
        "LeadMuon_pt", "histo_leadMuon_pt_mumu", pt_bins,
        DrawConfig(xmin=20, xmax=70, xlabel='p_{T}(Leading #mu) [GeV]'))
    sampMan.cacheDraw(
        "LeadMuon_eta", "histo_leadMuon_eta_mumu", eta_bins,
        DrawConfig(xmin=-2.6,
                   xmax=2.6,
                   xlabel='#eta (Leading #mu) [GeV]',
                   ymax=1e7,
                   ylabel='Events / 1'))
    sampMan.cacheDraw(
        "SubleadMuon_pt", "histo_subleadMuon_pt_mumu", pt_bins,
        DrawConfig(xmin=20, xmax=70, xlabel='p_{T}(Subleading #mu) [GeV]'))
    sampMan.cacheDraw(
        "SubleadMuon_eta", "histo_subleadMuon_eta_mumu", eta_bins,
        DrawConfig(xmin=-2.6,
                   xmax=2.6,
                   xlabel='#eta (Subleading #mu) [GeV]',
                   ymax=1e7,
                   ylabel='Events / 1'))

    sampMan.cacheDraw("met", "histo_zjets_mumu_pfmet_pt", met_pt_bins,
                      DrawConfig(xmin=0, xmax=100, xlabel='PF MET [GeV]'))
    sampMan.cacheDraw(
        "metPhi", "histo_zjets_mumu_pfmet_phi", 30, phimin, phimax,
        DrawConfig(xmin=phimin, xmax=phimax, xlabel='PF MET #phi'))

    sampMan.cacheDraw("met_raw_pt", "histo_zjets_mumu_pfmet_raw_pt",
                      met_pt_bins,
                      DrawConfig(xmin=0, xmax=100, xlabel='Raw PF MET [GeV]'))
    sampMan.cacheDraw(
        "met_raw_phi", "histo_zjets_mumu_pfmet_raw_phi", 30, phimin, phimax,
        DrawConfig(xmin=phimin, xmax=phimax, xlabel='Raw PF MET #phi'))

    sampMan.cacheDraw("met_wlepcorr_pt", "histo_zjets_mumu_pfmet_wlepcorr_pt",
                      met_pt_bins,
                      DrawConfig(xmin=0, xmax=100, xlabel='PF MET [GeV]'))
    sampMan.cacheDraw(
        "met_wlepcorr_phi", "histo_zjets_mumu_pfmet_wlepcorr_phi", 30, phimin,
        phimax, DrawConfig(xmin=phimin, xmax=phimax, xlabel='PF MET #phi'))

    sampMan.cacheDraw("met_corrected_pt",
                      "histo_zjets_mumu_pfmet_corrected_pt", met_pt_bins,
                      DrawConfig(xmin=0, xmax=100, xlabel='PF MET [GeV]'))
    sampMan.cacheDraw(
        "met_corrected_phi", "histo_zjets_mumu_pfmet_corrected_phi", 30,
        phimin, phimax,
        DrawConfig(xmin=phimin, xmax=phimax, xlabel='PF MET #phi'))

    sampMan.cacheDraw(
        "uraw1", "histo_zjets_mumu_pfmet_uraw1_pt", u1_bins,
        DrawConfig(xmin=-20.0,
                   xmax=100.0,
                   xlabel="Raw u_{#parallel} [GeV]",
                   extraText='#mu#mu channel'))
    sampMan.cacheDraw(
        "uraw2", "histo_zjets_mumu_pfmet_uraw2_pt", u2_bins,
        DrawConfig(xmin=-30.0,
                   xmax=30.0,
                   xlabel="Raw u_{#perp  } [GeV]",
                   extraText='#mu#mu channel'))

    sampMan.cacheDraw(
        "ucor1", "histo_zjets_mumu_pfmet_ucor1_pt", u1_bins,
        DrawConfig(xmin=-20.0,
                   xmax=100.0,
                   xlabel="u_{#parallel} [GeV]",
                   extraText='#mu#mu channel'))
    sampMan.cacheDraw(
        "ucor2", "histo_zjets_mumu_pfmet_ucor2_pt", u2_bins,
        DrawConfig(xmin=-30.0,
                   xmax=30.0,
                   xlabel="u_{#perp  } [GeV]",
                   extraText='#mu#mu channel'))

    sampMan.launchDraw()

    sampMan.dumpCounts()

    print "Program end..."

    raw_input()

    return