Example #1
0
def main():

    basedir="/disk1/erdweg/television/SIGNAL/merged/"
    # lumi=19712

    # xs= ConfigObj("/disk1/erdweg/plotting/xs_Phys14.cfg")
    # bghists=HistStorage(xs,lumi,path=basedir,isData=True)

    colors = ['lime', 'deepskyblue', 'magenta', 'orangered']

    bglist=OrderedDict()

    bglist = [
     'RPVresonantToEMu_M-200_LLE_LQD-001_13TeV_CA-skimid1965',
     'RPVresonantToEMu_M-300_LLE_LQD-001_13TeV_CA-skimid1829',
     'RPVresonantToEMu_M-400_LLE_LQD-001_13TeV_CA-skimid1954',
     'RPVresonantToEMu_M-500_LLE_LQD-001_13TeV_CA-skimid1827',
     'RPVresonantToEMu_M-600_LLE_LQD-001_13TeV_CA-skimid1888',
     'RPVresonantToEMu_M-700_LLE_LQD-001_13TeV_CA-skimid1884',
     'RPVresonantToEMu_M-800_LLE_LQD-001_13TeV_CA-skimid1935',
     'RPVresonantToEMu_M-900_LLE_LQD-001_13TeV_CA-skimid1966',
     'RPVresonantToEMu_M-1000_LLE_LQD-001_13TeV_CA-skimid1891',
     'RPVresonantToEMu_M-1200_LLE_LQD-001_13TeV_CA-skimid1892',
     'RPVresonantToEMu_M-1400_LLE_LQD-001_13TeV_CA-skimid1857',
     'RPVresonantToEMu_M-1600_LLE_LQD-001_13TeV_CA-skimid1859',
     'RPVresonantToEMu_M-1800_LLE_LQD-001_13TeV_CA-skimid1834',
     'RPVresonantToEMu_M-2000_LLE_LQD-001_13TeV_CA-skimid1831',
     'RPVresonantToEMu_M-2500_LLE_LQD-001_13TeV_CA-skimid1974',
     'RPVresonantToEMu_M-3000_LLE_LQD-01_13TeV_CA-skimid1835',
     'RPVresonantToEMu_M-3000_LLE_LQD-001_13TeV_CA-skimid1960',
     'RPVresonantToEMu_M-3500_LLE_LQD-001_13TeV_CA-skimid1889',
     'RPVresonantToEMu_M-3500_LLE_LQD-01_13TeV_CA-skimid2064',
     'RPVresonantToEMu_M-4000_LLE_LQD-001_13TeV_CA-skimid1833',
     'RPVresonantToEMu_M-4000_LLE_LQD-01_13TeV_CA-skimid1984',
     'RPVresonantToEMu_M-4000_LLE_LQD-02_13TeV_CA-skimid1929',
     'RPVresonantToEMu_M-4000_LLE_LQD-05_13TeV_CA-skimid1976',
     'RPVresonantToEMu_M-4500_LLE_LQD-001_13TeV_CA-skimid1832',
     'RPVresonantToEMu_M-4500_LLE_LQD-02_13TeV_CA-skimid1964',
     'RPVresonantToEMu_M-4500_LLE_LQD-05_13TeV_CA-skimid1977',
     'RPVresonantToEMu_M-5000_LLE_LQD-001_13TeV_CA-skimid1983',
     'RPVresonantToEMu_M-5000_LLE_LQD-02_13TeV_CA-skimid1975',
     'RPVresonantToEMu_M-5000_LLE_LQD-05_13TeV_CA-skimid1828',
     'RPVresonantToEMu_M-5500_LLE_LQD-001_13TeV_CA-skimid1869',
     'RPVresonantToEMu_M-5500_LLE_LQD-02_13TeV_CA-skimid1858',
     'RPVresonantToEMu_M-5500_LLE_LQD-05_13TeV_CA-skimid1830',
     'RPVresonantToEMu_M-6000_LLE_LQD-001_13TeV_CA-skimid1887',
     'RPVresonantToEMu_M-6000_LLE_LQD-02_13TeV_CA-skimid1927',
     'RPVresonantToEMu_M-6000_LLE_LQD-05_13TeV_CA-skimid1890',
     'RPVresonantToEMu_M-6500_LLE_LQD-001_13TeV_CA-skimid1967',
     'RPVresonantToEMu_M-6500_LLE_LQD-02_13TeV_CA-skimid1873',
     'RPVresonantToEMu_M-6500_LLE_LQD-05_13TeV_CA-skimid1886',
    ]

    colorList={}
    colorList['RPVresonantToEMu_M-200_LLE_LQD-001_13TeV_CA-skimid1965'] = 'lightblue'
    colorList['RPVresonantToEMu_M-300_LLE_LQD-001_13TeV_CA-skimid1829'] = 'lightblue'
    colorList['RPVresonantToEMu_M-400_LLE_LQD-001_13TeV_CA-skimid1954'] = 'lightblue'
    colorList['RPVresonantToEMu_M-500_LLE_LQD-001_13TeV_CA-skimid1827'] = 'lightblue'
    colorList['RPVresonantToEMu_M-600_LLE_LQD-001_13TeV_CA-skimid1888'] = 'lightblue'
    colorList['RPVresonantToEMu_M-700_LLE_LQD-001_13TeV_CA-skimid1884'] = 'lightblue'
    colorList['RPVresonantToEMu_M-800_LLE_LQD-001_13TeV_CA-skimid1935'] = 'lightblue'
    colorList['RPVresonantToEMu_M-900_LLE_LQD-001_13TeV_CA-skimid1966'] = 'lightblue'
    colorList['RPVresonantToEMu_M-1000_LLE_LQD-001_13TeV_CA-skimid1891'] = 'lightblue'
    colorList['RPVresonantToEMu_M-1200_LLE_LQD-001_13TeV_CA-skimid1892'] = 'lightblue'
    colorList['RPVresonantToEMu_M-1400_LLE_LQD-001_13TeV_CA-skimid1857'] = 'lightblue'
    colorList['RPVresonantToEMu_M-1600_LLE_LQD-001_13TeV_CA-skimid1859'] = 'lightblue'
    colorList['RPVresonantToEMu_M-1800_LLE_LQD-001_13TeV_CA-skimid1834'] = 'lightblue'
    colorList['RPVresonantToEMu_M-2000_LLE_LQD-001_13TeV_CA-skimid1831'] = 'lightblue'
    colorList['RPVresonantToEMu_M-2500_LLE_LQD-001_13TeV_CA-skimid1974'] = 'lightblue'
    colorList['RPVresonantToEMu_M-3000_LLE_LQD-01_13TeV_CA-skimid1835'] = 'lightblue'
    colorList['RPVresonantToEMu_M-3000_LLE_LQD-001_13TeV_CA-skimid1960'] = 'lightblue'
    colorList['RPVresonantToEMu_M-3500_LLE_LQD-001_13TeV_CA-skimid1889'] = 'lightblue'
    colorList['RPVresonantToEMu_M-3500_LLE_LQD-01_13TeV_CA-skimid2064'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4000_LLE_LQD-001_13TeV_CA-skimid1833'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4000_LLE_LQD-01_13TeV_CA-skimid1984'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4000_LLE_LQD-02_13TeV_CA-skimid1929'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4000_LLE_LQD-05_13TeV_CA-skimid1976'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4500_LLE_LQD-001_13TeV_CA-skimid1832'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4500_LLE_LQD-02_13TeV_CA-skimid1964'] = 'lightblue'
    colorList['RPVresonantToEMu_M-4500_LLE_LQD-05_13TeV_CA-skimid1977'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5000_LLE_LQD-001_13TeV_CA-skimid1983'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5000_LLE_LQD-02_13TeV_CA-skimid1975'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5000_LLE_LQD-05_13TeV_CA-skimid1828'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5500_LLE_LQD-001_13TeV_CA-skimid1869'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5500_LLE_LQD-02_13TeV_CA-skimid1858'] = 'lightblue'
    colorList['RPVresonantToEMu_M-5500_LLE_LQD-05_13TeV_CA-skimid1830'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6000_LLE_LQD-001_13TeV_CA-skimid1887'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6000_LLE_LQD-02_13TeV_CA-skimid1927'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6000_LLE_LQD-05_13TeV_CA-skimid1890'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6500_LLE_LQD-001_13TeV_CA-skimid1967'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6500_LLE_LQD-02_13TeV_CA-skimid1873'] = 'lightblue'
    colorList['RPVresonantToEMu_M-6500_LLE_LQD-05_13TeV_CA-skimid1886'] = 'lightblue'

    hists=['HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_Nvtx',
     'HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_pT(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu30_TkMu11_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Mu23_TrkIsoVVL_Ele12_Gsf_CaloId_TrackId_Iso_MediumWP_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Mu17_Mu8_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_IsoMu17_eta2p1_LooseIsoPFTau20_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Ele95_CaloIdVT_GsfTrkIdT_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Ele95_CaloIdVT_GsfTrkIdT_v1_vs_pT(Ele)',
     #'HLT_Effs/eff_HLT_HLT_Ele23_Ele12_CaloId_TrackId_Iso_v1_vs_Nvtx',
     #'HLT_Effs/eff_HLT_HLT_Ele22_eta2p1_WP85_Gsf_LooseIsoPFTau20_v1_vs_Nvtx',

     'RECO_Effs/eff_Ele_RECO_vs_Nvtx',
     'RECO_Effs/eff_Ele_RECO_vs_pT',
     # 'RECO_Effs/eff_MET_RECO_vs_Nvtx',
     # 'RECO_Effs/eff_MET_RECO_vs_pT',
     'RECO_Effs/eff_Muon_RECO_vs_Nvtx',
     'RECO_Effs/eff_Muon_RECO_vs_pT',
     # 'RECO_Effs/eff_Tau_RECO_vs_Nvtx',
     # 'RECO_Effs/eff_Tau_RECO_vs_pT',

     'RECO_Effs/eff_Ele_RECO_vs_Nvtx_in_Acc',
     'RECO_Effs/eff_Ele_RECO_vs_pT_in_Acc',
     'RECO_Effs/eff_Muon_RECO_vs_Nvtx_in_Acc',
     'RECO_Effs/eff_Muon_RECO_vs_pT_in_Acc',
     # 'RECO_Effs/eff_Tau_RECO_vs_Nvtx_in_Acc',
     # 'RECO_Effs/eff_Tau_RECO_vs_pT_in_Acc',

     'ID_Effs/eff_Ele_ID_vs_Nvtx',
     'ID_Effs/eff_Ele_ID_vs_Nvtx_in_Acc',
     'ID_Effs/eff_Ele_ID_vs_pT',
     'ID_Effs/eff_Ele_ID_vs_pT_gen',
     'ID_Effs/eff_Ele_ID_vs_pT_in_Acc',
     'ID_Effs/eff_Ele_ID_vs_pT_in_Acc_gen',

     'ID_Effs/eff_Muon_ID_vs_Nvtx',
     'ID_Effs/eff_Muon_ID_vs_Nvtx_in_Acc',
     'ID_Effs/eff_Muon_ID_vs_pT',
     'ID_Effs/eff_Muon_ID_vs_pT_gen',
     'ID_Effs/eff_Muon_ID_vs_pT_in_Acc',
     'ID_Effs/eff_Muon_ID_vs_pT_in_Acc_gen',

     # 'ID_Effs/eff_Tau_ID_vs_Nvtx',
     # 'ID_Effs/eff_Tau_ID_vs_Nvtx_in_Acc',
     # 'ID_Effs/eff_Tau_ID_vs_pT',
     # 'ID_Effs/eff_Tau_ID_vs_pT_gen',
     # 'ID_Effs/eff_Tau_ID_vs_pT_in_Acc',
     # 'ID_Effs/eff_Tau_ID_vs_pT_in_Acc_gen',
    ]

    overall_hists = [
     ['emu/eff_emu_Acc_vs_Mass','emu/eff_emu_RECO_vs_Mass','emu/eff_emu_Eff_vs_Mass'],
     ['emu/eff_emu_Acc_vs_Nvtx','emu/eff_emu_RECO_vs_Nvtx','emu/eff_emu_Eff_vs_Nvtx'],
    ]

    eff_colorList={}
    eff_colorList['emu/eff_emu_Acc_vs_Mass'] = 'deepskyblue'
    eff_colorList['emu/eff_emu_RECO_vs_Mass'] = 'darkgreen'
    eff_colorList['emu/eff_emu_Eff_vs_Mass'] = 'red'
    eff_colorList['emu/eff_emu_Acc_vs_Nvtx'] = 'deepskyblue'
    eff_colorList['emu/eff_emu_RECO_vs_Nvtx'] = 'darkgreen'
    eff_colorList['emu/eff_emu_Eff_vs_Nvtx'] = 'red'

    hists2D=['HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu30_TkMu11_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu30_TkMu11_v1_vs_pT(Mu,Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu23_TrkIsoVVL_Ele12_Gsf_CaloId_TrackId_Iso_MediumWP_v1_vs_eta_vs_phi(Ele)',
     #'HLT_Effs/eff_HLT_HLT_Mu23_TrkIsoVVL_Ele12_Gsf_CaloId_TrackId_Iso_MediumWP_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu23_TrkIsoVVL_Ele12_Gsf_CaloId_TrackId_Iso_MediumWP_v1_vs_pT(Mu,Ele)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_v1_vs_pT(Mu,Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_v1_vs_pT(Mu,Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_Mu8_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_Mu17_Mu8_v1_vs_pT(Mu,Mu)',
     #'HLT_Effs/eff_HLT_HLT_IsoMu17_eta2p1_LooseIsoPFTau20_v1_vs_eta_vs_phi(Mu)',
     #'HLT_Effs/eff_HLT_HLT_IsoMu17_eta2p1_LooseIsoPFTau20_v1_vs_eta_vs_phi(Tau)',
     #'HLT_Effs/eff_HLT_HLT_IsoMu17_eta2p1_LooseIsoPFTau20_v1_vs_pT(Mu,Tau)',
     #'HLT_Effs/eff_HLT_HLT_Ele95_CaloIdVT_GsfTrkIdT_v1_vs_eta_vs_phi(Ele)',
     #'HLT_Effs/eff_HLT_HLT_Ele23_Ele12_CaloId_TrackId_Iso_v1_vs_eta_vs_phi(Ele)',
     #'HLT_Effs/eff_HLT_HLT_Ele23_Ele12_CaloId_TrackId_Iso_v1_vs_pT(Ele,Ele)',
     #'HLT_Effs/eff_HLT_HLT_Ele22_eta2p1_WP85_Gsf_LooseIsoPFTau20_v1_vs_eta_vs_phi(Ele)',
     #'HLT_Effs/eff_HLT_HLT_Ele22_eta2p1_WP85_Gsf_LooseIsoPFTau20_v1_vs_eta_vs_phi(Tau)',
     #'HLT_Effs/eff_HLT_HLT_Ele22_eta2p1_WP85_Gsf_LooseIsoPFTau20_v1_vs_pT(Ele,Tau)',

     'RECO_Effs/eff_Ele_RECO_vs_eta_vs_phi',
     # 'RECO_Effs/eff_MET_RECO_vs_eta_vs_phi',
     'RECO_Effs/eff_Muon_RECO_vs_eta_vs_phi',
     # 'RECO_Effs/eff_Tau_RECO_vs_eta_vs_phi',

     'RECO_Effs/eff_Ele_RECO_vs_eta_vs_phi_in_Acc',
     'RECO_Effs/eff_Muon_RECO_vs_eta_vs_phi_in_Acc',
     # 'RECO_Effs/eff_Tau_RECO_vs_eta_vs_phi_in_Acc',

     'ID_Effs/eff_Ele_ID_vs_eta_vs_phi',
     'ID_Effs/eff_Ele_ID_vs_eta_vs_phi_gen',
     'ID_Effs/eff_Ele_ID_vs_eta_vs_phi_in_Acc',
     'ID_Effs/eff_Ele_ID_vs_eta_vs_phi_in_Acc_gen',

     'ID_Effs/eff_Muon_ID_vs_eta_vs_phi',
     'ID_Effs/eff_Muon_ID_vs_eta_vs_phi_gen',
     'ID_Effs/eff_Muon_ID_vs_eta_vs_phi_in_Acc',
     'ID_Effs/eff_Muon_ID_vs_eta_vs_phi_in_Acc_gen',

     # 'ID_Effs/eff_Tau_ID_vs_eta_vs_phi',
     # 'ID_Effs/eff_Tau_ID_vs_eta_vs_phi_gen',
     # 'ID_Effs/eff_Tau_ID_vs_eta_vs_phi_in_Acc',
     # 'ID_Effs/eff_Tau_ID_vs_eta_vs_phi_in_Acc_gen',
    ]

    res_histos = [
     'emu/Stage_0/h2_0_emu_Mass_resolution'
    ]

    res_histos1D = [
     'emu/Stage_0/h1_0_emu_Mass_resolution'
    ]

    binning={
            "_vs_pT":10,
            "_vs_Mass":10,
    }

    titles={
     'HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_Nvtx':['HLT_Mu50_v1 efficiency','$N_{vtx}$','efficiency $\epsilon$'],
     'HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_pT(Mu)':['HLT_Mu50_v1 efficiency','$p_{T}^{\mu}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'RECO_Effs/eff_Ele_RECO_vs_Nvtx':['Electron reco efficiency','$N_{vtx}$','efficiency $\epsilon$'],
     'RECO_Effs/eff_Ele_RECO_vs_pT':['Electron reco efficiency','$p_{T}^{e (gen)}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'RECO_Effs/eff_Muon_RECO_vs_Nvtx':['Muon reco efficiency','$N_{vtx}$','efficiency $\epsilon$'],
     'RECO_Effs/eff_Muon_RECO_vs_pT':['Muon reco efficiency','$p_{T}^{\mu (gen)}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'ID_Effs/eff_Ele_ID_vs_Nvtx':['HEEP ID efficiency','$N_{vtx}$','efficiency $\epsilon$'],
     'ID_Effs/eff_Ele_ID_vs_pT':['HEEP ID efficiency','$p_{T}^{e}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'ID_Effs/eff_Ele_ID_vs_pT_gen':['HEEP ID efficiency','$p_{T}^{e (gen)}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'ID_Effs/eff_Muon_ID_vs_Nvtx':['High p_T muon ID efficiency','$N_{vtx}$','efficiency $\epsilon$'],
     'ID_Effs/eff_Muon_ID_vs_pT_gen':['High p_T muon ID efficiency','$p_{T}^{\mu (gen)}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'ID_Effs/eff_Muon_ID_vs_pT':['High p_T muon ID efficiency','$p_{T}^{\mu}\,(\mathrm{GeV})$','efficiency $\epsilon$'],
     'emu/eff_emu_Acc_vs_Mass':['Acceptance','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','efficiency $\epsilon$'],
     'emu/eff_emu_RECO_vs_Mass':['Trigger','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','efficiency $\epsilon$'],
     'emu/eff_emu_Eff_vs_Mass':['Selection','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','efficiency $\epsilon$'],
     'emu/eff_emu_Acc_vs_Nvtx':['Acceptance','$N_{vtx}$','efficiency $\epsilon$'],
     'emu/eff_emu_RECO_vs_Nvtx':['Trigger','$N_{vtx}$','efficiency $\epsilon$'],
     'emu/eff_emu_Eff_vs_Nvtx':['Selection','$N_{vtx}$','efficiency $\epsilon$'],
     'emu/Stage_0/h1_0_emu_Mass_resolution':['Mass resolution','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','$\sigma((M_{e\mu, reco} - M_{e\mu, gen}) / M_{e\mu, gen})$'],
    }

    yranges={
     'ID_Effs/eff_Muon_ID_vs_pT':[0.5,1.02],
     'ID_Effs/eff_Muon_ID_vs_pT_gen':[0.5,1.02],
     'ID_Effs/eff_Muon_ID_vs_pT_in_Acc':[0.5,1.02],
     'ID_Effs/eff_Muon_ID_vs_pT_in_Acc_gen':[0.5,1.02],
     'HLT_Effs/eff_HLT_HLT_Mu50_v1_vs_pT(Mu)':[0.6,1.02],
     'ID_Effs/eff_Ele_ID_vs_pT':[0.7,1.02],
     'ID_Effs/eff_Ele_ID_vs_pT_gen':[0.7,1.02],
     'ID_Effs/eff_Ele_ID_vs_pT_in_Acc':[0.7,1.02],
     'ID_Effs/eff_Ele_ID_vs_pT_in_Acc_gen':[0.7,1.02],
    }

    ####################################################################
    # Individual 1D plots
    ####################################################################

    if False:
        for hist in hists:
            print("Now plotting: " + hist)
    
            histlist = []
            for item in bglist:
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                binf = getDictValue(hist, binning)
                if binf is not None:
                    t_eff = eff_rebinner(t_eff,binf)

                i_titles = getDictValue(hist, titles)

                t_eff = Graph(t_eff.CreateGraph())
                t_eff.SetLineColor(colorList[item])
                if i_titles is not None:
                    t_eff.SetTitle(i_titles[0])
                else:
                    t_eff.SetTitle(item)
                if 'Nvtx' in hist:
                    t_eff.xaxis.SetTitle('$N_{vtx}$')
                if 'pT' in hist:
                    if i_titles is not None:
                        t_eff.xaxis.SetTitle(i_titles[1])
                    else:
                        t_eff.xaxis.SetTitle('$p_{T}$ (GeV)')
                if i_titles is not None:
                    t_eff.yaxis.SetTitle(i_titles[2])
                else:
                    t_eff.yaxis.SetTitle('$\epsilon$')
                
                histlist.append(t_eff)
    
            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower middle', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')
            hist_style.Set_legend_font_size(12)

            test = plotter(hist = histlist,style=hist_style)

            if hist in yranges.keys():
                test.Set_axis(logy = False, grid = True, ymin=yranges[hist][0],ymax=yranges[hist][1])
            else:
                test.Set_axis(logy = False, grid = True)
    
            test._cms_text_x         = 0.12
            test._cms_text_y         = 0.91
    
            name=hist.replace("/","")
    
            test.make_plot('plots/%s.pdf'%(name))

    ####################################################################
    # Combined 1D plots
    ####################################################################

    if False:
        skip_list = []
        for hist in hists:
            if hist in skip_list:
                continue
            print("Now plotting: " + hist)
    
            histlist = []
            c_histo = r.TEfficiency()
            for item in bglist:
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                if len(histlist) == 0:
                    c_histo = t_eff
                else:
                    c_histo.Add(t_eff)
                histlist.append(t_eff)

            binf = getDictValue(hist, binning)
            if binf is not None:
                c_histo = eff_rebinner(c_histo,binf)

            i_titles = getDictValue(hist, titles)

            c_histo = Graph(c_histo.CreateGraph())

            c_histo.SetLineColor('deepskyblue')

            if i_titles is not None:
                # c_histo.SetTitle(i_titles[0] + ' in Acceptance')
                c_histo.SetTitle(i_titles[0] + ' ')
            else:
                c_histo.SetTitle(hist)
            if 'Nvtx' in hist:
                c_histo.xaxis.SetTitle('$N_{vtx}$')
            if 'pT' in hist:
                if i_titles is not None:
                    c_histo.xaxis.SetTitle(i_titles[1])
                else:
                    c_histo.xaxis.SetTitle('$p_{T}$ (GeV)')
            if i_titles is not None:
                c_histo.yaxis.SetTitle(i_titles[2])
            else:
                c_histo.yaxis.SetTitle('$\epsilon$')

            plots = [c_histo]

            if hist + '_in_Acc' in hists:
                skip_list.append(hist + '_in_Acc')
                histlist1 = []
                c_histo1 = r.TEfficiency()
                for item in bglist:
                    tfile = root_open(basedir + item + ".root", "READ")
                    t_eff = tfile.Get(hist + '_in_Acc')
                    if len(histlist1) == 0:
                        c_histo1 = t_eff
                    else:
                        c_histo1.Add(t_eff)
                    histlist1.append(t_eff)

                binf = getDictValue(hist, binning)
                if binf is not None:
                    c_histo1 = eff_rebinner(c_histo1,binf)

                c_histo1 = Graph(c_histo1.CreateGraph())
    
                c_histo1.SetLineColor('darkgreen')
                if i_titles is not None:
                    c_histo1.SetTitle(i_titles[0] + ' in Acceptance')
                else:
                    c_histo1.SetTitle(hist + '_in_Acc')
                plots.append(c_histo1)

            if hist[:-4] + '_in_Acc_gen' in hists and '_gen' in hist:
                skip_list.append(hist[:-4] + '_in_Acc_gen')
                histlist2 = []
                c_histo2 = r.TEfficiency()
                for item in bglist:
                    tfile = root_open(basedir + item + ".root", "READ")
                    t_eff = tfile.Get(hist[:-4] + '_in_Acc_gen')
                    if len(histlist2) == 0:
                        c_histo2 = t_eff
                    else:
                        c_histo2.Add(t_eff)
                    histlist2.append(t_eff)

                binf = getDictValue(hist, binning)
                if binf is not None:
                    c_histo2 = eff_rebinner(c_histo2,binf)

                c_histo2 = Graph(c_histo2.CreateGraph())
    
                c_histo2.SetLineColor('darkgreen')
                if i_titles is not None:
                    c_histo2.SetTitle(i_titles[0] + ' in Acceptance')
                else:
                    c_histo2.SetTitle(hist[:-4] + '_in_Acc_gen')

                plots.append(c_histo2)

            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower middle', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')
            hist_style.Set_legend_font_size(12)

            test = plotter(hist = plots, style = hist_style)

            if hist in yranges.keys():
                test.Set_axis(logy = False, grid = True, ymin=yranges[hist][0],ymax=yranges[hist][1])
            else:
                test.Set_axis(logy = False, grid = True)
    
            test._cms_text_x         = 0.12
            test._cms_text_y         = 0.91
    
            name=hist.replace("/","")
    
            test.make_plot('plots/%s.pdf'%(name))

    ####################################################################
    # Combined 1D plots for overall efficiencies
    ####################################################################

    if True:
        for hist in overall_hists:
            print("Now plotting: " + hist[0])

            hists_to_plot = []
            for i_hist in hist:
                histlist = []
                c_histo = r.TEfficiency()
                for item in bglist:
                    tfile = root_open(basedir + item + ".root", "READ")
                    t_eff = tfile.Get(i_hist)
                    if len(histlist) == 0:
                        c_histo = t_eff
                    else:
                        c_histo.Add(t_eff)
                    histlist.append(t_eff)

                binf = getDictValue(i_hist, binning)
                if binf is not None:
                    c_histo = eff_rebinner(c_histo,binf)

                i_titles = getDictValue(i_hist, titles)

                c_histo = Graph(c_histo.CreateGraph())
                c_histo.SetLineColor(eff_colorList[i_hist])
                if i_titles is not None:
                    c_histo.SetTitle(i_titles[0])
                else:
                    c_histo.SetTitle(i_hist)

                if 'Nvtx' in i_hist:
                    c_histo.xaxis.SetTitle('$N_{vtx}$')
                if 'Mass' in i_hist:
                    if i_titles is not None:
                        c_histo.xaxis.SetTitle(i_titles[1])
                    else:
                        c_histo.xaxis.SetTitle('$M$ (GeV)')
                if i_titles is not None:
                    c_histo.yaxis.SetTitle(i_titles[2])
                else:
                    c_histo.yaxis.SetTitle('$\epsilon$')

                hists_to_plot.append(c_histo)

            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower middle', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')
            hist_style.Set_legend_font_size(12)

            test = plotter(hist = hists_to_plot, style = hist_style)

            if hist in yranges.keys():
                test.Set_axis(logy = False, grid = True, ymin=yranges[hist][0],ymax=yranges[hist][1])
            else:
                test.Set_axis(logy = False, grid = True)
    
            test._cms_text_x         = 0.12
            test._cms_text_y         = 0.91
    
            name=hist[0].replace("/","")

            test.create_plot()

            if 'Mass' in hist[0]:
                plot_efficiency_fit(test.Get_axis1(), hists_to_plot[-1], xmin = 0, xmax = 6000, startvals = [0.78, -96, -85, -1.9e-5], plottrange = [100,6000])

            test.SavePlot('plots/%s.pdf'%(name))

    ####################################################################
    # Individual 2D plots
    ####################################################################

    if False:
        for hist in hists2D:
            print("Now plotting: " + hist)
    
            histlist = []
            for item in bglist:
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist).CreateHistogram()
                # t_eff.SetLineColor(colorList[item])
                t_eff.SetTitle(item)
                # t_eff.xaxis.SetTitle(t_eff.GetXaxis().GetTitle())
                # t_eff.yaxis.SetTitle(t_eff.GetYaxis().GetTitle())
                histlist.append(t_eff)

                hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Standard', cmsPositon = "outside left", legendPosition = 'lower middle', lumi = 0, cms = 13)
    
                hist_style.Set_additional_text('Spring15 simulation')
    
                test = plotter2D(hist = t_eff, style = hist_style)
    
                # test.Set_axis(xmin = -2.5, xmax = 2.5, ymin = 0, ymax = 3.1, zmin = 0, zmax = 1)
    
                name=hist.replace("/","")
    
                test.create_plot()
    
                test.save_plot('plots/%s_%s.pdf'%(item,name))

    ####################################################################
    # Combined 2D plots
    ####################################################################

    if False:
        for hist in hists2D:
            print("Now plotting: " + hist)
    
            histlist = []
            c_histo = r.TEfficiency()
            for item in bglist:
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                if len(histlist) == 0:
                    c_histo = t_eff
                else:
                    c_histo.Add(t_eff)
                histlist.append(t_eff)

            c_histo = c_histo.CreateHistogram()
            c_histo.SetTitle(hist)

            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Standard', cmsPositon = "outside left", legendPosition = 'lower middle', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')

            test = plotter2D(hist = c_histo, style = hist_style)

            # test.Set_axis(xmin = -2.5, xmax = 2.5, ymin = 0, ymax = 3.1, zmin = 0, zmax = 1)

            name=hist.replace("/","")

            test.create_plot()

            test.save_plot('plots/%s.pdf'%(name))

    ####################################################################
    # Resolution plot
    ####################################################################

    if False:
        for hist in res_histos:
            print("Now plotting: " + hist)
    
            histlist = []
            c_histo = r.TH2F()
            for item in bglist:
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                if len(histlist) == 0:
                    c_histo = t_eff
                else:
                    c_histo.Add(t_eff)
                histlist.append(t_eff)

            c_histo.SetTitle(hist)

            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Standard', cmsPositon = "outside left", legendPosition = 'lower middle', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')

            test = plotter2D(hist = c_histo, style = hist_style)
            # test.Add_x_projection()
            # test.Add_y_projection()

            test.Set_axis(ymin = -0.5, ymax = 0.5)

            name=hist.replace("/","")

            test.create_plot()

            test.save_plot('plots/%s.pdf'%(name))

    ####################################################################
    # Individual resolution plots
    ####################################################################

    if True:
        for hist in res_histos1D:
            print("Now plotting: " + hist)

            x_vals =[]
            y_vals = []
            y_errs = []
            for item in bglist:
                if 'LLE_LQD-001' not in item:
                    continue
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                t_eff.xaxis.SetTitle('$'+t_eff.xaxis.GetTitle()+'$')
                t_eff.yaxis.SetTitle('Events / %.2f'%t_eff.GetBinWidth(1))

                hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower left', lumi = 0, cms = 13)
                hist_style.Set_additional_text('Spring15 simulation')
                test = plotter(hist = [t_eff],style=hist_style)
                name=item.replace("/","")
                test.Set_axis(logy = True, grid = True, xmin = -1.01, xmax = 1.01, ymin = 0.9, ymax = 4000)
                test.create_plot()

                plot_gauss_fit(test.Get_axis1(), t_eff, color = 'red', write_results = True)

                test.SavePlot('plots/%s.pdf'%(name))

                fit_res = t_eff.Fit('gaus', 'N0S', '')
                y_vals.append(fit_res.Parameter(2))
                y_errs.append(fit_res.ParError(2))
                parts = item.split('_')
                for part in parts:
                    if 'M-'in part:
                        x_vals.append(int(part[2:]))

            x_vals = np.array(x_vals)
            y_vals = np.array(y_vals)
            y_errs = np.array(y_errs)

            graph = Graph(x_vals.shape[0])
            for i, (xx, yy, ye) in enumerate(zip(x_vals, y_vals, y_errs)):
                graph.SetPoint(i, xx, yy)
                graph.SetPointError(i, 0, 0, ye, ye)

            i_titles = getDictValue(hist, titles)

            if i_titles is not None:
                graph.SetTitle(i_titles[0])
                graph.xaxis.SetTitle(i_titles[1])
                graph.yaxis.SetTitle(i_titles[2])

            graph.SetLineColor('red')

            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower left', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')

            test = plotter(hist = [graph],style=hist_style)

            name=hist.replace("/","")

            test.Set_axis(logy = False, grid = True, xmin = 0, xmax = 6500)

            test.create_plot()

            func = plot_resolution_fit(test.Get_axis1(), graph, xmin = 0, xmax = 6000, startvals = [], plottrange = [], color = 'black')

            test.SavePlot('plots/%s.pdf'%(name))
            graph.SaveAs('plots/%s.root'%(name))
            func.SaveAs('plots/%s_func.root'%(name))

    return 42
Example #2
0
def main():
    #get the list of bg and data files from the unusal config
    sampleinfos, basedir = getSampleInfo("201705_mergedext.config")
    lumi = sampleinfos.values()[-1]["lumi"]
    useRoot = False

    #we will use the same colors as the .c plotter for now
    colors = [100, 90, 80, 70, 60, 95, 85, 75, 65, 55]
    #reverse order and change to RGB
    colors = [getRGBTColor(i) for i in colors[::-1]]

    #make storage containers for the bgs and data
    bghists = HistStorage(xs=sampleinfos,
                          xstype="BSM3G",
                          lumi=lumi,
                          path=basedir,
                          useRoot=useRoot)
    dat_hist = HistStorage(path=basedir, isData=True, useRoot=useRoot)

    #make some lists that we will put into the containers
    colorList = {}
    bglist = OrderedDict()
    for sample in sampleinfos:
        info = sampleinfos[sample]
        sample = sample.replace(".root", "")
        if info["type"] == "bg":
            shortName = info["output"].replace(".root", "")
            if "#" in shortName:
                shortName = "$\mathsf{" + shortName.replace("#", "\\") + "}$"
            if shortName not in bglist:
                bglist[shortName] = [sample]
                colorList[shortName] = colors.pop()
            else:
                bglist[shortName].append(sample)
        #for data directly add the file
        if info["type"] == "data":
            dat_hist.addFile(sample)
    for bg in bglist:
        print("bglist['%s']=[" % (bg))
        for ibg in bglist[bg]:
            print("'ibg',")
        print("]")

    #now actually add the backgrounds
    bghists.addFileList(bglist)
    bghists.colorList = colorList

    hists = [
        "NDiMuonCombinations/MHT",
        "NDiMuonCombinations/Meff",
    ]

    histContainer = HistStorageContainer(bg=bghists, data=dat_hist)
    #histContainer=HistStorageContainer(bg=bghists,sg=sghist,data=dat_hist)

    binning = {
        "_pt": 25,
        "_mt": 25,
        "_met": 25,
        "MC_W_m_Gen": 10,
        "_jet_ht": 10,
    }

    xranges = {
        "_pt": [0, 1000],
        "_jet_ht": [0, 1600],
        "_mt": [150, 1600],
        "boson_qt": [0, 600],
        "_met": [0, 1300],
        "_ET_MET": [0, 4],
        "_DeltaPhi": [0.2, math.pi],
        "MC_W_m_Gen": [0, 1300],
        "relIso": [0, 0.05],
    }
    yranges = {
        "_ET_MET": [1.01e-3, 1e8],
        "_DeltaPhi": [1.01e-3, 1e8],
    }

    bghists.initStyle(style="bg")
    #sghist.initStyle(style="sg")
    for hist in hists:

        ##use different out dirs
        dir_name = "test"
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)

        if "prof" in hist:
            hist_style = sc.style_container(kind="Lines",
                                            style='CMS',
                                            useRoot=useRoot,
                                            cmsPositon="upper left",
                                            lumi=lumi,
                                            cms=13)
        else:
            hist_style = sc.style_container(style='CMS',
                                            useRoot=useRoot,
                                            cmsPositon="upper left",
                                            lumi=lumi,
                                            cms=13)

        #change the style if you want
        #hist_style._error_bands_fcol=["grey","yellow"]
        #hist_style._error_bands_ecol=["lightgrey","yellow"]
        #hist_style._error_bands_alph=0.4
        #hist_style.Set_error_line_width(0.0000000001)
        hist_style.Set_poisson_error_off()
        #hist_style.Set_minor_ticks()
        #hist_style.Set_n_legend_columns(2)
        #hist_style.Set_xerr()
        #hist_style.Set_do_overflowbin()

        #get the actual histograms
        histContainer.getHist(hist)

        #programmable binning
        binf = getDictValue(hist, binning)
        if binf is not None:
            if isinstance(binf, list):
                histContainer.rebin(vector=binf)
            else:
                histContainer.rebin(width=binf)

        name = hist.replace("/", "")
        #test = plotter(hist=histContainer.getBGList(),data_hist=histContainer.getData(),data=True,style=hist_style)
        test = plotter(hist=histContainer.getBGList(), style=hist_style)
        test.Add_data(histContainer.getData())

        test.Add_plot('Ratio', pos=1, height=15)
        test.Add_plot('DiffRatio_width_increase', pos=2, height=15)
        mplt = test.create_plot()
        test.SavePlot('%s/%s.png' % (dir_name, name))
        test.SavePlot('%s/%s.pdf' % (dir_name, name))
def main():

    cfg=plotConfiguration(do_ddQCD=False)
    #cfg=plotConfiguration(do_ddQCD=True)

    hists=[
        #make a list of histograms to be drawn
        #give the path to the histogram in rootfile
        "demo/histoDir/mT_Stage1",
        "demo/histoDir/tauPt_Stage1"

    ]
    #cfg.DataFiles=["Data_MET"]
    if "multijet" in cfg.bglist:
        cfg.bglist["multijet"]=[
                   "dataDrivenQCD",
                    ]
    #splitbg(r'$\mathsf{t\bar{t}}$',cfg.bglist,cfg.bgcolorList)
    #cfg.bghists.additionalWeight["dataDrivenTree15_pt_baseFit"]=0.5
    systematics={}
    for hist in hists:
        try:
            syst_hist=getStystPlot(hist)
            systematics[hist]=syst_hist
        except:
            continue
    for bg in cfg.bghists.files:
        print bg
    cfg.compile_obj()

    #draw bg, sg and data
    histContainer=HistStorageContainer(bg=cfg.bghists,sg=cfg.sghist,data=cfg.dat_hist)
    #draw bg and data
    #histContainer=HistStorageContainer(bg=bghists,data=dat_hist)

    #set binning for different histograms
    binning={
            #variable binning
            #"_MT":range(200,300,20)+range(300,400,50)+range(400,1600,100)+range(1600,2000,200),
            #"_mt":range(150,400,25)+range(400,1401,50),
            #binned in 20 GeV
            "demo/histoDir/mT_Stage1":20,
            "demo/histoDir/tauPt_Stage1":20,
            "_pt":20,
            "_mt":30,
            "_met":20,
            "MC_W_m_Gen":10,
            "_jet_ht":10,
    }

    xranges={
            #set xrange to be drawn
            "demo/histoDir/mT_Stage1":[0,2000],
            "demo/histoDir/tauPt_Stage1":[0,1500],
            "_pt":[0,1000],
            "_jet_ht":[0,1600],
            "_mt":[150,1600],
            "boson_qt":[0,600],
            "_met":[0,1300],
            "_ET_MET":[0,4],
            "_DeltaPhi":[math.pi/40.*3,math.pi],
            "MC_W_m_Gen":[0,1300],
            "relIso":[0,0.05],
    }
    yranges={
            #set yrange to be drawn
            "_ET_MET":[1.01e-3,1e8],
            "_DeltaPhi":[1.01e-3,1e8],
            #"Taus/":[1.01e-3,1e4],
    }

    #set drawing style for bg and signal
    cfg.bghists.initStyle(style="bg")
    cfg.sghist.initStyle(style="sg")

    for hist in hists:
        dir_name="outFirstTest"
        #dir_name="out13_pfMET"
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)

        #see Plotlib/lib/plotlib.py for functions
        hist_style = sc.style_container(style = 'CMS', useRoot=cfg.useRoot,cmsPositon="upper left",lumi=cfg.lumi,cms=13)    #setup the histograms with lumi and CMS decoration
        hist_style._error_bands_fcol=["grey","yellow"]  #set errorband colors
        hist_style._error_bands_ecol=["lightgrey","yellow"] #set errorband colors
        hist_style._error_bands_alph=0.4    #set errorband alpha?
        hist_style.Set_error_line_width(0.0000000001)
        hist_style.Set_poisson_error_off()  #set error calculation
        hist_style.Set_minor_ticks()  #set tick style
        hist_style.Set_n_legend_columns(2)  #change number of columns to 2
        hist_style.Set_xerr()
        #hist_style.Set_error_bands_center("ref")
        hist_style.Set_do_overflowbin()
        hist_style.SetBatchMode(False)


        print "Working on",hist

        if "W_m_Gen" in hist:
            histContainer=HistStorageContainer(bg=cfg.bghists,data=cfg.bghists)

        histContainer.getHist(hist)

        #if "W_m_Gen" in hist:
            #wbg=filter(lambda x: r"{W\rightarrow l \nu" in x.GetTitle(),   histContainer.getBGList())
            #for bg in wbg:
                #print bg.GetTitle()
            #for bg in histContainer.getBGList():
                #print bg.GetTitle()
            #sumbg=sum(filter(lambda x: r"{W\rightarrow l \nu" in x.GetTitle(),   histContainer.getBGList()))
            #sumbg.GetXaxis().SetTitle("M_{W} [GeV]")
            #sumbg.SaveAs("Wmass.root")
            #continue

        #set binning
        binf=getDictValue(hist,binning)
        if binf is not None:
            if "_phi" not in hist and "jet_ht_lep_pt" not in hist:
                if isinstance(binf,list):
                    histContainer.rebin(vector=binf)
                else:
                    histContainer.rebin(width=binf)

        if "_mt" in hist or "_ET_MET" in hist:

            if "_mt" in hist:
                make_wprimeOverviewPlot(dir_name,hist,histContainer,[500,1000,1400])
                #make_OverviewPlot(dir_name,hist,histContainer,[500,1000,1400])

            makeTeXTable(dir_name,hist,histContainer)


            #generate some output
            mtBinOut=open(dir_name+"/"+hist.replace("/","")+"output.txt","w+")



            #generate some output
            for ibin in range(histContainer.getData().GetNbinsX()):
                mtBinOut.write( "------------------\n")
                mtBinOut.write( "{0}-{1}\n".format(histContainer.getData().xedgesl(ibin),histContainer.getData().xedgesl(ibin+1)))
                sumbg=0.
                for bg in cfg.bghists.hists:
                    weight=1.
                    for ibg in cfg.bglist[bg]:

                        if ibg in cfg.bghists.weight:
                            weight*=cfg.bghists.weight[ibg]

                    mtBinOut.write( "{0}  {1}  {2}\n".format(bg,cfg.bghists.hists[bg].integral(xbin1=ibin),weight))
                    sumbg+=cfg.bghists.hists[bg].integral(xbin1=ibin)
                mtBinOut.write( "data {0}  \n".format(histContainer.getData().integral(xbin1=ibin)))
                mtBinOut.write( "sumbg {0} \n".format(sumbg))

        #generate some output
        if "_pt" in hist:
            makeTeXTable(dir_name,hist,histContainer)

        #generate some output
        if "_ET_MET" in hist:
            mtBinOut=open(dir_name+"/"+hist.replace("/","")+"output2.txt","w+")
            #for ibin in range(histContainer.getData().GetNbinsX()):
            mtBinOut.write( "------------------\n")
            #mtBinOut.write( "{0}\n".format(histContainer.getData().xedgesl(ibin)))
            sumbg=0.
            qcd=0.
            for bg in cfg.bghists.hists:
                weight=1.
                for ibg in cfg.bglist[bg]:

                    if ibg in cfg.bghists.weight:
                        weight*=cfg.bghists.weight[ibg]

                mtBinOut.write( "{0}  {1}  {2}\n".format(bg,cfg.bghists.hists[bg].integral(xbin1=0,xbin2=histContainer.getData().FindBin(0.4))+cfg.bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,5)),weight))
                #mtBinOut.write( "{0}  {1}  {2}\n".format(bg,bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,4)),weight))
                if "multijet" not in bg:
                    sumbg+=cfg.bghists.hists[bg].integral(xbin1=0,xbin2=histContainer.getData().FindBin(0.4))+cfg.bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,5))
                    #sumbg+=bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,4))
                else:
                    qcd=cfg.bghists.hists[bg].integral(xbin1=0,xbin2=histContainer.getData().FindBin(0.4))+cfg.bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,5))
                    #qcd=bghists.hists[bg].integral(xbin1=histContainer.getData().FindBin(1,4))
            alldata=histContainer.getData().integral(xbin1=0,xbin2=histContainer.getData().FindBin(0.4))+histContainer.getData().integral(xbin1=histContainer.getData().FindBin(1,5))
            #alldata=histContainer.getData().integral(xbin1=histContainer.getData().FindBin(1,4))
            mtBinOut.write( "data {0}  \n".format(alldata))
            mtBinOut.write( "sumbg {0} \n".format(sumbg))
            if qcd!=0:
                mtBinOut.write( "qcd_factor {0} \n".format((alldata-sumbg)/qcd))


        if "nPrimaryVertices" in hist:
            mc_vertex_reco=ROOT.TFile("mc_vertex_reco.root","RECREATE")
            h=histContainer.bg.getAllAdded()
            mc_vertex_reco.cd()
            h.Write("pileup")
            mc_vertex_reco.Close()
            data_vertex_reco=ROOT.TFile("data_vertex_reco.root","RECREATE")
            h=histContainer.getData()
            data_vertex_reco.cd()
            h.Write("pileup")
            data_vertex_reco.Close()


        if "Tau_decayMode" in hist:
            for ih in histContainer.allStored:
                for h in ih.hists.values():
                    h.GetXaxis().SetTitle(h.GetXaxis().GetTitle().replace(r"#N_",r"N_"))
        #if "h1_7_Tau_met" in hist:
            #ratio=histContainer.getData().clone()
            #ratio/=sum(histContainer.getBGList())
            #for ibin in ratio.bins():
                #print ibin.x.low, ibin.x.high, ibin.value


        #possibility to make cumulative plot
        #histContainer.makeCumulative()

        #plot backgrounds with or without signals
        test = plotter(hist=histContainer.getBGList(),sig=histContainer.getSGList(),style=hist_style)
        #test = plotter(hist=histContainer.getBGList(),style=hist_style)
        #test = plotter(hist=histContainer.getBGList(),sig=[]  ,style=hist_style)

        lumi_err=histContainer.getData().empty_clone()
        for ibin in lumi_err:
            ibin.value=0.027
        #lumi_err.Draw()
        #raw_input()
        if hist in systematics:
            hist_style._error_bands_fcol=["grey","yellow"]
            hist_style._error_bands_ecol=["lightgrey","yellow"]
            realSyst=histContainer.getData().empty_clone()
            for ibin in range(realSyst.GetNbinsX()):
                realSyst[ibin].value=systematics[hist][systematics[hist].FindBin(realSyst[ibin].x.center)].value
                #print realSyst[ibin].x.center ,realSyst[ibin].value
            test.Add_error_hist(histo = [realSyst,lumi_err],labels=["Syst. uncer.","lumi Uncert"],band_center = "ref",stacking = "linear")
        else:
            hist_style._error_bands_fcol=["yellow"]
            hist_style._error_bands_ecol=["yellow"]
            test.Add_error_hist(histo = [lumi_err],labels=["lumi Uncert"],band_center = "ref",stacking = "linear")

        #add data to plot
        test.Add_data(histContainer.getData())




        #set x and y ranges for plot
        ymax=.5e4
        if ("h1_4_" in hist) and not "phi" in hist:
            ymax=.5e5
        if "h1_0" in hist:
            ymax=.5e11
        myrange=getDictValue(hist,yranges)
        if myrange is not None:
            ymax=myrange[1]
        test.Set_axis(ymin=1.01e-3,ymax=ymax)
        mxrange=getDictValue(hist,xranges)
        if mxrange is not None:
            if "_phi" not in hist and "jet_ht_lep_pt" not in hist:
                test.Set_axis(ymin=1.01e-3,ymax=ymax,xmin=mxrange[0],xmax=mxrange[1])
            if "jet_ht_lep_pt" in hist:
                test.Set_axis(ymin=1.01e-3,ymax=ymax,xmin=0,xmax=5)
                #test.Set_axis(ymin=1.01e-3,ymax=.5e3,xmin=mxrange[0],xmax=mxrange[1])
            #if "_mt" in hist:
                #test.Set_axis(ymin=1.01e-3,ymax=.5e3,xmin=mxrange[0],xmax=mxrange[1])
        #else:
            #test.Set_axis(ymin=1.01e-1,ymax=.5e4)
        #name=hist.replace("/","")
        name=hist.split("/")[-1]

        #if useRoot:
            #test.Add_plot('DiffRatio_width_increase',pos=0, height=15)
        #elif not "h1_0" in hist:
            ##test.Add_plot('Signi',pos=0, height=15)
            #test.Add_plot('Ratio',pos=1, height=15)
            ##test.Add_plot('DiffRatio_width_increase',pos=2, height=15)

        #set additional plots like ratio plot
        """
        if "mt" in hist and not "_syst_iso_QCD" in hist:
            test.Add_plot('Ratio_width_increase',pos=1, height=15)
            test.Add_plot('DiffRatio_width_increase',pos=2, height=15)
        elif not "_syst_iso_QCD" in hist:
            test.Add_plot('Ratio_width_increase',pos=1, height=15)
        """
        #test.Add_plot('Signi',pos=2, height=15)
        #test.Add_plot('Diff',pos=2, height=15)
        #test.Add_plot('Ratio',pos=1, height=15)
        #test.Add_error_hist([sys_hist_2,sys_hist], band_center = 'ref')
        #test.ChangeStyle(cms_val=8,lumi_val=lumi)


        #drawing
        print "make plot",name
        mplt=test.create_plot()
        part="e"
        if "Tau" in hist:
                part="\\tau"
        mplt.text(hist_style.Get_cmsTextPosition().getX()+ 0.16, hist_style.Get_cmsTextPosition().getY()-0.03, r'$\mathsf{%s+E_{T}^{miss}}$'%(part), va='bottom', ha='left', color=hist_style.Get_annotation_text_color(), size=14, weight='normal')
        print "save plot", '%s/%s.png'%(dir_name,name)
        #test.SavePlot('%s/%s_C.png'%(dir_name,name))
        #test.SavePlot('%s/%s_C.pdf'%(dir_name,name))
        #test.SavePlot('%s/%s_D.png'%(dir_name,name))
        #test.SavePlot('%s/%s_D.pdf'%(dir_name,name))
        #test.SavePlot('%s/%s_E.png'%(dir_name,name))
        #test.SavePlot('%s/%s_E.pdf'%(dir_name,name))
        test.SavePlot('%s/%s_CDE.png'%(dir_name,name))
        test.SavePlot('%s/%s_CDE.pdf'%(dir_name,name))
        #test.make_plot('out13_new/%s.pdf'%(name))
        #test.make_plot('out13_new/%s.png'%(name))
        #test.SavePlot('out13_new/%s.pdf'%(name))
        #test.make_plot('%s_cumulative.pdf'%(name))
    sys.exit()
def main():

    basedir="/.automount/home/home__home1/institut_3a/keller/Masterthesis/Results_MassResolution/"
    
    # lumi=19712

    # xs= ConfigObj("/disk1/erdweg/plotting/xs_Phys14.cfg")
    # bghists=HistStorage(xs,lumi,path=basedir,isData=True)

    colors = ['lime', 'deepskyblue', 'magenta', 'orangered']

    bglist=OrderedDict()

    bglist = [
     #'Asymptotic/Mass1000/SpecialHistos',
     #'Startup/Mass1000/SpecialHistos',
     #'Asymptotic/Mass1200/SpecialHistos',
     #'Startup/Mass1200/SpecialHistos',
     #'Asymptotic/Mass1400/SpecialHistos',
     #'Startup/Mass1400/SpecialHistos',
     'Asymptotic/Mass1600/SpecialHistos',
     'Startup/Mass1600/SpecialHistos',
     'Asymptotic/Mass1800/SpecialHistos',
     'Startup/Mass1800/SpecialHistos',
     'Asymptotic/Mass2000/SpecialHistos',
     'Startup/Mass2000/SpecialHistos',
      
    ]

    colorList={}
    colorList['SpecialHistos'] = 'lightblue'

    res_histos = [
     'emu/Stage_0/h2_0_emu_Mass_resolution'
    ]

    res_histos1D = [
     'emu/Stage_0/h1_0_emu_Mass_resolution'
    ]

    binning={
            "_vs_pT":10,
            "_vs_Mass":10,
    }

    titles={
     'emu/Stage_0/h1_0_emu_Mass_resolution':['Mass resolution asymptotic','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','$\sigma((M_{e\mu, reco} - M_{e\mu, gen}) / M_{e\mu, gen})$','Mass resolution startup','$M_{e\mu, gen}\,\,\mathrm{(GeV)}$','$\sigma((M_{e\mu, reco} - M_{e\mu, gen}) / M_{e\mu, gen})$'],
    }
   
    ####################################################################
    # Individual resolution plots
    ####################################################################

    if True:
        for hist in res_histos1D:
            print("Now plotting: " + hist)

            x_vals =[]
            y_vals = []
            y_errs = []
            x_vals_startup =[]
            y_vals_startup = []
            y_errs_startup = []
            for item in bglist:
                if 'SpecialHistos' not in item:
                    continue
                tfile = root_open(basedir + item + ".root", "READ")
                t_eff = tfile.Get(hist)
                t_eff.xaxis.SetTitle('$'+t_eff.xaxis.GetTitle()+'$')
                t_eff.yaxis.SetTitle('Events / %.2f'%t_eff.GetBinWidth(1))

                hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower left', lumi = 0, cms = 13)
                hist_style.Set_additional_text('Spring15 simulation')
                test = plotter(hist = [t_eff],style=hist_style)
                name=item.replace("/","")
                test.Set_axis(logy = False, grid = True, xmin = -1.01, xmax = 1.01, ymin = 0.9, ymax = 4000)
                test.create_plot()

                plot_gauss_fit(test.Get_axis1(), t_eff, color = 'red', write_results = True)

                test.SavePlot('plots/%s.pdf'%(name))

                fit_res = t_eff.Fit('gaus', 'N0S', '')
                if(item[0:-23] == "Asymptotic"):
		    y_vals.append(fit_res.Parameter(2))
		    y_errs.append(fit_res.ParError(2))
		    x_vals.append(int(item[15:-14]))
		if(item[0:-23] == "Startup"):
		    y_vals_startup.append(fit_res.Parameter(2))
		    y_errs_startup.append(fit_res.ParError(2))
		    x_vals_startup.append(int(item[12:-14]))
		
		
		
            x_vals = np.array(x_vals)
            y_vals = np.array(y_vals)
            y_errs = np.array(y_errs)
	    

	    x_vals_startup = np.array(x_vals_startup)
            y_vals_startup = np.array(y_vals_startup)
            y_errs_startup = np.array(y_errs_startup)
	    #print(len(x_vals))
	    #print(len(y_vals))
	    #print(len(y_errs))
	      
	    ### create plots for asymptotic
            graph = Graph(x_vals.shape[0])
            for i, (xx, yy, ye) in enumerate(zip(x_vals, y_vals, y_errs)):
                graph.SetPoint(i, xx, yy)
                graph.SetPointError(i, 0, 0, ye, ye)

            i_titles = getDictValue(hist, titles)

            if i_titles is not None:
                graph.SetTitle(i_titles[0])
                graph.xaxis.SetTitle(i_titles[1])
                graph.yaxis.SetTitle(i_titles[2])

            graph.SetLineColor('red')
	    
	    ### create plots for startup
            graph_startup = Graph(x_vals_startup.shape[0])
            for i, (xx, yy, ye) in enumerate(zip(x_vals_startup, y_vals_startup, y_errs_startup)):
                graph_startup.SetPoint(i, xx, yy)
                graph_startup.SetPointError(i, 0, 0, ye, ye)

            i_titles = getDictValue(hist, titles)

            if i_titles is not None:
                graph_startup.SetTitle(i_titles[3])
                graph_startup.xaxis.SetTitle(i_titles[4])
                graph_startup.yaxis.SetTitle(i_titles[5])

            graph_startup.SetLineColor('blue')
	      
            hist_style = sc.style_container(style = 'CMS', useRoot = False, kind = 'Graphs', cmsPositon = "upper left", legendPosition = 'lower left', lumi = 0, cms = 13)

            hist_style.Set_additional_text('Spring15 simulation')

            test = plotter(hist = [graph, graph_startup],style=hist_style)

            name=hist.replace("/","")

            test.Set_axis(logy = False, grid = True, xmin = 0, xmax = 6500)

            test.create_plot()

            #func = plot_resolution_fit(test.Get_axis1(), graph, xmin = 0, xmax = 6000, startvals = [], plottrange = [], color = 'black')

            test.SavePlot('plots/%s.pdf'%(name))
            graph.SaveAs('plots/%s.root'%(name))
            #func.SaveAs('plots/%s_func.root'%(name))

    return 42
Example #5
0
def main():

    basedir="/disk1/erdweg/out/output2015_2_13_15_47/merged//"
    lumi=1000

    xs= ConfigObj("/disk1/erdweg/plotting/xs_Phys14.cfg")
    bghists=HistStorage(xs,lumi,path=basedir)
    # bghists.setDataDriven("dataDrivenQCD")

    bglist=OrderedDict()

    bglist["PU20bx25"]=['ZprimeToTauTau_M-5000_PU20bx25_PHYS14',
     'ZprimeToTauTau_M-1000_PU20bx25_PHYS14',
    ]
    bglist["AVE30BX50"]=['ZprimeToTauTau_M-1000_AVE30BX50_PHYS14',
     'ZprimeToTauTau_M-5000_AVE30BX50_PHYS14',
     ]
    bglist["PU40bx25"]=['ZprimeToTauTau_M-1000_PU40bx25_PHYS14',
     'ZprimeToTauTau_M-5000_PU40bx25_PHYS14',
    ]

    colorList={}
    colorList["PU20bx25"]="lightblue"
    colorList["AVE30BX50"]="lightgreen"
    colorList["PU40bx25"]="darkmagenta"

    bghists.addFileList(bglist)

    dat_hist=HistStorage(xs,lumi,path=basedir,isData=True)
    # dat_hist.addFile("Data")

    hists=[#'Taus/h1_1_Tau_eta',
    #'Taus/h1_1_Tau_phi',
    #'Taus/h1_2_Tau_pt',
    #'Taus/h1_Tau_pt_resolution_0_500',
    'Eles/h1_Ele_pt_resolution_0_500',
    'Eles/h1_Ele_pt_resolution_500_1000',
    #'Eles/h1_2_Ele_pt',
    'Muons/h1_Muon_pt_resolution_0_500',
    'Muons/h1_Muon_pt_resolution_500_1000',
    #'Muons/h1_2_Muon_pt',
    #'emu/Stage_0/h1_0_emu_Mass',
    #'mutau/Stage_0/h1_0_mutau_Mass',
    #'mutau/Stage_6/h1_6_mutau_Mass',
    #'Ctr/h1_Ctr_Vtx_unweighted',
    #'Ctr/h1_Ctr_Vtx_weighted',
    #'Ctr/h1_Ctr_Vtx_emu_unweighted',
    #'Ctr/h1_Ctr_Vtx_emu_weighted',
    #'Ctr/h1_Ctr_HT',
    #'Ctr/h1_Ctr_pT_hat',
    #'emu/Stage_0/h1_0_emu_Mass_resolution',
    #'mutau/Stage_0/h1_0_mutau_Mass_resolution'
    ]

    sghist=HistStorage(xs,lumi,path=basedir)
    # sgName="$\mathsf{W' \, M=2.3\,TeV \cdot 0.02}$"
    # sghist.additionalWeight={"WprimeToTauNu_M-2300_TuneZ2star_8TeV-pythia6-tauola_Summer12_DR53X-PU_S10_START53_V7A-v1SIM":0.02}
    # sghist.addAllFiles(tag="WprimeToTauNu_M-2300",joinName=sgName)
    # sghist.colorList={sgName :"darkred"}

    histContainer=HistStorageContainer(sg=bghists,data=dat_hist,bg=sghist)

    binning={
            "Taus/h1_2_Tau_pt":10,
            # "emu/Stage_0/h1_0_emu_Mass":range(200,300,20)+range(300,400,50)+range(400,1600,100)+range(1600,2000,200),
            # "mutau/Stage_0/h1_0_mutau_Mass":range(200,300,20)+range(300,400,50)+range(400,1600,100)+range(1600,2000,200),
            # "mutau/Stage_6/h1_6_mutau_Mass":range(200,300,20)+range(300,400,50)+range(400,1600,100)+range(1600,2000,200),
            "_met_et":30,
    }

    xranges={
            "Taus/h1_2_Tau_pt":[0,2000],
            "emu/Stage_0/h1_0_emu_Mass":[0,2000],
            "mutau/Stage_0/h1_0_mutau_Mass":[0,2000],
            "mutau/Stage_6/h1_6_mutau_Mass":[0,2000],
            "emu/Stage_0/h1_0_emu_Mass_resolution":[-2,2],
            "mutau/Stage_0/h1_0_mutau_Mass_resolution":[-2,2],
            "Taus/h1_Tau_pt_resolution_0_500":[-2,2],
            "Eles/h1_Ele_pt_resolution_0_500":[-2,2],
            "Eles/h1_Ele_pt_resolution_500_1000":[-2,2],
            "Muons/h1_Muon_pt_resolution_0_500":[-2,2],
            "Muons/h1_Muon_pt_resolution_500_1000":[-2,2],
            "Ctr/h1_Ctr_Vtx_unweighted":[0,40],
            "Ctr/h1_Ctr_Vtx_weighted":[0,40],
            "Ctr/h1_Ctr_Vtx_emu_unweighted":[0,40],
            "Ctr/h1_Ctr_Vtx_emu_weighted":[0,40],
    }

    bghists.initStyle(style="sg",colors=colorList)
    # sghist.initStyle(style="sg")

    for hist in hists:
        print("Now plotting: " + hist)
        histContainer.getHist(hist)

        binf=getDictValue(hist,binning)
        if binf is not None:
            # dat_hist.rebin(width=binf)
            bghists.rebin(width=binf)
        bghists.colorList=colorList
        # bghists.setStyle(bgcolors=colorList)
        # dat_hist.getHistList()[0].SetTitle("data")

        hist_style = sc.style_container(style = 'CMS', useRoot = False,cms=13,lumi=19700)
        hist_style.Set_additional_text('plot dummy')

        test = plotter(sig=bghists.getHistList(),style=hist_style)
        # test.Add_data(dat_hist.getHistList()[0])
        # test.Add_plot('Signi',pos=0, height=15)

        #test.Add_plot('DiffRatio',pos=1, height=15)
        # test.Add_plot('Signi',pos=2, height=15)
        # test.Add_plot('Diff',pos=1, height=15)

        # test.Add_plot('Ratio',pos=2, height=15)
        #test.Add_error_hist([sys_hist_2,sys_hist], band_center = 'ref')

        test._cms_text_x         = 0.12
        test._cms_text_y         = 0.91
# 
        # mxrange=getDictValue(hist,xranges)
        if hist in xranges.keys():
            test.Set_axis(xmin=xranges[hist][0],xmax=xranges[hist][1],ymin=1e-3,ymax=1e3)

        name=hist.replace("/","")

        test.create_plot()

        plot_gauss_fit(test.Get_axis1(), bghists.getHistList()[0], xmin = -0.5, xmax = 0.5)

        # test.show_fig()

        test.SavePlot('plots/%s.pdf'%(name))
    return 42
Example #6
0
def main():

    hists=[
    'emu/Stage_0/h1_0_emu_Mass',
    ]

    binning={
            "Taus/h1_2_Tau_pt":10,
    }

    binning.update({"emu/Stage_0/h1_0_emu_Mass":get_binning_from_hist('res_unc.root','func',[0,4000],min_binning = 5)})

    xranges={
            "emu/Stage_0/h1_0_emu_Mass":[50,3000],
    }

    for hist in hists:
        print("Now plotting: " + hist)
        histContainer.getHist(hist)

        binf=getDictValue(hist,binning)
        if binf is not None:
            # dat_hist.rebin(width=1,vector=binf)
            bghists.rebin(width=1,vector=binf)
            # sghist.rebin(width=1,vector=binf)

        hist_style = sc.style_container(style = 'CMS', useRoot = False,cms=13,lumi=lumi, cmsPositon = 'upper left')

        dummy = bghists.getAllAdded()
        dummy.xaxis.SetTitle('')
        dummy.yaxis.SetTitle('')
        dummy.SaveAs('plots/' + hist.replace("/","") + '.root')

        test = plotter(hist=bghists.getHistList(),style=hist_style)
        # test.Add_data(dat_hist.getHistList()[0])

        hist_style.Set_error_bands_fcol(['gray','orange'])
        hist_style.Set_error_bands_ecol(['black','black'])
        hist_style.Set_error_bands_labl(['Systematics','Statistic'])

        if hist == 'emu/Stage_0/h1_0_emu_Mass':
            sys_file=File('syst/for_plotting.root', "read")
        
            test.Add_error_hist([sys_file.Get('Sys'),sys_file.Get('MC statistic')], band_center = 'ref', stacking = 'Nosum')
            # test.Add_error_hist([sys_file.Get('MC statistic')], band_center = 'ref', stacking = 'Nosum')

        # test.Add_plot('Diff',pos=0, height=12)
# 
        # test.Add_plot('DiffRatio',pos=1, height=12)
        # test.Add_plot('Signi',pos=2, height=12)

        if hist in xranges.keys():
            test.Set_axis(logx=True,logy=True,xmin=xranges[hist][0],xmax=xranges[hist][1],ymin=1e-6,ymax=1e3)

        name=hist.replace("/","")

        test.create_plot()

        # test.Get_axis0().set_ylim(ymin = -1.2, ymax = 1.7)
        # test.Get_axis2().set_ylim(ymin = -3, ymax = 13)
        # test.Get_axis3().set_ylim(ymin = -2, ymax = 2.0)

        test.SavePlot('plots/test.pdf')
    return 42