diff --git a/analysis/PbbJet/h3_n2ddt_CA15.root b/analysis/PbbJet/h3_n2ddt_CA15.root new file mode 100644 index 0000000..efb886c Binary files /dev/null and b/analysis/PbbJet/h3_n2ddt_CA15.root differ diff --git a/analysis/ZqqJet/failN2DDT.root b/analysis/ZqqJet/failN2DDT.root new file mode 100644 index 0000000..f4270ea Binary files /dev/null and b/analysis/ZqqJet/failN2DDT.root differ diff --git a/analysis/ZqqJet/passN2DDT.root b/analysis/ZqqJet/passN2DDT.root new file mode 100644 index 0000000..c8158ac Binary files /dev/null and b/analysis/ZqqJet/passN2DDT.root differ diff --git a/analysis/ZqqJet/plotDDT.py b/analysis/ZqqJet/plotDDT.py new file mode 100644 index 0000000..75dc551 --- /dev/null +++ b/analysis/ZqqJet/plotDDT.py @@ -0,0 +1,96 @@ +import ROOT +from ROOT import TFile, TTree, TChain, gPad, gDirectory +from multiprocessing import Process +from optparse import OptionParser +from operator import add +from array import array +import math +import sys +import time + +############################################################################## +def main(options,args): + + + c_ptH = ROOT.TCanvas("c_ptH","c_ptH",800,600) + file_in = ROOT.TFile.Open("h3_n2ddt_26eff_36binrho11pt_Spring16.root") + file_in.cd() + + tt = file_in.Get('h2ddt').Clone() + + tt.Draw('COLZ') + tt.SetContour(999) + ROOT.gPad.Update() + #c_ptH.cd() + #tt.GetXaxis().SetTitle('#rho = ln(m_{SD}^{2}/p_{T}^{2})') + tt.GetXaxis().SetTitle('#rho') + tt.GetYaxis().SetTitle('p_{T} (GeV)') + tt.GetXaxis().SetTitleSize(0.05) + tt.GetYaxis().SetTitleSize(0.05) + tt.GetXaxis().SetTitleOffset(1) + tt.GetYaxis().SetTitleOffset(1.2) + tt.GetXaxis().SetLabelSize(0.045) + tt.GetYaxis().SetLabelSize(0.045) + tt.GetZaxis().SetLabelSize(0.045) + tt.GetZaxis().SetTitleSize(0.05) + tt.GetZaxis().SetTitleOffset(1.2) + tt.GetZaxis().SetTitle('N_{2}^{1} cut at 26% QCD eff') + palette = ROOT.TPaletteAxis(-1.45,450,-1.1,1000,tt) + tt.Draw('COL') + palette.Draw() + tag1 = ROOT.TLatex(0.67, 0.92, "35.9 fb^{-1} (13 TeV)") + tag1.SetNDC() + tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.17, 0.92, "CMS") + tag2.SetTextSize(0.055) + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.27, 0.92, "Simulation Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + #tag1.Draw() + tag2.Draw() + tag3.Draw() + + c_ptH.SaveAs("DDT.pdf"); + c_ptH.SaveAs("DDT.C"); + c_ptH.SaveAs("DDT.png"); + +##----##----##----##----##----##----## +if __name__ == '__main__': + parser = OptionParser() + + (options, args) = parser.parse_args() + + import tdrstyle + tdrstyle.setTDRStyle() + ROOT.gStyle.SetPadTopMargin(0.10) + ROOT.gStyle.SetPadLeftMargin(0.16) + ROOT.gStyle.SetPadRightMargin(0.18) + ROOT.gStyle.SetPaintTextFormat("1.1f") + ROOT.gStyle.SetOptStat(0000) + ROOT.gStyle.SetOptFit(0000) + ROOT.gROOT.SetBatch() + #ROOT.gStyle.SetPalette(ROOT.kBlackBody) + #ROOT.gStyle.SetPalette(ROOT.kBird) + stops = [ 0.0, 1.0] + red = [ 1.0, 0.3] + green = [ 1.0, 0.3] + blue = [ 1.0, 1.0] + + s = array('d', stops) + r = array('d', red) + g = array('d', green) + b = array('d', blue) + + npoints = len(s) + ROOT.TColor.CreateGradientColorTable(npoints, s, r, g, b, 999) + + ROOT.gStyle.SetNumberContours(999) + + main(options,args) +##----##----##----##----##----##----## + diff --git a/analysis/comparisonSignals.py b/analysis/comparisonSignals.py index 9a5010b..2d3340c 100644 --- a/analysis/comparisonSignals.py +++ b/analysis/comparisonSignals.py @@ -18,6 +18,7 @@ def main(options,args): #idir = "/eos/uscms/store/user/lpchbb/ggHsample_V11/sklim-v0-28Oct/" #odir = "plots_2016_10_31/" idir = options.idir + idirData = 'root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.05/' odir = options.odir lumi = options.lumi @@ -31,7 +32,7 @@ def main(options,args): 'Phibb': ' Phi(125)(b#bar{b})'} - tfiles = {#'ggHbb': [idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_0_ptw_1000pb_weighted.root'],#amcatnloFXFX_pythia8_1000pb_weighted.root'], + tfiles = {#'ggHbb': [idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_CKKW_1000pb_weighted.root'] 'ggHbbp': [idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted.root'], 'VBFHbb': [idir+'/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root'], 'ZHbb': [idir+'/ZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', @@ -113,8 +114,9 @@ def main(options,args): ofile.cd() for process, h in hs.iteritems(): h.Write() + - #c.Write() + c.Write() diff --git a/analysis/controlPlotsVH.py b/analysis/controlPlotsVH.py new file mode 100644 index 0000000..8336e1a --- /dev/null +++ b/analysis/controlPlotsVH.py @@ -0,0 +1,490 @@ +import ROOT +from ROOT import TFile, TTree, TChain, gPad, gDirectory +from multiprocessing import Process +from optparse import OptionParser +from operator import add +import math +import sys +import time +import array +import glob +import os +from plotHelpers1lep import * +from sampleContainer1lep import * + +DBTMIN = -99 + + +# +def makePlots(plot, hs, hb, hd, hall, legname, color, style, isData, odir, lumi, ofile, canvases): + if isData: + c = makeCanvasComparisonStackWData(hd, hs, hb, legname, color, style, plot.replace('h_', 'stack_'), odir, lumi, + ofile) + canvases.append(c) + else: + c = makeCanvasComparisonStack(hs, hb, legname, color, style, 'WHbb', plot.replace('h_', 'stack_'), odir, lumi, + True, ofile) + # c1 = makeCanvasComparison(hall, legname, color, style, plot.replace('h_', 'signalcomparison_'), odir, lumi, + # ofile, True) + canvases.append(c) + #canvases.append(c1) + + +############################################################################## +def main(options, args, outputExists): + # idir = "/eos/uscms/store/user/lpchbb/ggHsample_V11/sklim-v0-28Oct/" + # odir = "plots_2016_10_31/" + # idir = options.idir + idir = "root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.04/norm2/cvernier/" + idirWH = "root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.04/cvernier/" + idirMuon = "root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.04/cvernier/" + idirData = 'root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.05/' + odir = options.odir + lumi = options.lumi + fillCA15 = options.fillCA15 + isData = options.isData + muonCR = options.muonCR + + legname = {'ggHbb': 'ggH(b#bar{b})', + 'Hbb': 'H(b#bar{b})', + 'VBFHbb': 'VBF H(b#bar{b})', + 'ZHbb': 'ZH(b#bar{b})', + 'WHbb': ' WH(b#bar{b})', + 'ttHbb': 't#bar{t}H(b#bar{b})', + 'Diboson': 'WW+WZ+ZZ', + 'SingleTop': 'single-t', + 'DY': 'Z(qq)+jets', + 'W': 'W(qq)+jets', + 'DYll': 'Z(ll)+jets', + 'Wlnu': 'W(l#nu)+jets', + 'TTbar': 't#bar{t}+jets', + 'TTbar1Mu': 't#bar{t}+jets, 1#mu', + 'TTbar1Ele': 't#bar{t}+jets, 1e', + 'TTbar1Tau': 't#bar{t}+jets, 1#tau', + 'TTbar1Lep': 't#bar{t}+jets, 1l', + 'TTbar0Lep': 't#bar{t}+jets, 0l', + 'TTbar2Lep': 't#bar{t}+jets, 2l', + 'QCD': 'QCD', + 'data': 'JetHT data', + 'muon': 'SingleMuon data', + 'Phibb50': '#Phi(b#bar{b}), 50 GeV', + 'Phibb75': '#Phi(b#bar{b}), 75 GeV', + 'Phibb150': '#Phi(b#bar{b}), 150 GeV', + 'Phibb250': '#Phi(b#bar{b}), 250 GeV' + } + + if isData and muonCR: + legname['data'] = 'SingleMuon data' + + tfiles = {'Hbb': [idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_CKKW_1000pb_weighted.root', + idir + '/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root', + idir + '/ZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + '/WminusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + '/WplusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir + '/ttHTobb_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir + '/ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir + '/ggZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + '/ZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'ggHbb': [idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_CKKW_1000pb_weighted.root'], + # idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'VBFHbb': [idir + '/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root'], + 'ZHbb': [idirWH + '/ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + '/ZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root', + idirWH + '/ZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + '/ggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8_1000pb_weighted.root'], + 'WHbb': [idirWH + '/WminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + 'WplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root'], + 'Diboson': [idir + '/WW_13TeV_pythia8_1000pb_weighted.root', + idir + '/ZZ_13TeV_pythia8_1000pb_weighted.root', + idir + 'WZ_13TeV_pythia8_1000pb_weighted.root'], + 'ttHbb': [idir + '/ttHTobb_M125_13TeV_powheg_pythia8_1000pb_weighted.root'], + # ttHTobb_M125_TuneCUETP8M2_ttHtranche3_13TeV_powheg_pythia8_1000pb_weighted.root'], + 'DY': [idirData + '/DYJetsToQQ_HT180_13TeV_1000pb_weighted.root'], + 'DYll': [idir + '/DYJetsToLL_M_50_13TeV_ext_1000pb_weighted.root'], + 'SingleTop': [ + idir + '/ST_t_channel_antitop_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV_powhegV2_madspin_1000pb_weighted.root', + idir + '/ST_t_channel_top_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV_powhegV2_madspin_1000pb_weighted.root', + idir + '/ST_tW_antitop_5f_inclusiveDecays_13TeV_powheg_pythia8_TuneCUETP8M2T4_1000pb_weighted.root', + idir + '/ST_tW_top_5f_inclusiveDecays_13TeV_powheg_pythia8_TuneCUETP8M2T4_1000pb_weighted.root'], + 'W': [idirData + '/WJetsToQQ_HT180_13TeV_1000pb_weighted.root'], + 'Wlnu': [idir + 'WJetsToLNu_HT_100To200_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_200To400_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_400To600_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_600To800_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_800To1200_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_1200To2500_13TeV_1000pb_weighted.root', + idir + '/WJetsToLNu_HT_2500ToInf_13TeV_1000pb_weighted.root'], + 'TTbar': [idir + '/TT_powheg_1000pb_weighted.root'], # Powheg is the new default + 'QCD': [idirData + '/QCD_HT100to200_13TeV_1000pb_weighted.root', + idirData + '/QCD_HT200to300_13TeV_1000pb_weighted.root', + idirData + '/QCD_HT300to500_13TeV_all_1000pb_weighted.root', + idirData + '/QCD_HT500to700_13TeV_1000pb_weighted.root', + idirData + '/QCD_HT700to1000_13TeV_1000pb_weighted.root', + idirData + '/QCD_HT1000to1500_13TeV_1000pb_weighted.root', + idirData + '/QCD_HT1500to2000_13TeV_all_1000pb_weighted.root', + idirData + '/QCD_HT2000toInf_13TeV_all_1000pb_weighted.root'], + 'Phibb50': [idirData + '/Spin0_ggPhibb1j_g1_50_Scalar_1000pb_weighted.root'], + 'Phibb75': [idirData + '/Spin0_ggPhibb1j_g1_75_Scalar_1000pb_weighted.root'], + 'Phibb150': [idirData + '/Spin0_ggPhibb1j_g1_150_Scalar_1000pb_weighted.root'], + 'Phibb250': [idirData + '/Spin0_ggPhibb1j_g1_250_Scalar_1000pb_weighted.root'], + 'data': [ + idirData + 'JetHTRun2016B_03Feb2017_ver2_v2_v3.root', + idirData + 'JetHTRun2016B_03Feb2017_ver1_v1_v3.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_0.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_1.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_2.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_3.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_4.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_5.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_6.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_7.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_8.root', + idirData + 'JetHTRun2016C_03Feb2017_v1_v3_9.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_0.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_1.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_10.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_11.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_12.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_13.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_14.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_2.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_3.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_4.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_5.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_6.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_7.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_8.root', + idirData + 'JetHTRun2016D_03Feb2017_v1_v3_9.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_0.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_1.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_2.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_3.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_4.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_5.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_6.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_7.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_8.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_9.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_10.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_11.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_12.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_13.root', + idirData + 'JetHTRun2016E_03Feb2017_v1_v3_14.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_0.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_1.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_2.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_3.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_4.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_5.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_6.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_7.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_8.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_9.root', + idirData + 'JetHTRun2016F_03Feb2017_v1_v3_10.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_0.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_1.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_2.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_3.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_4.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_5.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_6.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_7.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_8.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_9.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_10.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_11.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_12.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_13.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_14.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_15.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_16.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_17.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_18.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_19.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_20.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_21.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_22.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_23.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_24.root', + idirData + 'JetHTRun2016G_03Feb2017_v1_v3_25.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_0.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_1.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_2.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_3.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_4.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_5.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_6.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_7.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_8.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_9.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_10.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_11.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_12.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_13.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_14.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_15.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_16.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_17.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_18.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_19.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_20.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_21.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_22.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_23.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_24.root', + idirData + 'JetHTRun2016H_03Feb2017_ver2_v1_v3_25.root', + idirData + 'JetHTRun2016H_03Feb2017_ver3_v1_v3.root'], + 'muon': [idirMuon + '/SingleMuonRun2016B_03Feb2017_ver1_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016B_03Feb2017_ver2_v2_fixtrig.root', + idirMuon + '/SingleMuonRun2016C_03Feb2017_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016D_03Feb2017_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016E_03Feb2017_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016F_03Feb2017_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016G_03Feb2017_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016H_03Feb2017_ver2_v1_fixtrig.root', + idirMuon + '/SingleMuonRun2016H_03Feb2017_ver3_v1_fixtrig.root'] + + } + + color = {'ggHbb': ROOT.kAzure + 1, + 'Hbb': ROOT.kRed, + 'ZHbb': ROOT.kTeal + 1, + 'WHbb': ROOT.kTeal + 2, + 'VBFHbb': ROOT.kBlue - 10, + 'Phibb50': ROOT.kBlue - 1, + 'Phibb75': ROOT.kAzure + 1, + 'Phibb150': ROOT.kTeal + 1, + 'Phibb250': ROOT.kMagenta + 1, + 'ttHbb': ROOT.kBlue - 1, + 'Diboson': ROOT.kOrange, + 'SingleTop': ROOT.kRed - 2, + 'DY': ROOT.kRed, + 'DYll': ROOT.kRed - 3, + 'W': ROOT.kGreen + 3, + 'Wlnu': ROOT.kGreen + 2, + 'TTbar': ROOT.kGray, + 'TTbar1Mu': ROOT.kViolet, + 'TTbar1Lep': ROOT.kViolet, + 'TTbar1Ele': ROOT.kSpring, + 'TTbar1Tau': ROOT.kOrange + 2, + 'TTbar0Lep': ROOT.kGray, + 'TTbar2Lep': ROOT.kMagenta - 9, + 'QCD': ROOT.kAzure + 6, + 'data': ROOT.kBlack, + 'muon': ROOT.kBlack + } + + style = {'Hbb': 1, + 'ggHbb': 2, + 'Phibb50': 2, + 'Phibb75': 3, + 'Phibb150': 4, + 'Phibb250': 5, + 'VBFHbb': 3, + 'ZHbb': 4, + 'WHbb': 4, + 'ttHbb': 5, + 'Diboson': 1, + 'SingleTop': 1, + 'DY': 1, + 'DYll': 1, + 'W': 1, + 'Wlnu': 1, + 'TTbar': 1, + 'TTbar1Mu': 1, + 'TTbar1Lep': 1, + 'TTbar1Ele': 1, + 'TTbar1Tau': 1, + 'TTbar0Lep': 1, + 'TTbar2Lep': 1, + 'QCD': 1, + 'data': 1, + 'muon': 1 + } + + canvases = [] + if isData and muonCR: + plots = [] + testSample = sampleContainer('test', [], 1, DBTMIN, lumi) + for attr in dir(testSample): + try: + if 'h_' in attr and getattr(testSample, attr).InheritsFrom('TH1') and not getattr(testSample, + attr).InheritsFrom( + 'TH2'): + plots.append(attr) + except: + pass + elif isData: + plots = ['h_pt_ak8', 'h_msd_ak8', 'h_dbtag_ak8', 'h_n_ak4', 'h_n_ak4_dR0p8', 'h_t21_ak8', 'h_t32_ak8', + 'h_n2b1sdddt_ak8', 'h_t21ddt_ak8', 'h_met', 'h_npv', 'h_eta_ak8', 'h_ht', 'h_dbtag_ak8_aftercut', + 'h_n2b1sdddt_ak8_aftercut', 'h_rho_ak8'] + else: + plots = [] + testSample = sampleContainer('test', [], 1, DBTMIN, lumi) + for attr in dir(testSample): + try: + if 'h_' in attr and getattr(testSample, attr).InheritsFrom('TH1') and not getattr(testSample, + attr).InheritsFrom( + 'TH2'): + plots.append(attr) + except: + pass + + if not outputExists: + samples = ['ggHbb', 'VBFHbb', 'ZHbb', 'WHbb', 'QCD', 'SingleTop', 'Diboson', 'W', 'DY', 'TTbar'] + # for s in samples: + # for tfile in tfiles[s]: + # if not os.path.isfile(tfile): + # print 'error: %s does not exist'%tfile + # sys.exit() + print "Signals... " + sigSamples = {} + # sigSamples['ggHbb'] = sampleContainer('ggHbb',tfiles['ggHbb'] , 1, DBTMIN, lumi, False, fillCA15) + # sigSamples['VBFHbb'] = sampleContainer('VBFHbb',tfiles['VBFHbb'], 1, DBTMIN, lumi, False, fillCA15) + # sigSamples['VHbb'] = sampleContainer('VHbb',tfiles['VHbb'], 1, DBTMIN, lumi, False, fillCA15) + # sigSamples['ttHbb'] = sampleContainer('ttHbb',tfiles['ttHbb'], 1, DBTMIN, lumi, False, fillCA15) + # sigSamples['Phibb50'] = sampleContainer('Phibb50',tfiles['Phibb50'] , 1, 0.2480*lumi, False, fillCA15) + # sigSamples['Phibb75'] = sampleContainer('Phibb75',tfiles['Phibb75'], 1, 0.2080*lumi, False, fillCA15) + # sigSamples['Phibb150'] = sampleContainer('Phibb150',tfiles['Phibb150'], 1, 0.2764*lumi, False, fillCA15) + # sigSamples['Phibb250'] = sampleContainer('Phibb250',tfiles['Phibb250'], 1, 0.6699*lumi, False, fillCA15) + sigSamples['WHbb'] = sampleContainer('WHbb', tfiles['WHbb'], 1, DBTMIN, lumi, False, fillCA15) + sigSamples['ZHbb'] = sampleContainer('ZHbb', tfiles['ZHbb'], 1, DBTMIN, lumi, False, fillCA15) + print "Backgrounds..." + bkgSamples = {} + # bkgSamples['W'] = sampleContainer('W',tfiles['W'], 1, DBTMIN, lumi, False, fillCA15) + # bkgSamples['DY'] = sampleContainer('DY',tfiles['DY'], 1, DBTMIN, lumi, False, fillCA15) + + bkgSamples['QCD'] = sampleContainer('QCD', tfiles['QCD'], 1000, DBTMIN, lumi, False, fillCA15) + if muonCR: + bkgSamples['Wlnu'] = sampleContainer('Wlnu', tfiles['Wlnu'], 1, DBTMIN, lumi, False, fillCA15) + bkgSamples['DYll'] = sampleContainer('DYll', tfiles['DYll'], 1, DBTMIN, lumi, False, fillCA15) + # bkgSamples['TTbar1Mu'] = sampleContainer('TTbar1Mu',tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, 'genMuFromW==1&&genEleFromW+genTauFromW==0') + # bkgSamples['TTbar1Ele'] = sampleContainer('TTbar1Ele',tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, 'genEleFromW==1&&genMuFromW+genTauFromW==0') + # bkgSamples['TTbar1Tau'] = sampleContainer('TTbar1Tau',tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, 'genTauFromW==1&&genEleFromW+genMuFromW==0') + bkgSamples['TTbar1Lep'] = sampleContainer('TTbar1Lep', tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, + 'genMuFromW+genEleFromW+genTauFromW==1') + bkgSamples['TTbar0Lep'] = sampleContainer('TTbar0Lep', tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, + 'genMuFromW+genEleFromW+genTauFromW==0') + bkgSamples['TTbar2Lep'] = sampleContainer('TTbar2Lep', tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15, + 'genMuFromW+genEleFromW+genTauFromW==2') + else: + bkgSamples['TTbar'] = sampleContainer('TTbar', tfiles['TTbar'], 1, DBTMIN, lumi, False, fillCA15) + bkgSamples['SingleTop'] = sampleContainer('SingleTop', tfiles['SingleTop'], 1, DBTMIN, lumi, False, fillCA15) + bkgSamples['Diboson'] = sampleContainer('Diboson', tfiles['Diboson'], 1, DBTMIN, lumi, False, fillCA15) + # bkgSamples['Hbb'] = sampleContainer('Hbb',tfiles['Hbb'], 1, lumi ) + + if isData: + print "Data..." + if isData and muonCR: + dataSample = sampleContainer('muon', tfiles['muon'], 1, DBTMIN, lumi, isData, fillCA15, + '((triggerBits&4)&&passJson)') + elif isData: + dataSample = sampleContainer('data', tfiles['data'], 1, DBTMIN, lumi, isData, fillCA15, + '((triggerBits&2)&&passJson)') + + ofile = ROOT.TFile.Open(odir + '/Plots_1000pb_weighted.root ', 'recreate') + + hall_byproc = {} + for process, s in sigSamples.iteritems(): + hall_byproc[process] = {} + for process, s in bkgSamples.iteritems(): + hall_byproc[process] = {} + if isData: + if muonCR: + hall_byproc['muon'] = {} + else: + hall_byproc['data'] = {} + + for plot in plots: + for process, s in sigSamples.iteritems(): + hall_byproc[process][plot] = getattr(s, plot) + for process, s in bkgSamples.iteritems(): + hall_byproc[process][plot] = getattr(s, plot) + if isData: + if muonCR: + hall_byproc['muon'][plot] = getattr(dataSample, plot) + else: + hall_byproc['data'][plot] = getattr(dataSample, plot) + + ofile.cd() + for proc, hDict in hall_byproc.iteritems(): + for plot, h in hDict.iteritems(): + h.Write() + + for plot in plots: + hs = {} + hb = {} + hall = {} + hd = None + for process, s in sigSamples.iteritems(): + hs[process] = getattr(s, plot) + hall[process] = getattr(s, plot) + for process, s in bkgSamples.iteritems(): + hb[process] = getattr(s, plot) + hall[process] = getattr(s, plot) + if isData: + hd = getattr(dataSample, plot) + makePlots(plot, hs, hb, hd, hall, legname, color, style, isData, odir, lumi, ofile, canvases) + + ofile.Close() + else: + sigSamples = ['ggHbb', 'VBFHbb', 'WHbb', 'ZHbb'] + bkgSamples = ['QCD', 'SingleTop', 'Diboson', 'W', 'DY'] + if muonCR: + bkgSamples.extend(['Wlnu', 'DYll', 'TTbar1Lep', 'TTbar0Lep', 'TTbar2Lep']) + else: + bkgSamples.extend(['TTbar']) + + ofile = ROOT.TFile.Open(odir + '/Plots_1000pb_weighted.root', 'read') + for plot in plots: + hb = {} + hs = {} + hall = {} + hd = None + for process in bkgSamples: + hb[process] = ofile.Get(plot.replace('h_', 'h_%s_' % process)) + hall[process] = ofile.Get(plot.replace('h_', 'h_%s_' % process)) + for process in sigSamples: + hs[process] = ofile.Get(plot.replace('h_', 'h_%s_' % process)) + hall[process] = ofile.Get(plot.replace('h_', 'h_%s_' % process)) + if isData and muonCR: + hd = ofile.Get(plot.replace('h_', 'h_muon_')) + elif isData: + hd = ofile.Get(plot.replace('h_', 'h_data_')) + print plot + makePlots(plot, hs, hb, hd, hall, legname, color, style, isData, odir, lumi, ofile, canvases) + + +##----##----##----##----##----##----## +if __name__ == '__main__': + + parser = OptionParser() + parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') + parser.add_option("--lumi", dest="lumi", default=35.9, type=float, help="luminosity", metavar="lumi") + parser.add_option('-i', '--idir', dest='idir', default='data/', help='directory with data', metavar='idir') + parser.add_option('-o', '--odir', dest='odir', default='plots/', help='directory to write plots', metavar='odir') + parser.add_option('-s', '--isData', action='store_true', dest='isData', default=False, help='signal comparison', + metavar='isData') + parser.add_option('-m', '--muonCR', action='store_true', dest='muonCR', default=False, help='for muon CR', + metavar='muonCR') + parser.add_option('-c','--fillCA15', action='store_true', dest='fillCA15', default =False,help='for CA15', metavar='fillCA15') + + (options, args) = parser.parse_args() + + import tdrstyle + + tdrstyle.setTDRStyle() + ROOT.gStyle.SetPadTopMargin(0.10) + ROOT.gStyle.SetPadLeftMargin(0.16) + ROOT.gStyle.SetPadRightMargin(0.10) + # ROOT.gStyle.SetPalette(1) + ROOT.gStyle.SetPaintTextFormat("1.1f") + ROOT.gStyle.SetOptFit(0000) + ROOT.gROOT.SetBatch() + + outputExists = False + if glob.glob(options.odir + '/Plots_1000pb_weighted.root'): + outputExists = True + + main(options, args, outputExists) +##----##----##----##----##----##----## diff --git a/analysis/doCutFlowVH.py b/analysis/doCutFlowVH.py new file mode 100644 index 0000000..1244135 --- /dev/null +++ b/analysis/doCutFlowVH.py @@ -0,0 +1,169 @@ +import ROOT +from ROOT import TFile, TTree, TChain, gPad, gDirectory +from multiprocessing import Process +from optparse import OptionParser +from operator import add +import math +import sys +import time +import array + +from plotHelpers1lep import * +from sampleContainer1lep import * +# + +############################################################################## +def main(options,args): + #idir = "/eos/uscms/store/user/lpchbb/ggHsample_V11/sklim-v0-28Oct/" + #odir = "plots_2016_10_31/" + idir = "root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.04/norm2/cvernier/" + idirWH = "root://cmseos.fnal.gov//eos/uscms/store/user/lpchbb/zprimebits-v12.04/cvernier/" + #idir = options.idir + odir = options.odir + lumi = options.lumi + + + legname = {'ggHbb': 'ggH(b#bar{b})', + 'Hbb': 'H(b#bar{b})', + 'VBFHbb':'VBF H(b#bar{b})', + 'WHbb': 'WH(b#bar{b})', + 'Wlnu': 'W+jets', + 'TTbar': 't#bar{t}+jets', + 'QCD': 'QCD', + } + tfiles = {'Hbb': [idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted.root', + idir+'/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root', + idir+'/ZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/WminusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/WplusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ttHTobb_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ggZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'ggHbb': [idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted.root'], + # idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'VBFHbb': [idir+'/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root'], + 'WHbb': [idirWH + '/WminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idirWH + 'WplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root'], + 'VHbb': [idir+'/ZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/WminusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/WplusH_HToBB_WToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ggZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', + idir+'/ZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'ttHbb': [idir+'/ttHTobb_M125_13TeV_powheg_pythia8_1000pb_weighted.root'],#ttHTobb_M125_TuneCUETP8M2_ttHtranche3_13TeV_powheg_pythia8_1000pb_weighted.root'], + 'Diboson': [idir+'/WWTo4Q_13TeV_powheg_1000pb_weighted.root', + idir+'/ZZ_13TeV_pythia8_1000pb_weighted.root',#ZZTo4Q_13TeV_amcatnloFXFX_madspin_pythia8_1000pb_weighted.root', + idir+'/WZ_13TeV_pythia8_1000pb_weighted.root'], + 'DY': [idir+'/DYJetsToQQ_HT180_13TeV_1000pb_weighted.root'], + 'DYll': [idir+'/DYJetsToLL_M_50_13TeV_ext_1000pb_weighted.root'], + 'SingleTop': [idir+'/ST_t_channel_antitop_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV_powhegV2_madspin_1000pb_weighted.root', + idir+'/ST_t_channel_top_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV_powhegV2_madspin_1000pb_weighted.root', + idir+'/ST_tW_antitop_5f_inclusiveDecays_13TeV_powheg_pythia8_TuneCUETP8M2T4_1000pb_weighted.root', + idir+'/ST_tW_top_5f_inclusiveDecays_13TeV_powheg_pythia8_TuneCUETP8M2T4_1000pb_weighted.root'], + 'W': [idir+'/WJetsToQQ_HT180_13TeV_1000pb_weighted.root'], + 'Wlnu': [idir+'WJetsToLNu_HT_100To200_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_200To400_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_400To600_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_600To800_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_800To1200_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_1200To2500_13TeV_1000pb_weighted.root', + idir+'/WJetsToLNu_HT_2500ToInf_13TeV_1000pb_weighted.root'], + 'TTbar': [idir+'/TT_powheg_1000pb_weighted.root'], #Powheg is the new default + 'QCD': [idir+'/QCD_HT100to200_13TeV_1000pb_weighted.root', + idir+'/QCD_HT200to300_13TeV_all_1000pb_weighted.root', + idir+'/QCD_HT300to500_13TeV_all_1000pb_weighted.root', + idir+'/QCD_HT500to700_13TeV_ext_1000pb_weighted.root', + idir+'/QCD_HT700to1000_13TeV_ext_1000pb_weighted.root', + idir+'/QCD_HT1000to1500_13TeV_all_1000pb_weighted.root', + idir+'/QCD_HT1500to2000_13TeV_all_1000pb_weighted.root', + idir+'/QCD_HT2000toInf_13TeV_1000pb_weighted.root'], + + } + + color = {'ggHbb': ROOT.kRed+1, + 'Hbb': ROOT.kRed, + 'WHbb': ROOT.kTeal+1, + 'VBFHbb': ROOT.kAzure+2, + 'Wlnu': ROOT.kOrange+1, + 'TTbar': ROOT.kGray, + 'QCD': ROOT.kBlue+2, + } + + style = {'Hbb': 1, + 'ggHbb': 2, + 'Phibb50': 2, + 'Phibb75': 3, + 'Phibb150': 4, + 'Phibb250': 5, + 'VBFHbb': 1, + 'WHbb': 4, + 'Wlnu': 5, + 'TTbar': 1, + 'QCD': 1, + } + + print "Signals... " + sigSamples = {} + #sigSamples['ggHbb'] = sampleContainer('ggHbb',tfiles['ggHbb'] , 1, lumi) + sigSamples['WHbb'] = sampleContainer('WHbb',tfiles['WHbb'], 1, lumi ) + #sigSamples['VHbb'] = sampleContainer('VHbb',tfiles['VHbb'], 1, lumi ) + #sigSamples['ttHbb'] = sampleContainer('ttHbb',tfiles['ttHbb'], 1, lumi ) + #sigSamples['Phibb50'] = sampleContainer('Phibb50',tfiles['Phibb50'] , 1, 0.2480*lumi) + #sigSamples['Phibb75'] = sampleContainer('Phibb75',tfiles['Phibb75'], 1, 0.2080*lumi ) + #sigSamples['Phibb150'] = sampleContainer('Phibb150',tfiles['Phibb150'], 1, 0.2764*lumi ) + #sigSamples['Phibb250'] = sampleContainer('Phibb250',tfiles['Phibb250'], 1, 0.6699*lumi ) + print "Backgrounds..." + bkgSamples = {} + bkgSamples['Wlnu'] = sampleContainer('Wlnu',tfiles['Wlnu'], 10, lumi) + bkgSamples['TTbar'] = sampleContainer('TTbar',tfiles['TTbar'], 10, lumi) + #bkgSamples['Hbb'] = sampleContainer('Hbb',tfiles['Hbb'], 1, lumi ) + + ofile = ROOT.TFile.Open(odir+'/Plots_1000pb_weighted.root ','recreate') + + + canvases = [] + plots = ['h_Cuts'] + for plot in plots: + hs = {} + hb = {} + hall={} + for process, s in sigSamples.iteritems(): + hs[process] = getattr(s,plot) + hall[process] = getattr(s,plot) + for process, s in bkgSamples.iteritems(): + hb[process] = getattr(s,plot) + hall[process] = getattr(s,plot) + c = makeCanvasComparisonStack(hs,hb,legname,color,style,'WHbb',plot.replace('h_','stack_'),odir,lumi,ofile) + c1 = makeCanvasComparison(hall,legname,color,style,plot.replace('h_','signalcomparison_'),odir,lumi,ofile) + canvases.append(c) + + +##----##----##----##----##----##----## +if __name__ == '__main__': + + parser = OptionParser() + parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') + parser.add_option("--lumi", dest="lumi", default = 35.9,type=float,help="luminosity", metavar="lumi") + parser.add_option('-i','--idir', dest='idir', default = 'data/',help='directory with data', metavar='idir') + parser.add_option('-o','--odir', dest='odir', default = 'plots/',help='directory to write plots', metavar='odir') + + (options, args) = parser.parse_args() + + + import tdrstyle + tdrstyle.setTDRStyle() + ROOT.gStyle.SetPadTopMargin(0.10) + ROOT.gStyle.SetPadLeftMargin(0.16) + ROOT.gStyle.SetPadRightMargin(0.10) + ROOT.gStyle.SetPalette(1) + ROOT.gStyle.SetPaintTextFormat("1.1f") + ROOT.gStyle.SetOptFit(0000) + ROOT.gROOT.SetBatch() + + main(options,args) +##----##----##----##----##----##----## + + + + diff --git a/analysis/plotHelpers.py b/analysis/plotHelpers.py index e61474c..91ca40f 100644 --- a/analysis/plotHelpers.py +++ b/analysis/plotHelpers.py @@ -22,7 +22,7 @@ def getRatio(hist, reference): ratio.SetBinContent(xbin, val/ref) ratio.SetBinError(xbin, math.sqrt( (val*refE/(ref**2))**2 + (valE/ref)**2 )) except ZeroDivisionError: - ratio.SetBinContent(xbin, 1.0) + #ratio.SetBinContent(xbin, 1.0) ratio.SetBinError(xbin, 0.0) return ratio @@ -587,7 +587,8 @@ def makeCanvasShapeComparison(hs,legname,name,pdir="plots"): def makeCanvasComparison(hs,legname,color,style,name,pdir="plots",lumi=30,ofile=None,unitnorm=False): #color = [ROOT.kBlue,ROOT.kGreen+1,ROOT.kCyan,ROOT.kViolet,ROOT.kBlack,ROOT.kRed,5,2,4,6,7,8,3,5,2,4,6,7,8,3,5] #style = [1,2,5,6,7,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3] - leg = ROOT.TLegend(0.65,0.65,0.9,0.9) + #leg = ROOT.TLegend(0.65,0.65,0.9,0.9) + leg = ROOT.TLegend(0.65,0.62,0.9,0.87) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetTextSize(0.027) @@ -599,12 +600,12 @@ def makeCanvasComparison(hs,legname,color,style,name,pdir="plots",lumi=30,ofile= h.SetLineStyle(style[iname]) h.SetLineWidth(2) h.SetFillStyle(0) - h.GetXaxis().SetLabelSize(0.03) + h.GetXaxis().SetLabelSize(0.04) h.GetXaxis().SetTitleOffset(1.1) - h.GetXaxis().SetTitleSize(0.033) - h.GetYaxis().SetLabelSize(0.03) + h.GetXaxis().SetTitleSize(0.04) + h.GetYaxis().SetLabelSize(0.04) h.GetYaxis().SetTitleOffset(1.2) - h.GetYaxis().SetTitleSize(0.033) + h.GetYaxis().SetTitleSize(0.04) if h.GetMaximum() > maxval: maxval = h.GetMaximum() @@ -622,11 +623,15 @@ def makeCanvasComparison(hs,legname,color,style,name,pdir="plots",lumi=30,ofile= i+=1 if i==1: s.SetMaximum(1.5*maxval) - s.SetMinimum(0.01) + #s.SetMinimum(0.01) + s.SetMinimum(0.4) if unitnorm : s.SetMaximum(100.) s.DrawNormalized("hist") - else: s.Draw("hist") + else: + s.GetXaxis().SetTitle(s.GetXaxis().GetTitle().replace("AK8 m_{SD}^{PUPPI} (GeV)","m_{SD} (GeV)")) + s.GetYaxis().SetTitle("Events / 7 GeV") + s.Draw("hist") else : if unitnorm : s.DrawNormalized("histsame") else : s.Draw("histsame") @@ -636,15 +641,34 @@ def makeCanvasComparison(hs,legname,color,style,name,pdir="plots",lumi=30,ofile= tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) tag1.SetNDC(); tag1.SetTextFont(42) tag1.SetTextSize(0.033) - tag2 = ROOT.TLatex(0.17,0.92,"CMS") + tag2 = ROOT.TLatex(0.18,0.83,"CMS") tag2.SetNDC(); tag2.SetTextFont(62) - tag3 = ROOT.TLatex(0.25,0.92,"Simulation Preliminary") + tag3 = ROOT.TLatex(0.18,0.79,"Simulation") tag3.SetNDC(); tag3.SetTextFont(52) - tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); tag1.Draw(); tag2.Draw(); tag3.Draw() + tag4 = ROOT.TLatex(0.18,0.75,"Preliminary") + tag4.SetNDC(); tag4.SetTextFont(52) + + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); tag4.SetTextSize(0.033); tag1.Draw(); tag2.Draw(); tag3.Draw(); #tag4.Draw() + + + ptRange = [450, 1000] + if 'msd_ak8_topR6_N2_pass' in name: + passTag = 'double-b tag > 0.9' + elif 'msd_ak8_topR6_N2_fail' in name: + passTag = 'double-b tag < 0.9' + if 'msd_ak8_topR6_N2_pass' in name or 'msd_ak8_topR6_N2_fail' in name: + tag5 = ROOT.TLatex(0.31, 0.83, "#splitline{%i < p_{T} < %i GeV}{%s}"%(ptRange[0],ptRange[1],passTag)) + tag5.SetNDC() + tag5.SetTextFont(42) + tag5.SetTextSize(0.025) + tag5.Draw() + c.SaveAs(pdir+"/"+name+".pdf") + c.SaveAs(pdir+"/"+name+".C") ROOT.gPad.SetLogy() c.SaveAs(pdir+"/"+name+"_log.pdf") + c.SaveAs(pdir+"/"+name+"_log.C") if ofile is not None: ofile.cd() c.Write('c'+name) @@ -806,7 +830,7 @@ def makeCanvasComparisonStack(hs,hb,legname,color,style,nameS,outname,pdir="plot return c -def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="plots",lumi=30,ofile=None,normalize=False,ratio=False): +def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="plots",lumi=30,ofile=None,normalize=True,ratio=True): ttbarInt = 0 ttbarErr = 0 ttbarErr2 = 0 @@ -858,6 +882,7 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl h.SetLineStyle(1) h.SetLineWidth(1) h.SetFillStyle(1001) + if h.GetMaximum() > maxval: maxval = h.GetMaximum() allMC=hstack.GetStack().Last().Clone() maxval = max(hd.GetMaximum(),maxval) @@ -868,7 +893,9 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl scalefactor = hd.Integral()/fullmc.Integral(); print "data/mc scale factor = ", scalefactor if normalize: - for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): h.Scale( scalefactor ); + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + if 'QCD' in name: + h.Scale( scalefactor ); hstack2 = ROOT.THStack("hstack2","hstack2"); for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): hstack2.Add(h); @@ -877,6 +904,8 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl h.SetLineStyle(1) h.SetLineWidth(1) h.SetFillStyle(1001) + + for name, h in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): if 'ggH' in name: @@ -884,20 +913,38 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl h.SetLineStyle(style[name]) h.SetLineWidth(2) h.SetFillStyle(0) + - leg_y = 0.88 - (2+len(hb))*0.04 - leg = ROOT.TLegend(0.6,leg_y,0.88,0.88,"data/mc scale factor %.2f"%(scalefactor),"NDC") + leg_y = 0.88 - (2+int(len(hb)/3))*0.03 + leg = ROOT.TLegend(0.2,leg_y,0.5,0.88)#,"data/mc scale factor %.2f"%(scalefactor),"NDC") leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetTextSize(0.035) leg.SetTextFont(42) - + leg2 = ROOT.TLegend(0.5,leg_y,0.78,0.88,) + leg2.SetFillStyle(0) + leg2.SetBorderSize(0) + leg2.SetTextSize(0.035) + leg2.SetTextFont(42) + leg3 = ROOT.TLegend(0.65,leg_y,0.98,0.88,) + leg3.SetFillStyle(0) + leg3.SetBorderSize(0) + leg3.SetTextSize(0.035) + leg3.SetTextFont(42) + + + count=1 for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): - leg.AddEntry(h,legname[name],"f") + if count <4: + if name in 'QCD': leg.AddEntry(h,legname[name]+" (k-factor %.2f)"%scalefactor,"f") + else : leg.AddEntry(h,legname[name],"f") + elif count >3 and count<7 : leg2.AddEntry(h,legname[name],"f") + elif count >6 : leg3.AddEntry(h,legname[name],"f") + count = count+1 for name, h in sorted(hs.iteritems(),key=lambda (k,v): -v.Integral()): if 'ggH' in name: - leg.AddEntry(h,legname[name],"l") - leg.AddEntry(hd,legname['data'],"pe"); + leg3.AddEntry(h,legname[name],"l") + leg3.AddEntry(hd,'Data',"pe"); c = ROOT.TCanvas("c"+outname,"c"+outname,1000,800) c.SetFillStyle(4000) c.SetFrameFillStyle(1000) @@ -910,7 +957,7 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl unten.SetBottomMargin(0.35) else: - oben = ROOT.TPad('oben','oben',0,0.05 ,1.0,1.0) + oben = ROOT.TPad('oben','oben',0,0.03 ,1.0,1.0) unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.0) oben.SetFillStyle(4000) oben.SetFrameFillStyle(1000) @@ -923,7 +970,9 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl oben.cd() hstack2.Draw('hist') - hstack2.SetMaximum(500000.*maxval) + hstack2.SetMaximum(10*maxval) + hstack2.SetMinimum(1.) + hstack2.GetYaxis().SetRangeUser(1.,10*maxval) hstack2.GetYaxis().SetTitle('Events') hstack2.GetYaxis().SetTitleOffset(1.0) hstack2.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) @@ -935,8 +984,43 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl if 'ggH' in name: h.Draw("histsame") leg.Draw() - hstack2.SetMinimum(1e-1) + leg2.Draw() + leg3.Draw() + hstack2.SetMinimum(1) + allMC2=hstack2.GetStack().Last().Clone() + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + if name in 'QCD' : + herr = h.Clone('herr') + herr2 = h.Clone('herr2') + # for ibin in range(1,h.GetNbinsX()+1): print(ibin,herr.GetBinError(ibin),herr.GetBinContent(ibin)) + + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + #for ibin in range(1,h.GetNbinsX()+1): print(ibin,herr.GetBinError(ibin),herr.GetBinContent(ibin)) + if name in 'QCD' : continue + for ibin in range(1,h.GetNbinsX()+1): + valA = herr.GetBinContent(ibin); + evalA = herr.GetBinError(ibin); + valB = h.GetBinContent(ibin); + evalB = h.GetBinError(ibin); + + herr.SetBinContent(ibin,(valA+valB)); + herr.SetBinError(ibin,sqrt(evalA*evalA+evalB*evalB)); + if(valA+valB >0): herr2.SetBinContent(ibin,(valA+valB+sqrt(evalA*evalA+evalB*evalB))/(valA+valB)); + else : herr2.SetBinContent(ibin,1); + #herr2.SetBinError(ibin,sqrt(evalA*evalA+evalB*evalB)); + + + theErrorGraph = ROOT.TGraphErrors(herr) + theErrorGraph.SetFillColor(ROOT.kGray+2) + theErrorGraph.SetFillStyle(3002) + herr.SetFillColor(ROOT.kGray+2) + herr.SetFillStyle(3002) + herr.SetMarkerColor(1111); + leg3.AddEntry(herr,"MC uncert. (stat.)","fl") + hd.Draw('pesames'); + theErrorGraph.Draw('SAME2') + #herr.Draw('ERROR SAME2') tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) tag1.SetNDC(); tag1.SetTextFont(42) tag1.SetTextSize(0.045) @@ -951,16 +1035,18 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl tag1.Draw() tag2.Draw() tag3.Draw() - allMC2=hstack2.GetStack().Last().Clone() + if ratio: unten.cd() - ratio= getRatio(hd,allMC2) + ratio = getRatio(hd,allMC2) + herr3= TOTerror(allMC2,ratio); + toterree = ROOT.TGraphErrors(herr3) ksScore = hd.KolmogorovTest( allMC2 ) chiScore = hd.Chi2Test( allMC2 , "UWCHI2/NDF") print ksScore print chiScore ratio.SetStats(0) - ratio.GetYaxis().SetRangeUser(0,2.5) + ratio.GetYaxis().SetRangeUser(0,5) ratio.GetYaxis().SetNdivisions(504) ratio.GetYaxis().SetTitle("Data/Simulation") ratio.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) @@ -984,17 +1070,35 @@ def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="pl #ratioError = ROOT.TGraphErrors(error) #ratioError.SetFillColor(ROOT.kGray+3) #ratioError.SetFillStyle(3013) - ratio.Draw("E1 ") + ratio.Draw("P E ") + ''' + herr2.SetFillColor(ROOT.kGray+2); + herr2.SetLineColor(ROOT.kGray+2); + herr2.SetFillStyle(3002); + herr2.Draw("hist same"); + ''' + toterree.SetFillColor(ROOT.kGray+2); + toterree.SetLineColor(ROOT.kGray+2); + toterree.SetFillStyle(3002); + toterree.Draw("2 same"); + #toterree.Draw("p"); line.Draw("same") #tKsChi.DrawLatex(0.7,0.895,"#chi^{2}_{ }#lower[0.1]{/^{}#it{NDF} = %.2f}"%(chiScore)) + leg4 = ROOT.TLegend(0.7,0.89,0.5,0.8)#,"data/mc scale factor %.2f"%(scalefactor),"NDC") + leg4.SetFillStyle(0) + leg4.SetBorderSize(0) + leg4.SetTextSize(0.05) + leg4.SetTextFont(42) + leg4.AddEntry(toterree,"MC uncert. (stat.)","fl") + leg4.Draw() c.SaveAs(pdir+"/"+outname+".pdf") - c.SaveAs(pdir+"/"+outname+".C") + c.SaveAs(pdir+"/"+outname+".root") oben.SetLogy() c.SaveAs(pdir+"/"+outname+"_log.pdf") - c.SaveAs(pdir+"/"+outname+"_log.C") + c.SaveAs(pdir+"/"+outname+"_log.root") if ofile is not None: ofile.cd() @@ -1521,3 +1625,57 @@ def makeROCFromHisto(hists,LtoR=True): def dummy(): print "hi"; + + +def TOTerror(hmc, ratio ): + hmc.Sumw2() + den1 = hmc.Clone ("den1"); + den2 = hmc.Clone ("den2"); + + nvar = hmc.GetNbinsX(); + + x1 = [] + y1 = [] + exl1 = [] + eyl1= [] + exh1= [] + eyh1= [] + + for km in range(1,nvar+1): + delta = hmc.GetBinError(km) + den1.SetBinError(km,0) + #den1.SetBinContent(km,hmc.GetBinContent(km) + delta); + #den2.SetBinContent(km,hmc.GetBinContent(km) - delta); + + + # ratio from variation and nominal + ratiop = hmc.Clone("ratiop"); + ratiom = hmc.Clone("ratiom"); + + ratiop.Divide(den1); + ratiom.Divide(den1); + #den1.Divide(ratiop) + #den2.Divide(ratiom) + ''' + for km in range(0,nvar): + if(ratio.GetBinContent(km+1)==0): + y1.append(1.) + eyl1.append(0.) + eyh1.append(0.) + else: + y1.append(1) + eyl1.append(abs(ratiop.GetBinContent(km+1)))# - ratio.GetBinContent(km+1))) + eyh1.append(abs(ratiom.GetBinContent(km+1)))# - ratio.GetBinContent(km+1))) + x1.append(ratio.GetBinCenter(km+1)) + exl1.append(ratio.GetBinWidth(km)/2) + exh1.append(ratio.GetBinWidth(km)/2) + x1Array = array.array ('d', x1) + y1Array = array.array ('d', y1) + exl1Array = array.array ('d', exl1) + eyl1Array = array.array ('d', eyl1) + exh1Array = array.array ('d', exh1) + eyh1Array = array.array ('d', eyh1) + err = ROOT.TGraphAsymmErrors (nvar, x1Array, y1Array, exl1Array, exh1Array, eyl1Array, eyh1Array); + ''' + + return ratiop; diff --git a/analysis/plotHelpers1lep.py b/analysis/plotHelpers1lep.py new file mode 100644 index 0000000..e6aba26 --- /dev/null +++ b/analysis/plotHelpers1lep.py @@ -0,0 +1,1682 @@ +import ROOT +from ROOT import TFile, TTree, TChain, gPad, gDirectory, TVirtualFitter +import math +import sys +from math import sqrt +import time +import array + + +def getRatio(hist, reference): + ratio = hist.Clone("%s_ratio"%hist.GetName()) + ratio.SetDirectory(0) + ratio.SetLineColor(hist.GetLineColor()) + for xbin in xrange(1,reference.GetNbinsX()+1): + ref = reference.GetBinContent(xbin) + val = hist.GetBinContent(xbin) + + refE = reference.GetBinError(xbin) + valE = hist.GetBinError(xbin) + + try: + ratio.SetBinContent(xbin, val/ref) + ratio.SetBinError(xbin, math.sqrt( (val*refE/(ref**2))**2 + (valE/ref)**2 )) + except ZeroDivisionError: + #ratio.SetBinContent(xbin, 1.0) + ratio.SetBinError(xbin, 0.0) + + return ratio + + +def getSoverRootB(hs, hallMC, iBin): + bb=0. + ss=0. + for i in range(iBin, hallMC.GetNbinsX()): + bb+=hallMC.GetBinContent(i) + ss+=hs.GetBinContent(i) + if bb > 0 : + return ss/sqrt(bb) + else: + return 0. + + +def customSort(dictValue): + (k, v) = dictValue + if 'DY' in k: + return 0 + elif 'W' in k: + return -1 + elif 'Diboson' in k or 'VV' in k: + return -2 + elif 'TTbar' in k: + return -3 + elif 'ST' in k or 'SingleTop' in k: + return -4 + elif 'QCD' in k: + return -5 + else: + return -v.Integral() #negative integral + + + +def makeCanvas(hists,normalize=False,odir = "plots"): + + color = [1,2,4,6,7,8,3,4,1,1,7,8] + style = [1,2,2,2,1,2,2,2,2,1,1,1] + options = ["hist", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames", + "histsames"] + + c = ROOT.TCanvas("c"+hists[0].GetName(),"c"+hists[0].GetName(),1000,800); + + max = -999; + + for i in range(len(hists)): + hists[i].SetLineColor(color[i]) + hists[i].SetMarkerColor(color[i]) + hists[i].SetMarkerStyle(20) + hists[i].SetLineStyle(style[i]) + hists[i].SetLineWidth(2) + + if hists[i].GetMaximum() > max: + max = hists[i].GetMaximum(); + hists[0].SetMaximum(max*1.25); + if normalize and hists[i].Integral() > 0: hists[i].Scale(1./hists[i].Integral()) + + hists[i].Draw(options[i]); + + c.SaveAs(odir+hists[0].GetName()+".pdf") + ROOT.gPad.SetLogy(); + c.SaveAs(odir+hists[0].GetName()+"_log.pdf") + +def makeCanvasDataMC(hd,hmcs,legname,name,pdir="plots",nodata=False): + + color = [ROOT.kBlue,ROOT.kGreen+1,ROOT.kCyan,ROOT.kViolet,ROOT.kBlack,ROOT.kRed,5,2,4,6,7,8,3,5,2,4,6,7,8,3,5] + style = [1,2,5,6,7,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3] + for h in range(len(hmcs)): + hmcs[h].SetFillStyle(1001) + hmcs[h].SetLineStyle(style[h]) + hmcs[h].SetLineColor(color[h]) + hmcs[h].SetFillColor(color[h]) + + hstack = ROOT.THStack("hstack","hstack"); + for h in hmcs: hstack.Add(h); + fullmc = hstack.GetStack().Last(); + + # normalize MC to data + scalefactor = hd.Integral()/fullmc.Integral(); + print "data/mc scale factor = ", scalefactor + for i in range(len(hmcs)): hmcs[i].Scale( scalefactor ); + + xtitle = hmcs[0].GetXaxis().GetTitle(); + ytitle = hmcs[0].GetYaxis().GetTitle(); + hstack2 = ROOT.THStack("hstack2",";"+xtitle+";"+ytitle+";"); + for h in hmcs: hstack2.Add(h); + + maxval = 2.*max(hstack2.GetStack().Last().GetMaximum(),hd.GetMaximum()) + # print maxval; + leg = ROOT.TLegend(0.6,0.7,0.9,0.9); + leg.SetFillStyle(0); + leg.SetBorderSize(0); + leg.SetTextSize(0.035); + leg.AddEntry(hd,"data","pe"); + for i in range(len(hmcs)): + leg.AddEntry(hmcs[i],legname[i],"f") + # print hstack2.GetStack().Last().Integral(), hstack.GetStack().Last().Integral(),hd.Integral() + # print hstack2.GetStack().Last().GetMaximum(),hd.GetMaximum()) + + tag1 = ROOT.TLatex(0.7,0.95,"30 fb^{-1} (13 TeV)") + tag1.SetNDC(); + tag1.SetTextFont(42) + tag1.SetTextSize(0.045); + tag2 = ROOT.TLatex(0.17,0.95,"CMS Preliminary") + tag2.SetNDC(); + tag2.SetTextSize(0.045); + + c = ROOT.TCanvas("c"+name,"c"+name,1000,800); + p2 = ROOT.TPad("pad2","pad2",0,0,1,0.31); + p2.SetTopMargin(0); + p2.SetBottomMargin(0.3); + p2.SetLeftMargin(0.15) + p2.SetRightMargin(0.03) + p2.SetFillStyle(0); + p2.Draw(); + p1 = ROOT.TPad("pad1","pad1",0,0.31,1,1); + p1.SetBottomMargin(0); + p1.SetLeftMargin(p2.GetLeftMargin()) + p1.SetRightMargin(p2.GetRightMargin()) + p1.Draw(); + p1.cd(); + + mainframe = hmcs[0].Clone('mainframe') + mainframe.Reset('ICE') + mainframe.GetXaxis().SetTitleFont(43) + mainframe.GetXaxis().SetLabelFont(43) + mainframe.GetYaxis().SetTitleFont(43) + mainframe.GetYaxis().SetLabelFont(43) + mainframe.GetYaxis().SetTitle('Events') + mainframe.GetYaxis().SetLabelSize(22) + mainframe.GetYaxis().SetTitleSize(26) + mainframe.GetYaxis().SetTitleOffset(2.0) + mainframe.GetXaxis().SetTitle('') + mainframe.GetXaxis().SetLabelSize(0) + mainframe.GetXaxis().SetTitleSize(0) + mainframe.GetXaxis().SetTitleOffset(1.5) + mainframe.GetYaxis().SetNoExponent() + mainframe.Draw() + + if nodata: + hstack.SetMaximum(maxval); + hstack.Draw("hist"); + else: + hstack2.SetMaximum(maxval); + hstack2.Draw("hist"); + hd.Draw("pesames"); + # ROOT.gPad.Update(); + # hstack2.GetXaxis.SetTitle( hmcs[0].GetXaxis().GetTitle() ); + # hstack2.GetYaxis.SetTitle( hmcs[0].GetYaxis().GetTitle() ); + leg.Draw(); + tag1.Draw(); + tag2.Draw(); + + p2.cd() + ratioframe = mainframe.Clone('ratioframe') + ratioframe.Reset('ICE') + ratioframe.GetYaxis().SetRangeUser(0.50,1.50) + ratioframe.GetYaxis().SetTitle('Data/MC') + ratioframe.GetXaxis().SetTitle(hmcs[0].GetXaxis().GetTitle()) + ratioframe.GetXaxis().SetLabelSize(22) + ratioframe.GetXaxis().SetTitleSize(26) + ratioframe.GetYaxis().SetNdivisions(5) + ratioframe.GetYaxis().SetNoExponent() + ratioframe.GetYaxis().SetTitleOffset(mainframe.GetYaxis().GetTitleOffset()) + ratioframe.GetXaxis().SetTitleOffset(3.0) + ratioframe.Draw() + + ## Calculate Ratios + ratios = [] + ratios.append(getRatio(hd, fullmc)) + ratios[0].SetMinimum(0) + ratios[0].SetMaximum(2) + ratioframe.GetYaxis().SetRangeUser(0,2) + + line = ROOT.TLine(ratios[0].GetXaxis().GetXmin(), 1.0, + ratios[0].GetXaxis().GetXmax(), 1.0) + line.SetLineColor(ROOT.kGray) + line.SetLineStyle(2) + line.Draw() + + ratios[0].Draw("P same") + + c.cd() + c.Modified() + c.Update() + c.SaveAs(pdir+"/"+name+".pdf") + c.SaveAs(pdir+"/"+name+".png") + + p1.cd() + ROOT.gPad.SetLogy() + hstack.SetMinimum(0.1) + c.SaveAs(pdir+"/"+name+"_log.pdf") + c.SaveAs(pdir+"/"+name+"_log.png") + + c.Close() + +################################################################################################## +def makeCanvasDataMC_wpred(hd,gpred,hmcs,legname,name,pdir="plots",blind=True): + + print "makeCanvasDataMC_wpred---" + # print "hd integral = ",hd.Integral(); + gpred.SetLineColor(2); + gpred.SetFillColor(2); + gpred.SetFillStyle(3001); + + color = [2,4,6,7,8,3,5] + for h in range(len(hmcs)): + hmcs[h].SetFillStyle(0); + hmcs[h].SetLineColor(4); + hmcs[h].SetFillColor(0) + + hstack = ROOT.THStack("hstack","hstack"); + for h in hmcs: hstack.Add(h); + fullmc = hstack.GetStack().Last(); + + # normalize MC to data + scalefactor = hd.Integral()/fullmc.Integral(); + for i in range(len(hmcs)): hmcs[i].Scale( scalefactor ); + + xtitle = hmcs[0].GetXaxis().GetTitle(); + ytitle = hmcs[0].GetYaxis().GetTitle(); + hstack2 = ROOT.THStack("hstack2",";"+xtitle+";"+ytitle+";"); + for h in hmcs: hstack2.Add(h); + + # print maxval; + leg = ROOT.TLegend(0.6,0.7,0.9,0.9); + leg.SetFillStyle(0); + leg.SetBorderSize(0); + leg.SetTextSize(0.035); + leg.AddEntry(hd,"data","pe"); + leg.AddEntry(gpred,"bkg pred.","f"); + for i in range(len(hmcs)): + leg.AddEntry(hmcs[i],legname[i],"f") + # print hstack2.GetStack().Last().Integral(), hstack.GetStack().Last().Integral(),hd.Integral() + # print hstack2.GetStack().Last().GetMaximum(),hd.GetMaximum()) + + tag1 = ROOT.TLatex(0.7,0.95,"0.46 fb^{-1} (13 TeV)") + tag1.SetNDC(); + tag1.SetTextSize(0.035); + tag2 = ROOT.TLatex(0.17,0.95,"CMS preliminary") + tag2.SetNDC(); + tag2.SetTextSize(0.035); + + gpred.SetMarkerStyle(24); + gpred.SetMarkerColor(2); + + #--------------------------------------------------------------- + c = ROOT.TCanvas("c"+name,"c"+name,1000,800); + + p1 = ROOT.TPad("p1","p1",0.0,0.3,1.0,1.0); + p2 = ROOT.TPad("p2","p2",0.0,0.0,1.0,0.3); + p1.SetBottomMargin(0.05); + p2.SetTopMargin(0.05); + p2.SetBottomMargin(0.3); + + c.cd(); + p1.Draw(); p1.cd(); + + mcall = hstack2.GetStack().Last() + maxval = 2.*max(mcall.GetMaximum(),hd.GetMaximum()); + hd.SetLineColor(1); + mcall.SetLineColor(4); + if not blind: + mcall.SetMaximum(maxval); + mcall.Draw("hist"); + hd.Draw("pesames"); + gpred.Draw("2"); + mcall.Draw("histsames"); + hd.Draw("pesames"); + hd.SetMinimum(0); + if blind: + mcall.SetMaximum(maxval); + mcall.Draw("hist"); + gpred.Draw("2"); + mcall.Draw("histsames"); + mcall.SetMinimum(0); + + mcall.GetXaxis().SetTitle(""); + # ROOT.gPad.Update(); + # hstack2.GetXaxis.SetTitle( hmcs[0].GetXaxis().GetTitle() ); + # hstack2.GetYaxis.SetTitle( hmcs[0].GetYaxis().GetTitle() ); + leg.Draw(); + tag1.Draw(); + tag2.Draw(); + + c.cd(); + p2.Draw(); p2.cd(); + p2.SetGrid(); + + hdOvPred = hd.Clone(); + hpred = gpred.GetHistogram(); + hdOvPred.SetMaximum(2); + hdOvPred.SetMinimum(0); + for i in range(hd.GetNbinsX()): + + # print "bin ", i, ", ", hd.GetBinContent(i+1),hpred.GetBinContent(i+1),gpred.GetY()[i] + if gpred.GetY()[i] > 0: + hdOvPred.SetBinContent( i+1, hd.GetBinContent(i+1)/gpred.GetY()[i] ); + else: + hdOvPred.SetBinContent( i+1, 0. ); + + hdOvPred.GetXaxis().SetTitle("jet mass (GeV)"); + hdOvPred.GetXaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitle("Data/MC"); + hdOvPred.GetYaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitleOffset(0.42); + hdOvPred.Draw('hist'); + + c.SaveAs(pdir+"/"+name+".pdf"); + #--------------------------------------------------------------- + mcall.SetMinimum(0.1); + p1.cd(); + p1.SetLogy(); + c.SaveAs(pdir+"/"+name+"_log.pdf") + +################################################################################################## +def makeCanvasDataMC_MONEY(hd,gpred,hmcs,legname,name,pdir="plots",blind=True): + + print "makeCanvasDataMC_wpred---" + print "hd integral = ",hd.Integral(); + + gpred.SetLineColor(2); + gpred.SetFillColor(2); + gpred.SetFillStyle(3001); + + color = [2,4,6,7,8,3,5] + for h in range(len(hmcs)): + hmcs[h].SetLineWidth(2); + hmcs[h].SetLineColor(color[h]) + + # build total stack + hTotSM = hd.Clone(); + ## for i in range(hd.GetNbinsX()): + ## hTotSM.SetBinContent(i+1, gpred.GetY()[i]+hmcs[0].GetBinContent(i+1)+hmcs[1].GetBinContent(i+1) ); + ## # FinalErrorsVis = 0; + ## # FinalErrorsVis += gpred.GetY()[i]*gpred.GetY()[i]; + ## # hTotSM.SetBinContent(i+1, gpred.GetY()[i]+hmcs[0].GetBinContent(i+1)+hmcs[1].GetBinContent(i+1) ); + hTotSM.SetLineColor(ROOT.kGreen+2); + hTotSM.SetLineWidth(2); + hTotSM.GetYaxis().SetTitle("Events"); + + # print maxval; + leg = ROOT.TLegend(0.6,0.65,0.9,0.9); + leg.SetFillStyle(0); + leg.SetBorderSize(0); + leg.SetTextSize(0.035); + leg.AddEntry(hd,"data","pe"); + leg.AddEntry(hTotSM,"Total SM", "l"); + leg.AddEntry(gpred,"QCD pred.","f"); + for i in range(len(hmcs)): + leg.AddEntry(hmcs[i],legname[i],"l") + + tag1 = ROOT.TLatex(0.7,0.95,"0.46 fb^{-1} (13 TeV)") + tag1.SetNDC(); + tag1.SetTextSize(0.033); + tag1.SetTextFont(52); + txta = ROOT.TLatex(0.2,0.95,"CMS"); + txta.SetNDC(); + txtb = ROOT.TLatex(0.24,0.95,"Simulation Preliminary"); + txtb.SetNDC(); txtb.SetTextFont(52); + txta.SetTextSize(0.033); + txtb.SetTextSize(0.033); + + gpred.SetMarkerStyle(24); + gpred.SetMarkerColor(2); + + #--------------------------------------------------------------- + c = ROOT.TCanvas("c"+name,"c"+name,1000,800); + + p1 = ROOT.TPad("p1","p1",0.0,0.3,1.0,1.0); + p2 = ROOT.TPad("p2","p2",0.0,0.0,1.0,0.3); + p1.SetBottomMargin(0.05); + p2.SetTopMargin(0.05); + p2.SetBottomMargin(0.3); + + c.cd(); + p1.Draw(); p1.cd(); + + hTotSM.SetMaximum( hTotSM.GetMaximum()*1.2 ); + hTotSM.Draw("hist"); + if not blind: hd.Draw("pesames"); + gpred.Draw('2'); + for i in range(len(hmcs)): + hmcs[i].Draw("histsames"); + + leg.Draw(); + tag1.Draw(); + txta.Draw(); + txtb.Draw(); + + c.cd(); + p2.Draw(); p2.cd(); + p2.SetGrid(); + + hdOvPred = hd.Clone(); + hdOvPred.SetMaximum(2); + hdOvPred.SetMinimum(0); + one_x = [] + one_y = [] + one_ex = [] + one_ey = [] + for i in range(hd.GetNbinsX()): + + if hd.GetBinContent(i+1) > 0: + hdOvPred.SetBinContent( i+1, hd.GetBinContent(i+1)/hTotSM.GetBinContent(i+1) ); + errdat = hd.GetBinError(i+1)/hd.GetBinContent(i+1); + errtot = math.sqrt(errdat*errdat) + hdOvPred.SetBinError( i+1, errtot ); + else: + hdOvPred.SetBinContent( i+1, 0. ); + hdOvPred.SetBinError( i+1, 0. ); + + ## one_x.append( hd.GetXaxis().GetBinCenter(i+1) ); + ## one_ex.append( hd.GetXaxis().GetBinWidth(i+1) ); + ## if gpred.GetY()[i] > 0: + ## one_y.append( 1. ); + ## errmc = gpred.GetEY()[i]/gpred.GetY()[i]; + ## one_ey.append( errmc ); + ## else: + ## one_y.append( 0 ); + ## one_ey.append( 0 ); + + hdOvPred.GetXaxis().SetTitle("jet mass (GeV)"); + hdOvPred.GetXaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitle("Data/MC"); + hdOvPred.GetYaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitleOffset(0.42); + hdOvPred.Draw('pe'); + + ## grrat = ROOT.TGraphErrors(len(one_x),array.array('d',one_x),array.array('d',one_y),array.array('d',one_ex),array.array('d',one_ey) ); + ## grrat.SetLineColor(2); + ## grrat.SetFillColor(2); + ## grrat.SetFillStyle(3001); + ## grrat.Draw('2'); + c.SaveAs(pdir+"/"+name+".pdf"); + #--------------------------------------------------------------- + #--------------------------------------------------------------- + c2 = ROOT.TCanvas("c2"+name,"c2"+name,1000,800); + + p12 = ROOT.TPad("p12","p12",0.0,0.3,1.0,1.0); + p22 = ROOT.TPad("p22","p22",0.0,0.0,1.0,0.3); + p12.SetBottomMargin(0.05); + p22.SetTopMargin(0.05); + p22.SetBottomMargin(0.3); + + c2.cd(); + p12.Draw(); p12.cd(); + + hTotSM.SetMaximum( hTotSM.GetMaximum()*2 ); + hTotSM.SetMinimum( 0.001 ); + hd.SetMaximum( hTotSM.GetMaximum()*2 ); + hd.SetMinimum( 0.001 ); + + hd.Draw("histpe"); + hTotSM.Draw("histsames"); + gpred.Draw('2'); + for i in range(len(hmcs)): + hmcs[i].Draw("histsames"); + + leg.Draw(); + tag1.Draw(); + txta.Draw(); + txtb.Draw(); + p12.SetLogy(); + + c2.cd(); + p22.Draw(); p22.cd(); + p22.SetGrid(); + + hdOvPred = hd.Clone(); + hdOvPred.SetMaximum(2); + hdOvPred.SetMinimum(0); + one_x = [] + one_y = [] + one_ex = [] + one_ey = [] + for i in range(hd.GetNbinsX()): + + if hd.GetBinContent(i+1) > 0: + hdOvPred.SetBinContent( i+1, hd.GetBinContent(i+1)/hTotSM.GetBinContent(i+1) ); + errdat = hd.GetBinError(i+1)/hd.GetBinContent(i+1); + errtot = math.sqrt(errdat*errdat) + hdOvPred.SetBinError( i+1, errtot ); + else: + hdOvPred.SetBinContent( i+1, 0. ); + hdOvPred.SetBinError( i+1, 0. ); + + ## one_x.append( hd.GetXaxis().GetBinCenter(i+1) ); + ## one_ex.append( hd.GetXaxis().GetBinWidth(i+1) ); + ## if gpred.GetY()[i] > 0: + ## one_y.append( 1. ); + ## errmc = gpred.GetEY()[i]/gpred.GetY()[i]; + ## one_ey.append( errmc ); + ## else: + ## one_y.append( 0 ); + ## one_ey.append( 0 ); + + hdOvPred.GetXaxis().SetTitle("jet mass (GeV)"); + hdOvPred.GetXaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitle("Data/MC"); + hdOvPred.GetYaxis().SetTitleSize(0.14); + hdOvPred.GetYaxis().SetTitleOffset(0.42); + hdOvPred.Draw('pe'); + + + ## grrat = ROOT.TGraphErrors(len(one_x),array.array('d',one_x),array.array('d',one_y),array.array('d',one_ex),array.array('d',one_ey) ); + ## grrat.SetLineColor(2); + ## grrat.SetFillColor(2); + ## grrat.SetFillStyle(3001); + ## grrat.Draw('2'); + c2.SaveAs(pdir+"/"+name+"_log.pdf"); + +################################################################################################## +def makeCanvasShapeComparison(hs,legname,name,pdir="plots"): + + color = [2,4,6,7,8,3,5,2,4,6,7,8,3,5,2,4,6,7,8,3,5] + style = [1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3] + + leg = ROOT.TLegend(0.6,0.5,0.9,0.9); + leg.SetFillStyle(0); + leg.SetBorderSize(0); + leg.SetTextSize(0.035); + + maxval = -99; + for h in range(len(hs)): + hs[h].SetLineColor(color[h]); + hs[h].SetLineStyle(style[h]); + hs[h].SetLineWidth(2); + hs[h].SetFillStyle(0); + if hs[h].Integral() > 0: hs[h].Scale(1./hs[h].Integral()); + if hs[h].GetMaximum() > maxval: maxval = hs[h].GetMaximum(); + leg.AddEntry(hs[h],legname[h],"l"); + + tag2 = ROOT.TLatex(0.2,0.90,"CMS preliminary") + tag2.SetNDC(); + tag2.SetTextSize(0.032); + + c = ROOT.TCanvas("c"+name,"c"+name,1000,800); + hs[0].SetMaximum(2.*maxval); + hs[0].Draw("hist"); + for h in range(1,len(hs)): hs[h].Draw("histsames"); + leg.Draw(); + c.SaveAs(pdir+"/"+name+".pdf"); + ROOT.gPad.SetLogy(); + hs[0].SetMinimum(1e-3); + tag2.Draw(); + c.SaveAs(pdir+"/"+name+"_log.pdf") + +def makeCanvasComparison(hs,legname,color,style,name,pdir="plots",lumi=30,ofile=None,unitnorm=False): + #color = [ROOT.kBlue,ROOT.kGreen+1,ROOT.kCyan,ROOT.kViolet,ROOT.kBlack,ROOT.kRed,5,2,4,6,7,8,3,5,2,4,6,7,8,3,5] + #style = [1,2,5,6,7,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3] + #leg = ROOT.TLegend(0.65,0.65,0.9,0.9) + leg = ROOT.TLegend(0.65,0.62,0.9,0.87) + leg.SetFillStyle(0) + leg.SetBorderSize(0) + leg.SetTextSize(0.027) + leg.SetTextFont(42) + + maxval = -99 + for iname, h in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): + h.SetLineColor(color[iname]) + h.SetLineStyle(style[iname]) + h.SetLineWidth(2) + h.SetFillStyle(0) + h.GetXaxis().SetLabelSize(0.03) + h.GetXaxis().SetTitleOffset(1.1) + h.GetXaxis().SetTitleSize(0.033) + h.GetYaxis().SetLabelSize(0.03) + h.GetYaxis().SetTitleOffset(1.2) + h.GetYaxis().SetTitleSize(0.033) + + + if h.GetMaximum() > maxval: maxval = h.GetMaximum() + leg.AddEntry(h,legname[iname],"l") + + + print "======== signal contribution ==========" + for iname, h in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): + print iname+": here %.4f "%(h.Integral()) + + + c = ROOT.TCanvas("c"+name,"c"+name,900,800) + i=0 + for process, s in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): + i+=1 + if i==1: + s.SetMaximum(10.*maxval) + #s.SetMinimum(0.01) + s.SetMinimum(0.05) + if unitnorm : + s.SetMaximum(100.) + s.DrawNormalized("hist") + else: s.Draw("hist") + else : + if unitnorm : s.DrawNormalized("histsame") + else : s.Draw("histsame") + leg.Draw() + #hs[0].GetXaxis().SetRangeUser(0,400) + #hs[0].SetMinimum(1e-1); i + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = ROOT.TLatex(0.18,0.83,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.18,0.79,"Simulation Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag4 = ROOT.TLatex(0.18,0.75,"Preliminary") + tag4.SetNDC(); tag4.SetTextFont(52) + + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); tag4.SetTextSize(0.033); tag1.Draw(); tag2.Draw(); tag3.Draw(); #tag4.Draw() + + + ptRange = [450, 1000] + if 'msd_ak8_topR6_N2_pass' in name: + passTag = 'double-b tag > 0.9' + elif 'msd_ak8_topR6_N2_fail' in name: + passTag = 'double-b tag < 0.9' + if 'msd_ak8_topR6_N2_pass' in name or 'msd_ak8_topR6_N2_fail' in name: + tag5 = ROOT.TLatex(0.31, 0.83, "#splitline{%i < p_{T} < %i GeV}{%s}"%(ptRange[0],ptRange[1],passTag)) + tag5.SetNDC() + tag5.SetTextFont(42) + tag5.SetTextSize(0.025) + tag5.Draw() + + c.SaveAs(pdir+"/"+name+".pdf") + c.SaveAs(pdir+"/"+name+".C") + ROOT.gPad.SetLogy() + + c.SaveAs(pdir+"/"+name+"_log.pdf") + c.SaveAs(pdir+"/"+name+"_log.C") + if ofile is not None: + ofile.cd() + c.Write('c'+name) + + + return c + + +def makeCanvasComparisonStack(hs,hb,legname,color,style,nameS,outname,pdir="plots",lumi=30,printSB=True,ofile=None): + leg_y = 0.88 - (1+len(hb))*0.03 + leg = ROOT.TLegend(0.65,leg_y,0.88,0.88) + leg.SetFillStyle(0) + leg.SetBorderSize(0) + leg.SetTextSize(0.035) + leg.SetTextFont(42) + + maxval = -99 + nevt=[] + hstack = ROOT.THStack("hstack","hstack") + #for name, h in (sorted(hb.iteritems(),key=customSort)): + # print name + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + hstack.Add(h) + h.SetFillColor(color[name]) + h.SetLineColor(1) + h.SetLineStyle(1) + h.SetLineWidth(1) + h.SetFillStyle(1001) + nevt.append(h.Integral()) + if h.GetMaximum() > maxval: maxval = h.GetMaximum() + + allMC=hstack.GetStack().Last().Clone() + ntotal=allMC.Integral() + nsig=hs[nameS].Integral() + + if(printSB): + ratio = hs[nameS].Clone("%s_ratio"%hs[nameS].GetName()) + ratio.SetDirectory(0) + for i in range(0, allMC.GetNbinsX()): + SoverB=0 + SoverB= getSoverRootB(hs[nameS],allMC,i) + ratio.SetBinContent(i,SoverB) + + + for name, h in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): + if 'WH' in name : + h.SetLineColor(color[name]) + h.SetLineStyle(style[name]) + h.SetLineWidth(2) + h.SetFillStyle(0) + #h.Scale(100) + + + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + leg.AddEntry(h,legname[name],"f") + for name, h in sorted(hs.iteritems(),key=lambda (k,v): -v.Integral()): + if 'WH' in name: leg.AddEntry(h,legname[name],"l") + + + c = ROOT.TCanvas("c"+outname,"c"+outname,1000,800) + c.SetFillStyle(4000) + c.SetFrameFillStyle(1000) + c.SetFrameFillColor(0) + + if(printSB): + oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0) + oben.SetBottomMargin(0) + oben.SetFillStyle(4000) + oben.SetFrameFillStyle(1000) + oben.SetFrameFillColor(0) + unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3) + unten.SetTopMargin(0.) + unten.SetBottomMargin(0.35) + unten.SetFillStyle(4000) + unten.SetFrameFillStyle(1000) + unten.SetFrameFillColor(0) + + oben.Draw() + unten.Draw() + oben.cd() + else : + c.cd() + + hstack.Draw('hist') + hstack.SetMaximum(1.5*maxval) + hstack.GetYaxis().SetTitle('Events') + hstack.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) + hstack.Draw('hist') + for name, h in hs.iteritems(): + if 'WH' in name: + h.Draw("histsame") + leg.Draw() + + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = ROOT.TLatex(0.17,0.92,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.27,0.92,"Simulation Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); tag1.Draw(); tag2.Draw(); tag3.Draw() + + if(printSB): + unten.cd() + unten.SetLogy() + ratio.SetStats(0) + ratio.SetLineColor(hs[nameS].GetLineColor()) + ratio.SetLineWidth(2) + ratio.SetLineStyle(1) + ratio.GetYaxis().SetRangeUser(0.001,2) + ratio.GetYaxis().SetTitle("S/#sqrt{B}") + ratio.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) + ratio.GetXaxis().SetTitleSize(0.14) + ratio.GetXaxis().SetTitleOffset(1.0) + ratio.GetYaxis().SetTitleOffset(0.5) + ratio.GetYaxis().SetLabelSize(0.12) + ratio.GetYaxis().SetTitleSize(0.14) + ratio.GetXaxis().SetLabelSize(0.12) + + line = ROOT.TLine(ratio.GetXaxis().GetXmin(), 1.0, + ratio.GetXaxis().GetXmax(), 1.0) + line.SetLineColor(ROOT.kGray) + line.SetLineStyle(2) + line.Draw() + + ratio.Draw("HIST") + line.Draw("same") + + + c.SaveAs(pdir+"/"+outname+".pdf") + c.SaveAs(pdir+"/"+outname+".C") + + + #ROOT.gPad.SetLogy() + if(printSB): + oben.SetLogy() + else: + c.SetLogy() + hstack.SetMinimum(1e-1) + + c.SaveAs(pdir+"/"+outname+"_log.pdf") + c.SaveAs(pdir+"/"+outname+"_log.C") + + + allMC=hstack.GetStack().Last().Clone() + ntotal=allMC.Integral() + i=0 + print "========== Background composition ===========" + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + if ntotal>0: + print name+": %.2f frac : %.3f"%(h.Integral(),nevt[i]/ntotal*100.) + i+=1 + print "H: %.2f : %.3f "%(nsig,nsig/ntotal*100.) + + + if ofile is not None: + ofile.cd() + c.Write('c'+outname) + + return c + + +def makeCanvasComparisonStackWData(hd,hs,hb,legname,color,style,outname,pdir="plots",lumi=30,ofile=None,normalize=True,ratio=True): + ttbarInt = 0 + ttbarErr = 0 + ttbarErr2 = 0 + otherInt = 0 + otherErr = 0 + otherErr2 = 0 + print "========== Background composition ===========" + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + error = array.array('d',[0.0]) + integral = h.IntegralAndError(1,h.GetNbinsX(),error) + print name, integral, '+/-', error[0] + if 'TTbar' in name: + ttbarInt += integral + ttbarErr2 += error[0]*error[0] + else: + otherInt += integral + otherErr2 += error[0]*error[0] + + ttbarErr = sqrt(ttbarErr2) + otherErr = sqrt(otherErr2) + error = array.array('d',[0.0]) + integral = hd.IntegralAndError(1,hd.GetNbinsX(),error) + print 'data', integral, '+/-', error[0] + dataInt = integral + dataErr = error[0] + + kTTbar = 1 + kTTbarErr = 1 + if ttbarInt>0 and dataInt-otherInt>0: + kTTbar = (dataInt-otherInt)/ttbarInt + kTTbarErr = kTTbar*sqrt(pow(sqrt(dataErr*dataErr + otherErr*otherErr)/(dataInt-otherInt),2.) + pow(ttbarErr/ttbarInt,2.)) + + print 'kTTbar', kTTbar, '+/-', kTTbarErr + + print 'data TTBar', dataInt-otherInt,'+/-', sqrt(dataErr*dataErr + otherErr*otherErr) + print 'mc TTBar', ttbarInt, '+/-', ttbarErr + + + maxval = -99 + + hstack = ROOT.THStack("hstack","hstack") + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + #if 'TTbar' in name: + # print 'scaling %s by k = %f'%(name, kTTbar) + # h.Scale(kTTbar) + hstack.Add(h) + h.SetFillColor(color[name]) + h.SetLineColor(1) + h.SetLineStyle(1) + h.SetLineWidth(1) + h.SetFillStyle(1001) + + if h.GetMaximum() > maxval: maxval = h.GetMaximum() + allMC=hstack.GetStack().Last().Clone() + maxval = max(hd.GetMaximum(),maxval) + + fullmc = hstack.GetStack().Last(); + + # normalize MC to data + scalefactor = hd.Integral()/fullmc.Integral(); + print "data/mc scale factor = ", scalefactor + if normalize: + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + if 'QCD' in name: + h.Scale( scalefactor ); + hstack2 = ROOT.THStack("hstack2","hstack2"); + for name, h in sorted(hb.iteritems(),key=lambda (k,v): v.Integral()): + hstack2.Add(h); + h.SetFillColor(color[name]) + h.SetLineColor(1) + h.SetLineStyle(1) + h.SetLineWidth(1) + h.SetFillStyle(1001) + + + + for name, h in sorted(hs.iteritems(),key=lambda (k,v): v.Integral()): + if 'WH' in name or 'ttH' in name or 'VBF' in name: + h.SetLineColor(color[name]) + h.SetLineStyle(style[name]) + h.SetLineWidth(2) + h.SetFillStyle(0) + + + leg_y = 0.88 - (2+int(len(hb)/3))*0.03 + leg_y2 = 0.88 - (4+int(len(hb)/3))*0.03 + leg = ROOT.TLegend(0.2,leg_y,0.5,0.88)#,"data/mc scale factor %.2f"%(scalefactor),"NDC") + leg.SetFillStyle(0) + leg.SetBorderSize(0) + leg.SetTextSize(0.035) + leg.SetTextFont(42) + leg2 = ROOT.TLegend(0.5,leg_y,0.78,0.88,) + leg2.SetFillStyle(0) + leg2.SetBorderSize(0) + leg2.SetTextSize(0.035) + leg2.SetTextFont(42) + leg3 = ROOT.TLegend(0.65,leg_y2,0.98,0.88,) + leg3.SetFillStyle(0) + leg3.SetBorderSize(0) + leg3.SetTextSize(0.035) + leg3.SetTextFont(42) + + + count=1 + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + if count <4: + if name in 'QCD': leg.AddEntry(h,legname[name]+" (k-factor %.2f)"%scalefactor,"f") + else : leg.AddEntry(h,legname[name],"f") + elif count >3 and count<7 : leg2.AddEntry(h,legname[name],"f") + elif count >6 : leg3.AddEntry(h,legname[name],"f") + count = count+1 + for name, h in sorted(hs.iteritems(),key=lambda (k,v): -v.Integral()): + if 'WH' in name or 'ttH' in name or 'VBF' in name: + leg3.AddEntry(h,legname[name],"l") + leg3.AddEntry(hd,'Data',"pe"); + c = ROOT.TCanvas("c"+outname,"c"+outname,1000,800) + c.SetFillStyle(4000) + c.SetFrameFillStyle(1000) + c.SetFrameFillColor(0) + if ratio: + oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0) + unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3) + oben.SetBottomMargin(0) + unten.SetTopMargin(0.) + unten.SetBottomMargin(0.35) + + else: + oben = ROOT.TPad('oben','oben',0,0.03 ,1.0,1.0) + unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.0) + oben.SetFillStyle(4000) + oben.SetFrameFillStyle(1000) + oben.SetFrameFillColor(0) + unten.SetFillStyle(4000) + unten.SetFrameFillStyle(1000) + unten.SetFrameFillColor(0) + oben.Draw() + unten.Draw() + oben.cd() + + hstack2.Draw('hist') + hstack2.SetMaximum(10*maxval) + hstack2.SetMinimum(1.) + hstack2.GetYaxis().SetRangeUser(1.,10*maxval) + hstack2.GetYaxis().SetTitle('Events') + hstack2.GetYaxis().SetTitleOffset(1.0) + hstack2.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) + hstack2.GetXaxis().SetTitleOffset(1.3) + hstack2.GetXaxis().SetLabelSize(0.04) + hstack2.GetXaxis().SetTitleSize(0.045) + hstack2.Draw('hist') + for name, h in hs.iteritems(): + if 'WH' in name or 'ttH' in name or 'VBF' in name: + h.Draw("histsame") + leg.Draw() + leg2.Draw() + leg3.Draw() + hstack2.SetMinimum(1) + allMC2=hstack2.GetStack().Last().Clone() + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + if name in 'QCD' : + herr = h.Clone('herr') + herr2 = h.Clone('herr2') + # for ibin in range(1,h.GetNbinsX()+1): print(ibin,herr.GetBinError(ibin),herr.GetBinContent(ibin)) + + for name, h in sorted(hb.iteritems(),key=lambda (k,v): -v.Integral()): + #for ibin in range(1,h.GetNbinsX()+1): print(ibin,herr.GetBinError(ibin),herr.GetBinContent(ibin)) + if name in 'QCD' : continue + for ibin in range(1,h.GetNbinsX()+1): + valA = herr.GetBinContent(ibin); + evalA = herr.GetBinError(ibin); + valB = h.GetBinContent(ibin); + evalB = h.GetBinError(ibin); + + herr.SetBinContent(ibin,(valA+valB)); + herr.SetBinError(ibin,sqrt(evalA*evalA+evalB*evalB)); + if(valA+valB >0): herr2.SetBinContent(ibin,(valA+valB+sqrt(evalA*evalA+evalB*evalB))/(valA+valB)); + else : herr2.SetBinContent(ibin,1); + #herr2.SetBinError(ibin,sqrt(evalA*evalA+evalB*evalB)); + + + theErrorGraph = ROOT.TGraphErrors(herr) + theErrorGraph.SetFillColor(ROOT.kGray+2) + theErrorGraph.SetFillStyle(3002) + herr.SetFillColor(ROOT.kGray+2) + herr.SetFillStyle(3002) + herr.SetMarkerColor(1111); + leg3.AddEntry(herr,"MC uncert. (stat.)","fl") + + hd.Draw('pesames'); + theErrorGraph.Draw('SAME2') + #herr.Draw('ERROR SAME2') + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.17,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.27,0.92,"Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + if ratio: + unten.cd() + ratio = getRatio(hd,allMC2) + herr3= TOTerror(allMC2,ratio); + toterree = ROOT.TGraphErrors(herr3) + ksScore = hd.KolmogorovTest( allMC2 ) + chiScore = hd.Chi2Test( allMC2 , "UWCHI2/NDF") + print ksScore + print chiScore + ratio.SetStats(0) + ratio.GetYaxis().SetRangeUser(0,5) + ratio.GetYaxis().SetNdivisions(504) + ratio.GetYaxis().SetTitle("Data/Simulation") + ratio.GetXaxis().SetTitle(allMC.GetXaxis().GetTitle()) + ratio.GetXaxis().SetTitleSize(0.14) + ratio.GetXaxis().SetTitleOffset(1.0) + ratio.GetYaxis().SetTitleOffset(0.5) + ratio.GetYaxis().SetLabelSize(0.12) + ratio.GetYaxis().SetTitleSize(0.11) + ratio.GetXaxis().SetLabelSize(0.11) + + line = ROOT.TLine(ratio.GetXaxis().GetXmin(), 1.0, + ratio.GetXaxis().GetXmax(), 1.0) + line.SetLineColor(ROOT.kGray) + line.SetLineStyle(2) + line.Draw() + tKsChi = ROOT.TLatex() + tKsChi.SetNDC() + tKsChi.SetTextFont(42) + tKsChi.SetTextSize(0.09) + + #ratioError = ROOT.TGraphErrors(error) + #ratioError.SetFillColor(ROOT.kGray+3) + #ratioError.SetFillStyle(3013) + ratio.Draw("P E ") + ''' + herr2.SetFillColor(ROOT.kGray+2); + herr2.SetLineColor(ROOT.kGray+2); + herr2.SetFillStyle(3002); + herr2.Draw("hist same"); + ''' + toterree.SetFillColor(ROOT.kGray+2); + toterree.SetLineColor(ROOT.kGray+2); + toterree.SetFillStyle(3002); + toterree.Draw("2 same"); + #toterree.Draw("p"); + line.Draw("same") + #tKsChi.DrawLatex(0.7,0.895,"#chi^{2}_{ }#lower[0.1]{/^{}#it{NDF} = %.2f}"%(chiScore)) + leg4 = ROOT.TLegend(0.7,0.89,0.5,0.8)#,"data/mc scale factor %.2f"%(scalefactor),"NDC") + leg4.SetFillStyle(0) + leg4.SetBorderSize(0) + leg4.SetTextSize(0.05) + leg4.SetTextFont(42) + leg4.AddEntry(toterree,"MC uncert. (stat.)","fl") + leg4.Draw() + + c.SaveAs(pdir+"/"+outname+".pdf") + c.SaveAs(pdir+"/"+outname+".root") + oben.SetLogy() + + + c.SaveAs(pdir+"/"+outname+"_log.pdf") + c.SaveAs(pdir+"/"+outname+"_log.root") + + if ofile is not None: + ofile.cd() + c.Write('c'+outname) + + + return c + +def makeCanvasRatio(h_denom,h_numer,legname,color,style,outname,pdir="plots",lumi=30,ofile=None,pt=None,f2params=None): + leg_y = 0.88 - (6)*0.04 + leg = ROOT.TLegend(0.5,leg_y,0.88,0.88) + leg.SetFillStyle(0) + leg.SetBorderSize(0) + leg.SetTextSize(0.035) + leg.SetTextFont(42) + + maxval = -99 + + #h_denom.Scale(1./h_denom.Integral()) + #h_numer.Scale(1./h_numer.Integral()) + leg.AddEntry(h_denom,legname[0],'l') + leg.AddEntry(h_numer,legname[1],'pe') + + c = ROOT.TCanvas("c"+outname,"c"+outname,1000,800) + + c.SetFillStyle(4000) + c.SetFrameFillStyle(1000) + c.SetFrameFillColor(0) + + oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0) + oben.SetBottomMargin(0) + oben.SetFillStyle(4000) + oben.SetFrameFillStyle(1000) + oben.SetFrameFillColor(0) + unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3) + unten.SetTopMargin(0.) + unten.SetBottomMargin(0.35) + unten.SetFillStyle(4000) + unten.SetFrameFillStyle(1000) + unten.SetFrameFillColor(0) + + oben.Draw() + unten.Draw() + oben.cd() + + h_denom.GetYaxis().SetTitle('Probability') + h_denom.GetYaxis().SetTitleOffset(1.0) + h_denom.SetMaximum(1.2*max(h_denom.GetMaximum(),h_numer.GetMaximum())) + h_denom.SetMinimum(0.) + h_denom.SetLineColor(color[0]) + h_numer.SetLineColor(color[1]) + h_denom.Draw('hist') + h_numer.Draw('pezsame') + + if pt is not None and f2params is not None: + f1params = array.array('d',list(f2params)) + f1params.append(pt) + npar = len(f2params) + f2 = ROOT.TF2("f2",fun2,h_denom.GetXaxis().GetXmin(),h_denom.GetXaxis().GetXmax(),h_denom.GetYaxis().GetXmin(),h_denom.GetYaxis().GetXmax(),npar) + f2.SetParameters(f2params) + f1 = ROOT.TF1("f1",fun1,h_denom.GetXaxis().GetXmin(),h_denom.GetXaxis().GetXmax(),npar+1) + f1.SetParameters(f1params) + + h_pred = h_denom.Clone('h_pred') + for i in range(1,h_pred.GetXaxis().GetNbins()+1): + h_pred.SetBinContent(i,f2.Eval(h_pred.GetBinCenter(i),pt)*h_pred.GetBinContent(i)) + + h_pred.SetLineColor(ROOT.kRed) + h_pred.Draw('histsame') + leg.AddEntry(h_pred,'QCD fail #times polynomial','l') + + leg.Draw() + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + unten.cd() + ratio= getRatio(h_numer,h_denom) + ksScore = h_numer.KolmogorovTest( h_denom ) + chiScore = h_numer.Chi2Test( h_denom , "WWCHI2/NDF") + print ksScore + print chiScore + ratio.SetStats(0) + ratio.GetYaxis().SetRangeUser(0.3,1.7) + ratio.GetYaxis().SetNdivisions(504) + ratio.GetYaxis().SetTitle("Ratio") + ratio.GetXaxis().SetTitle(h_denom.GetXaxis().GetTitle()) + ratio.GetXaxis().SetTitleSize(0.14) + ratio.GetXaxis().SetTitleOffset(1.0) + ratio.GetYaxis().SetTitleOffset(0.5) + ratio.GetYaxis().SetLabelSize(0.12) + ratio.GetYaxis().SetTitleSize(0.14) + ratio.GetXaxis().SetLabelSize(0.12) + + + line = ROOT.TLine(ratio.GetXaxis().GetXmin(), 1.0, + ratio.GetXaxis().GetXmax(), 1.0) + line.SetLineColor(ROOT.kGray) + line.SetLineStyle(2) + line.Draw() + tKsChi = ROOT.TLatex() + tKsChi.SetNDC() + tKsChi.SetTextFont(42) + tKsChi.SetTextSize(0.09) + + #ratioError = ROOT.TGraphErrors(error) + #ratioError.SetFillColor(ROOT.kGray+3) + #ratioError.SetFillStyle(3013) + ratio.Draw("pez") + line.Draw("same") + + if pt is not None: + f1.SetLineColor(ROOT.kRed) + f1.Draw("csame") + + tKsChi.DrawLatex(0.7,0.895,"#chi^{2}_{ }#lower[0.1]{/^{}#it{NDF} = %.2f}"%(chiScore)) + + c.SaveAs(pdir+"/"+outname+".pdf") + c.SaveAs(pdir+"/"+outname+".C") + + h_denom.SetMinimum(0.0005) + h_denom.SetMaximum(1) + oben.SetLogy() + + + c.SaveAs(pdir+"/"+outname+"_log.pdf") + c.SaveAs(pdir+"/"+outname+"_log.C") + + if ofile is not None: + ofile.cd() + c.Write('c'+outname) + + return c + +def fun2(x, par): + rho = ROOT.TMath.Log((x[0]*x[0])/(x[1]*x[1])) + poly0 = par[0]*(1.0 + par[1]*rho + par[2]*rho*rho) + poly1 = par[0]*(par[3] + par[4]*rho + par[5]*rho*rho)*x[1] + poly2 = par[0]*(par[6] + par[7]*rho + par[8]*rho*rho)*x[1]*x[1] + return poly0+poly1+poly2 + +def fun2rho(x, par): + rho = x[0] + poly0 = par[0]*(1.0 + par[1]*rho + par[2]*rho*rho) + poly1 = par[0]*(par[3] + par[4]*rho + par[5]*rho*rho)*x[1] + poly2 = par[0]*(par[6] + par[7]*rho + par[8]*rho*rho)*x[1]*x[1] + return poly0+poly1+poly2 + +def fun1(x, par): + rho = ROOT.TMath.Log((x[0]*x[0])/(par[9]*par[9])) + poly0 = par[0]*(1.0 + par[1]*rho + par[2]*rho*rho) + poly1 = par[0]*(par[3] + par[4]*rho + par[5]*rho*rho)*par[9] + poly2 = par[0]*(par[6] + par[7]*rho + par[8]*rho*rho)*par[9]*par[9] + return poly0+poly1+poly2 + +def makeCanvasRatio2D(h_denom,h_numer,legname,color,style,outname,pdir="plots",lumi=30,ofile=None): + leg_y = 0.88 - (6)*0.04 + leg = ROOT.TLegend(0.5,leg_y,0.88,0.88) + leg.SetFillStyle(0) + leg.SetBorderSize(0) + leg.SetTextSize(0.035) + leg.SetTextFont(42) + + maxval = -99 + + #h_denom.Scale(1./h_denom.Integral()) + #h_numer.Scale(1./h_numer.Integral()) + ratio = h_numer.Clone('ratio') + ratio.Divide(h_denom) + ratio.GetXaxis().SetTitleOffset(1.5) + ratio.GetYaxis().SetTitleOffset(1.5) + ratio.GetZaxis().SetTitle('Ratio') + ratio.GetXaxis().SetNdivisions(504) + ratio.GetYaxis().SetNdivisions(508) + ratio.GetZaxis().SetNdivisions(504) + for i in range(ratio.GetNbinsX()): + for j in range(ratio.GetNbinsY()): + if ratio.GetBinContent(i+1,j+1)==0: + ratio.SetBinContent(i+1,j+1,0) + c = ROOT.TCanvas("c"+outname,"c"+outname,1000,800) + + c.SetFillStyle(4000) + c.SetFrameFillStyle(1000) + c.SetFrameFillColor(0) + + ratio.SetLineColor(ROOT.kBlue+1) + + + f2params = array.array('d',[1,0,0,0,0,0,0,0,0]) + npar = len(f2params) + f2 = ROOT.TF2("f2",fun2,ratio.GetXaxis().GetXmin(),ratio.GetXaxis().GetXmax(),ratio.GetYaxis().GetXmin(),ratio.GetYaxis().GetXmax(),npar) + f2.SetParameters(f2params) + #f2.FixParameter(2,0) + #f2.FixParameter(5,0) + #f2.FixParameter(8,0) + f2.FixParameter(6,0) + f2.FixParameter(7,0) + f2.FixParameter(8,0) + fr = ratio.Fit('f2','RNS') + #f2.Draw("surf") + ratio.Draw('surf1') + + + f2graph = ROOT.TGraph2D() + N = -1 + for i in range(101): + for j in range(101): + N+=1 + x = ratio.GetXaxis().GetXmin() + i*(ratio.GetXaxis().GetXmax()-ratio.GetXaxis().GetXmin())/100 + y = ratio.GetYaxis().GetXmin() + j*(ratio.GetYaxis().GetXmax()-ratio.GetYaxis().GetXmin())/100 + z = f2.Eval(x,y) + if math.log(x*x/(y*y)) < -6 or math.log(x*x/(y*y)) > -2.1: + z = 0 + #print x, y, z + f2graph.SetPoint(N,x,y,z) + f2.Draw("surf fb bb same") + #f2graph.SetLineColor(ROOT.kRed) + #f2graph.Draw("surf fb bb same") + + #raw_input("Press Enter to continue...") + print 'chi2 = ', fr.Chi2() + + #ratio.GetZaxis().SetRangeUser(0.3,1.7) + #ratio.SetMinimum(0.3) + #ratio.SetMaximum(1.7) + + ROOT.gPad.SetTheta(30) + ROOT.gPad.SetPhi(30+270) + ROOT.gPad.Modified() + ROOT.gPad.Update() + #h1 = c.DrawFrame(40,500,200,1000) + #ratio.Draw('surf1') + #f2.Draw("surf same bb") + + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.25,0.92,"Simulation Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + c.SaveAs(pdir+"/"+outname+".pdf") + c.SaveAs(pdir+"/"+outname+".C") + #for i in range(0,360): + # ROOT.gPad.SetPhi(30+270+i) + # ROOT.gPad.Modified() + # ROOT.gPad.Update() + # c.SaveAs(pdir+"/"+outname+"_%03d.png"%i) + + ROOT.gPad.SetLogz() + + ratio.SetMinimum(1e-2) + ratio.SetMaximum(10) + f2.GetParameters(f2params) + print f2params + + c.SaveAs(pdir+"/"+outname+"_log.pdf") + c.SaveAs(pdir+"/"+outname+"_log.C") + + if ofile is not None: + ofile.cd() + c.Write('c'+outname) + + + #c.Clear() + c.SetLogz(0) + + ratiorho = ROOT.TH2D('ratiorho','ratiorho',100,-6,-2.1,100,ratio.GetYaxis().GetXmin(),ratio.GetYaxis().GetXmax()) + ratiorho.GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + ratiorho.GetXaxis().SetTitle('#rho') + ratiorho.GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + ratiorhograph = ROOT.TGraph2D() + N = -1 + for i in range(1,ratio.GetNbinsX()+1): + for j in range(1,ratio.GetNbinsY()+1): + N+=1 + m = ratio.GetXaxis().GetBinCenter(i) + y = ratio.GetYaxis().GetBinCenter(j) + x = math.log(m*m/(y*y)) + z = ratio.GetBinContent(i,j) + #print N, x, y, z + ratiorhograph.SetPoint(N,x,y,z) + f2rho = ROOT.TF2("f2",fun2rho,-6,-2.1,ratio.GetYaxis().GetXmin(),ratio.GetYaxis().GetXmax(),npar) + f2rho.SetParameters(f2params) + f2rhograph = ROOT.TGraph2D() + N = -1 + for i in range(101): + for j in range(101): + N+=1 + x = -6 + i*(-2.1+6)/100 + y = ratio.GetYaxis().GetXmin() + j*(ratio.GetYaxis().GetXmax()-ratio.GetYaxis().GetXmin())/100 + z = f2rho.Eval(x,y) + m = math.sqrt(math.exp(x))*y + if m < 40 or m > 201: + z = 0 + #print x, y, z + f2rhograph.SetPoint(N,x,y,z) + #ratiorho.Draw('surf1') + ratiorhograph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + ratiorhograph.GetHistogram().GetXaxis().SetTitle('#rho') + ratiorhograph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + ratiorhograph.GetHistogram().GetYaxis().SetNdivisions(505) + ratiorhograph.GetHistogram().GetXaxis().SetNdivisions(505) + ratiorhograph.GetHistogram().GetXaxis().SetTitleOffset(1.5) + ratiorhograph.GetHistogram().GetYaxis().SetTitleOffset(1.5) + ratiorhograph.Draw("surf1") + f2rho.Draw("surf fb bb same") + #f2rhograph.SetLineColor(ROOT.kRed) + #f2rhograph.Draw("surf fb bb same") + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.25,0.92,"Simulation Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + c.SaveAs(pdir+"/"+outname.replace('msd','rho')+".pdf") + c.SaveAs(pdir+"/"+outname.replace('msd','rho')+".C") + + #f2rho.Draw("colz") + c.SetRightMargin(0.20) + f2graph.Draw("colz") + f2graph.GetHistogram().GetXaxis().SetTitle(ratio.GetXaxis().GetTitle()) + f2graph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + f2graph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.25,0.92,"Simulation Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + c.SaveAs(pdir+"/"+outname.replace('msd','msdcolz')+".pdf") + c.SaveAs(pdir+"/"+outname.replace('msd','msdcolz')+".C") + + f2rhograph.Draw("colz") + f2rhograph.GetHistogram().GetXaxis().SetTitle('#rho') + f2rhograph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + f2rhograph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + tag1 = ROOT.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = ROOT.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = ROOT.TLatex(0.25,0.92,"Simulation Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + c.SaveAs(pdir+"/"+outname.replace('msd','rhocolz')+".pdf") + c.SaveAs(pdir+"/"+outname.replace('msd','rhocolz')+".C") + + + #raw_input("Press Enter to continue...") + + return c, f2params + +def makeCanvas2D( TFMap, name, pdir='plots' ): + + c1 = ROOT.TCanvas("c1","c1",1000,800) + TFMap.Draw("colz"); + c1.SetRightMargin(0.15); + c1.SaveAs(pdir+"/"+name+".pdf"); + + # hxs = []; + hys = []; + + # for i in range(TFMap.GetNbinsX()): + # xnam = TFMap.GetYaxis().GetTitle(); + # nbin = TFMap.GetNbinsY(); + # ylo = TFMap.GetYaxis().GetBinLowEdge(1); + # yhi = TFMap.GetYaxis().GetBinUpEdge(nbin); + # hxs.append( ROOT.TH1F("hxs"+str(i),";"+xnam+";",nbin,ylo,yhi) ); + + for i in range(TFMap.GetNbinsY()): + xnam = TFMap.GetXaxis().GetTitle(); + nbin = TFMap.GetNbinsX(); + ylo = TFMap.GetXaxis().GetBinLowEdge(1); + yhi = TFMap.GetXaxis().GetBinUpEdge(nbin); + hys.append( ROOT.TH1F("hys"+str(i),";"+xnam+";",nbin,ylo,yhi) ); + + # for i in range(TFMap.GetNbinsX()): + # for j in range(TFMap.GetNbinsY()): + # hxs[i].SetBinContent( j+1, TFMap.GetBinContent(i+1,j+1) ); + # hxs[i].SetBinError( j+1, TFMap.GetBinError(i+1,j+1) ); + + for i in range(TFMap.GetNbinsY()): + for j in range(TFMap.GetNbinsX()): + hys[i].SetBinContent( j+1, TFMap.GetBinContent(j+1,i+1) ); + hys[i].SetBinError( j+1, TFMap.GetBinError(j+1,i+1) ); + + colors = []; + for i in range(10): + colors.append(1); colors.append(2); colors.append(4); colors.append(6); + # for i in range(len(hxs)): + # hxs[i].SetLineColor(colors[i]); + # hxs[i].SetMarkerSize(0); + for i in range(len(hys)): + hys[i].SetLineColor(colors[i]); + hys[i].SetMarkerSize(0); + + # cx = ROOT.TCanvas("cx","cx",1000,800); + # hxs[0].SetMaximum( 1.25*TFMap.GetMaximum() ); + # hxs[0].SetMinimum( 0. ); + # hxs[0].Draw("histe"); + # for i in range(1,len(hxs)): + # hxs[i].Draw("histesames") + # cx.SaveAs(pdir+"/"+name+"_hxs.pdf"); + + cy = ROOT.TCanvas("cy","cy",1000,800); + hys[0].SetMaximum( 1.25*TFMap.GetMaximum() ); + hys[0].SetMinimum( 0. ); + hys[0].Draw("histe"); + for i in range(1,len(hys)): + hys[i].Draw("histesames") + cy.SaveAs(pdir+"/"+name+"_hys.pdf"); + + return hys; + +def plotROCs(grs,legs,pdir,name): + + canroc = ROOT.TCanvas("c","c",1000,800); + hrl1 = canroc.DrawFrame(0.,0.,1.0,1.0); + hrl1.GetXaxis().SetTitle("signal efficiency"); + hrl1.GetYaxis().SetTitle("background efficiency"); + + leg = ROOT.TLegend( 0.2, 0.6, 0.5, 0.9 ); + leg.SetBorderSize( 0 ); + leg.SetFillStyle( 0 ); + leg.SetTextSize( 0.03 ); + + colors = [1,2,4,6,7] + ctr = 0; + for gr in grs: + gr.Draw(); + gr.SetLineColor(colors[ctr]); + leg.AddEntry(gr,legs[ctr],"l"); + ctr += 1; + leg.Draw(); + canroc.SaveAs(pdir+"/"+name+".pdf"); + + +def makeROCFromHisto(hists,LtoR=True): + + hsig = hists[0]; + hbkg = hists[1]; + + nbins = hsig.GetNbinsX(); + binsize = hsig.GetBinWidth(1); + lowedge = hsig.GetBinLowEdge(1); + + #print "lowedge: ",lowedge + + hsigIntegral = hsig.Integral(); + hbkgIntegral = hbkg.Integral(); + + xval = array.array('d', []) + yval = array.array('d', []) + ctr = 0; + effBkgPrev = -9999; + for i in range(1,nbins+1): + + effBkg = 0; + effSig = 0; + + if LtoR: effBkg = hbkg.Integral( i, nbins )/hbkgIntegral; + else: effBkg = hbkg.Integral( 1, i )/hbkgIntegral; + + if LtoR: effSig = hsig.Integral( i, nbins )/hsigIntegral; + else: effSig = hsig.Integral( 1, i )/hsigIntegral; + + #if not effBkg == 0.: print "cut: ",(lowedge+(i-1)*binsize),"effBkg: ", effBkg, ", effSig: ", effSig; + + xval.append( effSig ); + yval.append( effBkg ); + + #effBkgPrev = effBkg; + ctr = ctr + 1; + + #print nbins, "and ", ctr + tg = ROOT.TGraph( nbins, xval, yval ); + tg.SetName( "tg"+hsig.GetName() ); + return tg; + +def dummy(): + print "hi"; + + + +def TOTerror(hmc, ratio ): + hmc.Sumw2() + den1 = hmc.Clone ("den1"); + den2 = hmc.Clone ("den2"); + + nvar = hmc.GetNbinsX(); + + x1 = [] + y1 = [] + exl1 = [] + eyl1= [] + exh1= [] + eyh1= [] + + for km in range(1,nvar+1): + delta = hmc.GetBinError(km) + den1.SetBinError(km,0) + #den1.SetBinContent(km,hmc.GetBinContent(km) + delta); + #den2.SetBinContent(km,hmc.GetBinContent(km) - delta); + + + # ratio from variation and nominal + ratiop = hmc.Clone("ratiop"); + ratiom = hmc.Clone("ratiom"); + + ratiop.Divide(den1); + ratiom.Divide(den1); + #den1.Divide(ratiop) + #den2.Divide(ratiom) + ''' + for km in range(0,nvar): + if(ratio.GetBinContent(km+1)==0): + y1.append(1.) + eyl1.append(0.) + eyh1.append(0.) + else: + y1.append(1) + eyl1.append(abs(ratiop.GetBinContent(km+1)))# - ratio.GetBinContent(km+1))) + eyh1.append(abs(ratiom.GetBinContent(km+1)))# - ratio.GetBinContent(km+1))) + x1.append(ratio.GetBinCenter(km+1)) + exl1.append(ratio.GetBinWidth(km)/2) + exh1.append(ratio.GetBinWidth(km)/2) + x1Array = array.array ('d', x1) + y1Array = array.array ('d', y1) + exl1Array = array.array ('d', exl1) + eyl1Array = array.array ('d', eyl1) + exh1Array = array.array ('d', exh1) + eyh1Array = array.array ('d', eyh1) + err = ROOT.TGraphAsymmErrors (nvar, x1Array, y1Array, exl1Array, exh1Array, eyl1Array, eyh1Array); + ''' + + return ratiop; diff --git a/analysis/plotTrigger.py b/analysis/plotTrigger.py new file mode 100644 index 0000000..ab0de6b --- /dev/null +++ b/analysis/plotTrigger.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python +import ROOT as rt,sys,math,os +import numpy as np +from multiprocessing import Process +from optparse import OptionParser +from operator import add +import math +import sys +import time + +# including other directories +#sys.path.insert(0, '../.') + +def main(options, args): + + lumi_GH = 16.146 + lumi_BCDEF = 19.721 + lumi_total = lumi_GH + lumi_BCDEF + + f_trig = rt.TFile.Open( + "$ZPRIMEPLUSJET_BASE/analysis/ggH/RUNTriggerEfficiencies_SingleMuon_Run2016_V2p1_v03.root", "read") + trig_denom = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtDenom_cutJet") + trig_numer = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtPassing_cutJet") + trig_denom.SetDirectory(0) + trig_numer.SetDirectory(0) + trig_denom.RebinX(2) + trig_numer.RebinX(2) + trig_denom.RebinY(5) + trig_numer.RebinY(5) + trig_eff = rt.TEfficiency() + if (rt.TEfficiency.CheckConsistency(trig_numer, trig_denom)): + trig_eff = rt.TEfficiency(trig_numer, trig_denom) + trig_eff.SetDirectory(0) + f_trig.Close() + + c = rt.TCanvas('c','c',500,500) + c.SetRightMargin(0.15) + trig_eff.Draw('colztexte') + trig_eff.Paint('colztexte') + + hist_eff = trig_eff.GetPaintedHistogram() + hist_eff.SetMarkerSize(1.0) + hist_eff.GetYaxis().SetRangeUser(0,1000) + hist_eff.GetXaxis().SetRangeUser(0,300) + hist_eff.Draw('colztext') + hist_eff.GetXaxis().SetTitle('AK8 m_{SD} (GeV)') + hist_eff.GetYaxis().SetTitle('AK8 p_{T} (GeV)') + + tlatex = [] + l = rt.TLatex() + l.SetTextSize(0.011) + l.SetTextAlign(13) + for i in range(1,hist_eff.GetNbinsX()+1): + for j in range(1,hist_eff.GetNbinsY()+1): + massForTrig = hist_eff.GetXaxis().GetBinCenter(i) + ptForTrig = hist_eff.GetYaxis().GetBinCenter(j) + eff = trig_eff.GetEfficiency(trig_eff.FindFixBin(massForTrig, ptForTrig)) + errUp = trig_eff.GetEfficiencyErrorUp(trig_eff.FindFixBin(massForTrig, ptForTrig)) + errDown = trig_eff.GetEfficiencyErrorLow(trig_eff.FindFixBin(massForTrig, ptForTrig)) + hist_eff.SetBinError(i,j,max(errUp,errDown)) + #if eff > 0 and massForTrig < 300 and ptForTrig < 1000: + # l.DrawLatex(massForTrig-5,ptForTrig+20,"#splitline{%.3f}{#splitline{+%.3f}{-%.3f}}"%(eff,errUp,errDown)) + + tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi_total) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = rt.TLatex(0.17,0.92,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = rt.TLatex(0.25,0.92," Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); + tag1.Draw(); tag2.Draw(); tag3.Draw() + c.Print('trig_eff.pdf') + + d = rt.TCanvas('d','d',600,500) + d.SetRightMargin(0.15) + # get muon trigger efficiency object + + f_mutrig_GH = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_Period4.root", "read") + mutrig_eff_GH = f_mutrig_GH.Get("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/pt_abseta_DATA") + mutrig_eff_GH.Sumw2() + mutrig_eff_GH.SetDirectory(0) + f_mutrig_GH.Close() + + f_mutrig_BCDEF = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_RunBtoF.root", "read") + mutrig_eff_BCDEF = f_mutrig_BCDEF.Get("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/pt_abseta_DATA") + mutrig_eff_BCDEF.Sumw2() + mutrig_eff_BCDEF.SetDirectory(0) + f_mutrig_BCDEF.Close() + + mutrig_eff = mutrig_eff_GH.Clone('pt_abseta_DATA_mutrig_ave') + mutrig_eff.Scale(lumi_GH / lumi_total) + mutrig_eff.Add(mutrig_eff_BCDEF, lumi_BCDEF / lumi_total) + + d.SetLogx() + mutrig_eff.SetMinimum(0) + mutrig_eff.SetMaximum(1) + mutrig_eff.GetXaxis().SetMoreLogLabels(1) + mutrig_eff.GetXaxis().SetNoExponent() + mutrig_eff.Draw('colztexte') + rt.gStyle.SetPaintTextFormat("3.3f") + + tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi_total) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = rt.TLatex(0.17,0.92,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = rt.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); + tag1.Draw(); tag2.Draw(); tag3.Draw() + d.Print('mutrig_eff.pdf') + + f_muid_GH = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_GH.root", "read") + muid_eff_GH = f_muid_GH.Get("MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/efficienciesDATA/pt_abseta_DATA") + muid_eff_GH.Sumw2() + muid_eff_GH.SetDirectory(0) + f_muid_GH.Close() + + f_muid_BCDEF = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_BCDEF.root", "read") + muid_eff_BCDEF = f_muid_BCDEF.Get( + "MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/efficienciesDATA/pt_abseta_DATA") + muid_eff_BCDEF.Sumw2() + muid_eff_BCDEF.SetDirectory(0) + f_muid_BCDEF.Close() + + + muid_eff = muid_eff_GH.Clone('pt_abseta_DATA_muid_ave') + muid_eff.Scale(lumi_GH / lumi_total) + muid_eff.Add(muid_eff_BCDEF, lumi_BCDEF / lumi_total) + + + muid_eff.SetMinimum(0) + muid_eff.SetMaximum(1) + muid_eff.GetXaxis().SetMoreLogLabels(1) + muid_eff.GetXaxis().SetNoExponent() + #muid_eff.GetZaxis().SetTitle('') + muid_eff.Draw('colztexte') + rt.gPad.Modified() + rt.gPad.Update() + rt.gStyle.SetPaintTextFormat("3.3f") + + tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi_total) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = rt.TLatex(0.17,0.92,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = rt.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); + tag1.Draw(); tag2.Draw(); tag3.Draw() + d.Print('muid_eff.pdf') + + + f_muiso_GH = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_ISO_GH.root", "read") + muiso_eff_GH = f_muiso_GH.Get("LooseISO_LooseID_pt_eta/efficienciesDATA/pt_abseta_DATA") + muiso_eff_GH.Sumw2() + muiso_eff_GH.SetDirectory(0) + f_muiso_GH.Close() + + f_muiso_BCDEF = rt.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_ISO_BCDEF.root", "read") + muiso_eff_BCDEF = f_muiso_BCDEF.Get("LooseISO_LooseID_pt_eta/efficienciesDATA/pt_abseta_DATA") + muiso_eff_BCDEF.Sumw2() + muiso_eff_BCDEF.SetDirectory(0) + f_muiso_BCDEF.Close() + + muiso_eff = muiso_eff_GH.Clone('pt_abseta_DATA_muiso_ave') + muiso_eff.Scale(lumi_GH / lumi_total) + muiso_eff.Add(muiso_eff_BCDEF, lumi_BCDEF / lumi_total) + + muiso_eff.SetMinimum(0) + muiso_eff.SetMaximum(1) + muiso_eff.GetXaxis().SetMoreLogLabels(1) + muiso_eff.GetXaxis().SetNoExponent() + muiso_eff.Draw('colztexte') + rt.gStyle.SetPaintTextFormat("4.4f") + + tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi_total) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.033) + tag2 = rt.TLatex(0.17,0.92,"CMS") + tag2.SetNDC(); tag2.SetTextFont(62) + tag3 = rt.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC(); tag3.SetTextFont(52) + tag2.SetTextSize(0.042); tag3.SetTextSize(0.033); + tag1.Draw(); tag2.Draw(); tag3.Draw() + d.Print('muiso_eff.pdf') + + + +if __name__ == '__main__': + parser = OptionParser() + parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') + parser.add_option('--lumi', dest='lumi', type=float, default = 20,help='lumi in 1/fb ', metavar='lumi') + parser.add_option('-i','--idir', dest='idir', default = './',help='directory with data', metavar='idir') + parser.add_option('-o','--odir', dest='odir', default = './',help='directory to write cards', metavar='odir') + + (options, args) = parser.parse_args() + import tdrstyle + tdrstyle.setTDRStyle() + rt.gStyle.SetPadTopMargin(0.10) + rt.gStyle.SetPadLeftMargin(0.16) + rt.gStyle.SetPadRightMargin(0.10) + #rt.gStyle.SetPaintTextFormat("5.5f") + rt.gStyle.SetPaintTextFormat("2.2f") + rt.gStyle.SetOptFit(0000) + rt.gStyle.SetPalette(rt.kBird) + rt.gStyle.SetNumberContours(999) + rt.gROOT.SetBatch() + + main(options, args) diff --git a/analysis/sampleContainer1lep.py b/analysis/sampleContainer1lep.py new file mode 100644 index 0000000..dfcc6ea --- /dev/null +++ b/analysis/sampleContainer1lep.py @@ -0,0 +1,1228 @@ +import ROOT +from ROOT import TFile, TTree, TChain, gPad, gDirectory +from multiprocessing import Process +from optparse import OptionParser +from operator import add +import math +import array +import scipy +import pdb +import sys +import time +import warnings + +PTCUT = 100. +PTCUTMUCR = 250. +DBTAGCUT_AK8 = 0.9 +DBTAGCUT_CA15 = 0.75 +T21DDTCUT = 0.55 +MUONPTCUT = 55 +METCUT = 140 +MASSCUT = 40 +NJETCUT = 100 + + +def delta_phi(phi1, phi2): + PI = 3.14159265359 + x = phi1 - phi2 + while x >= PI: + x -= (2 * PI) + while x < -PI: + x += (2 * PI) + return x + + +def delta_phi_david(phi1, phi2): + return math.acos(math.cos(phi1 - phi2)) + + +######################################################################################################### +class sampleContainer: + def __init__(self, name, fn, sf=1, DBTAGCUTMIN=-99., lumi=1, isData=False, fillCA15=False, cutFormula='1', + minBranches=False): + self._name = name + print(name) + self.DBTAGCUTMIN = DBTAGCUTMIN + self._fillCA15 = fillCA15 + if self._fillCA15: + self.DBTAGCUT = DBTAGCUT_CA15 + else: + self.DBTAGCUT = DBTAGCUT_AK8 + self._fn = fn + if len(fn) > 0: + self._tf = ROOT.TFile.Open(self._fn[0]) + self._tt = ROOT.TChain('otree') + for fn in self._fn: self._tt.Add(fn) + self._sf = sf + self._lumi = lumi + warnings.filterwarnings(action='ignore', category=RuntimeWarning, message='creating converter.*') + if not self._fillCA15: + self._cutFormula = ROOT.TTreeFormula("cutFormula", + "(" + cutFormula + ")&&(AK8Puppijet0_pt>%f||AK8Puppijet0_pt_JESDown>%f||AK8Puppijet0_pt_JESUp>%f||AK8Puppijet0_pt_JERUp>%f||AK8Puppijet0_pt_JERDown>%f)" % ( + PTCUTMUCR, PTCUTMUCR, PTCUTMUCR, PTCUTMUCR, PTCUTMUCR), self._tt) + else: + self._cutFormula = ROOT.TTreeFormula("cutFormula", + "(" + cutFormula + ")&&(CA15Puppijet0_pt>%f||CA15Puppijet0_pt_JESDown>%f||CA15Puppijet0_pt_JESUp>%f||CA15Puppijet0_pt_JERUp>%f||CA15Puppijet0_pt_JERDown>%f)" % ( + PTCUTMUCR, PTCUTMUCR, PTCUTMUCR, PTCUTMUCR, PTCUTMUCR), self._tt) + self._isData = isData + # print lumi + # print self._NEv.GetBinContent(1) + if self._isData: + self._lumi = 1 + # based on https://github.com/thaarres/PuppiSoftdropMassCorr Summer16 + self.corrGEN = ROOT.TF1("corrGEN", "[0]+[1]*pow(x*[2],-[3])", 200, 3500) + self.corrGEN.SetParameter(0, 1.00626) + self.corrGEN.SetParameter(1, -1.06161) + self.corrGEN.SetParameter(2, 0.0799900) + self.corrGEN.SetParameter(3, 1.20454) + + self.corrRECO_cen = ROOT.TF1("corrRECO_cen", "[0]+[1]*x+[2]*pow(x,2)+[3]*pow(x,3)+[4]*pow(x,4)+[5]*pow(x,5)", + 200, 3500) + self.corrRECO_cen.SetParameter(0, 1.09302) + self.corrRECO_cen.SetParameter(1, -0.000150068) + self.corrRECO_cen.SetParameter(2, 3.44866e-07) + self.corrRECO_cen.SetParameter(3, -2.68100e-10) + self.corrRECO_cen.SetParameter(4, 8.67440e-14) + self.corrRECO_cen.SetParameter(5, -1.00114e-17) + + self.corrRECO_for = ROOT.TF1("corrRECO_for", "[0]+[1]*x+[2]*pow(x,2)+[3]*pow(x,3)+[4]*pow(x,4)+[5]*pow(x,5)", + 200, 3500) + self.corrRECO_for.SetParameter(0, 1.27212) + self.corrRECO_for.SetParameter(1, -0.000571640) + self.corrRECO_for.SetParameter(2, 8.37289e-07) + self.corrRECO_for.SetParameter(3, -5.20433e-10) + self.corrRECO_for.SetParameter(4, 1.45375e-13) + self.corrRECO_for.SetParameter(5, -1.50389e-17) + + # f_puppi= ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ZqqJet/puppiCorr.root","read") + # self._puppisd_corrGEN = f_puppi.Get("puppiJECcorr_gen") + # self._puppisd_corrRECO_cen = f_puppi.Get("puppiJECcorr_reco_0eta1v3") + # self._puppisd_corrRECO_for = f_puppi.Get("puppiJECcorr_reco_1v3eta2v5") + + f_pu = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/puWeights_All.root", "read") + self._puw = f_pu.Get("puw") + self._puw_up = f_pu.Get("puw_p") + self._puw_down = f_pu.Get("puw_m") + + # get histogram for transform + if not self._fillCA15: + f_h2ddt = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ZqqJet/h3_n2ddt_26eff_36binrho11pt_Spring16.root", + "read") # GridOutput_v13_WP026.root # smooth version of the ddt ; exp is 4.45 vs 4.32 (3% worse) AK8 + else: + f_h2ddt = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/PbbJet/h3_n2ddt_CA15.root", + "read") # GridOutput_v13_WP026.root # smooth version of the ddt ; exp is 4.45 vs 4.32 (3% worse) CA15 + self._trans_h2ddt = f_h2ddt.Get("h2ddt") + self._trans_h2ddt.SetDirectory(0) + f_h2ddt.Close() + + # get trigger efficiency object + + if not self._fillCA15: + f_trig = ROOT.TFile.Open( "$ZPRIMEPLUSJET_BASE/analysis/ggH/RUNTriggerEfficiencies_SingleMuon_Run2016_V2p1_v03.root", "read") #AK8 + self._trig_denom = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtDenom_cutJet") + self._trig_numer = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtPassing_cutJet") + else: + f_trig = ROOT.TFile.Open( "$ZPRIMEPLUSJET_BASE/analysis/ggH/RUNTriggerEfficiencies_SingleMuon_Run2016_V2p4_v08.root", "read") #CA15 + self._trig_denom = f_trig.Get("DijetCA15TriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtDenom_cutJet") + self._trig_numer = f_trig.Get("DijetCA15TriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtPassing_cutJet") + self._trig_denom = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtDenom_cutJet") + self._trig_numer = f_trig.Get("DijetTriggerEfficiencySeveralTriggers/jet1SoftDropMassjet1PtPassing_cutJet") + self._trig_denom.SetDirectory(0) + self._trig_numer.SetDirectory(0) + self._trig_denom.RebinX(2) + self._trig_numer.RebinX(2) + self._trig_denom.RebinY(5) + self._trig_numer.RebinY(5) + self._trig_eff = ROOT.TEfficiency() + if (ROOT.TEfficiency.CheckConsistency(self._trig_numer, self._trig_denom)): + self._trig_eff = ROOT.TEfficiency(self._trig_numer, self._trig_denom) + self._trig_eff.SetDirectory(0) + f_trig.Close() + + # get muon trigger efficiency object + + lumi_GH = 16.146 + lumi_BCDEF = 19.721 + lumi_total = lumi_GH + lumi_BCDEF + + f_mutrig_GH = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_Period4.root", "read") + self._mutrig_eff_GH = f_mutrig_GH.Get("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/pt_abseta_DATA") + self._mutrig_eff_GH.Sumw2() + self._mutrig_eff_GH.SetDirectory(0) + f_mutrig_GH.Close() + + f_mutrig_BCDEF = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_RunBtoF.root", "read") + self._mutrig_eff_BCDEF = f_mutrig_BCDEF.Get("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/pt_abseta_DATA") + self._mutrig_eff_BCDEF.Sumw2() + self._mutrig_eff_BCDEF.SetDirectory(0) + f_mutrig_BCDEF.Close() + + self._mutrig_eff = self._mutrig_eff_GH.Clone('pt_abseta_DATA_mutrig_ave') + self._mutrig_eff.Scale(lumi_GH / lumi_total) + self._mutrig_eff.Add(self._mutrig_eff_BCDEF, lumi_BCDEF / lumi_total) + + # get muon ID efficiency object + + f_muid_GH = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_GH.root", "read") + self._muid_eff_GH = f_muid_GH.Get("MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/efficienciesDATA/pt_abseta_DATA") + self._muid_eff_GH.Sumw2() + self._muid_eff_GH.SetDirectory(0) + f_muid_GH.Close() + + f_muid_BCDEF = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_BCDEF.root", "read") + self._muid_eff_BCDEF = f_muid_BCDEF.Get( + "MC_NUM_LooseID_DEN_genTracks_PAR_pt_eta/efficienciesDATA/pt_abseta_DATA") + self._muid_eff_BCDEF.Sumw2() + self._muid_eff_BCDEF.SetDirectory(0) + f_muid_BCDEF.Close() + + self._muid_eff = self._muid_eff_GH.Clone('pt_abseta_DATA_muid_ave') + self._muid_eff.Scale(lumi_GH / lumi_total) + self._muid_eff.Add(self._muid_eff_BCDEF, lumi_BCDEF / lumi_total) + + # get muon ISO efficiency object + + f_muiso_GH = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_ISO_GH.root", "read") + self._muiso_eff_GH = f_muiso_GH.Get("LooseISO_LooseID_pt_eta/efficienciesDATA/pt_abseta_DATA") + self._muiso_eff_GH.Sumw2() + self._muiso_eff_GH.SetDirectory(0) + f_muiso_GH.Close() + + f_muiso_BCDEF = ROOT.TFile.Open("$ZPRIMEPLUSJET_BASE/analysis/ggH/EfficienciesAndSF_ISO_BCDEF.root", "read") + self._muiso_eff_BCDEF = f_muiso_BCDEF.Get("LooseISO_LooseID_pt_eta/efficienciesDATA/pt_abseta_DATA") + self._muiso_eff_BCDEF.Sumw2() + self._muiso_eff_BCDEF.SetDirectory(0) + f_muiso_BCDEF.Close() + + self._muiso_eff = self._muiso_eff_GH.Clone('pt_abseta_DATA_muiso_ave') + self._muiso_eff.Scale(lumi_GH / lumi_total) + self._muiso_eff.Add(self._muiso_eff_BCDEF, lumi_BCDEF / lumi_total) + + self._minBranches = minBranches + # set branch statuses and addresses + self._branches = [('AK8Puppijet0_msd', 'd', -999), ('AK8Puppijet0_pt', 'd', -999), + ('AK8Puppijet0_pt_JERUp', 'd', -999), ('AK8Puppijet0_pt_JERDown', 'd', -999), + ('AK8Puppijet0_pt_JESUp', 'd', -999), ('AK8Puppijet0_pt_JESDown', 'd', -999), + ('AK8Puppijet0_eta', 'd', -999), ('AK8Puppijet0_phi', 'd', -999), + ('AK8Puppijet0_tau21', 'd', -999), ('AK8Puppijet0_tau32', 'd', -999), + ('AK8Puppijet0_N2sdb1', 'd', -999), ('puWeight', 'f', 0), ('scale1fb', 'f', 0), + ('AK8Puppijet0_doublecsv', 'd', -999), + ('kfactor', 'f', 0), ('kfactorNLO', 'f', 0), ('nAK4PuppijetsPt30', 'i', -999), + ('nAK4PuppijetsPt30dR08_0', 'i', -999), + ('nAK4PuppijetsPt30dR08jesUp_0', 'i', -999), ('nAK4PuppijetsPt30dR08jesDown_0', 'i', -999), + ('nAK4PuppijetsPt30dR08jerUp_0', 'i', -999), ('nAK4PuppijetsPt30dR08jerDown_0', 'i', -999), + ('nAK4PuppijetsMPt50dR08_0', 'i', -999), + ('AK8Puppijet0_ratioCA15_04', 'd', -999), + ('pfmet', 'f', -999), ('pfmetphi', 'f', -999), ('puppet', 'f', -999), + ('puppetphi', 'f', -999), + ('MetXCorrjesUp', 'd', -999), ('MetXCorrjesDown', 'd', -999), ('MetYCorrjesUp', 'd', -999), + ('MetYCorrjesDown', 'd', -999), + ('MetXCorrjerUp', 'd', -999), ('MetXCorrjerDown', 'd', -999), ('MetYCorrjerUp', 'd', -999), + ('MetYCorrjerDown', 'd', -999), + ('neleLoose', 'i', -999), ('nmuLoose', 'i', -999), ('ntau', 'i', -999), + ('nphoLoose', 'i', -999), + ('triggerBits', 'i', 1), ('passJson', 'i', 1), ('vmuoLoose0_pt', 'd', -999), + ('vmuoLoose0_eta', 'd', -999), ('vmuoLoose0_phi', 'd', -999), + ('npv', 'i', 1), ('npu', 'i', 1), + ('AK8Puppijet0_isTightVJet', 'i', 0) + ] + if not self._minBranches: + self._branches.extend([('nAK4PuppijetsfwdPt30', 'i', -999), ('nAK4PuppijetsLPt50dR08_0', 'i', -999), + ('nAK4PuppijetsTPt50dR08_0', 'i', -999), + ('nAK4PuppijetsLPt100dR08_0', 'i', -999), ('nAK4PuppijetsMPt100dR08_0', 'i', -999), + ('nAK4PuppijetsTPt100dR08_ 0', 'i', -999), + ('nAK4PuppijetsLPt150dR08_0', 'i', -999), ('nAK4PuppijetsMPt150dR08_0', 'i', -999), + ('nAK4PuppijetsTPt150dR08_0', 'i', -999), + ('nAK4PuppijetsLPt50dR08_1', 'i', -999), ('nAK4PuppijetsMPt50dR08_1', 'i', -999), + ('nAK4PuppijetsTPt50dR08_1', 'i', -999), + ('nAK4PuppijetsLPt100dR08_1', 'i', -999), ('nAK4PuppijetsMPt100dR08_1', 'i', -999), + ('nAK4PuppijetsTPt100dR08_ 1', 'i', -999), + ('nAK4PuppijetsLPt150dR08_1', 'i', -999), ('nAK4PuppijetsMPt150dR08_1', 'i', -999), + ('nAK4PuppijetsTPt150dR08_1', 'i', -999), + ('nAK4PuppijetsLPt50dR08_2', 'i', -999), ('nAK4PuppijetsMPt50dR08_2', 'i', -999), + ('nAK4PuppijetsTPt50dR08_2', 'i', -999), + ('nAK4PuppijetsLPt100dR08_2', 'i', -999), ('nAK4PuppijetsMPt100dR08_2', 'i', -999), + ('nAK4PuppijetsTPt100dR08_ 1', 'i', -999), + ('nAK4PuppijetsLPt150dR08_2', 'i', -999), ('nAK4PuppijetsMPt150dR08_2', 'i', -999), + ('nAK4PuppijetsTPt150dR08_2', 'i', -999), + ('nAK4PuppijetsLPt150dR08_0', 'i', -999), ('nAK4PuppijetsMPt150dR08_0', 'i', -999), + ('nAK4PuppijetsTPt150dR08_0', 'i', -999), + ('AK8Puppijet1_pt', 'd', -999), ('AK8Puppijet2_pt', 'd', -999), + ('AK8Puppijet1_tau21', 'd', -999), ('AK8Puppijet2_tau21', 'd', -999), + ('AK8Puppijet1_msd', 'd', -999), ('AK8Puppijet2_msd', 'd', -999), + ('AK8Puppijet1_doublecsv', 'd', -999), ('AK8Puppijet2_doublecsv', 'i', -999), + ('AK8Puppijet1_isTightVJet', 'i', 0), + ('AK8Puppijet2_isTightVJet', 'i', 0), ('AK4Puppijet3_pt', 'f', 0), + ('AK4Puppijet2_pt', 'f', 0), ('AK4Puppijet1_pt', 'f', 0), + ('AK4Puppijet0_pt', 'f', 0), + ('AK4Puppijet3_eta', 'f', 0), ('AK4Puppijet2_eta', 'f', 0), + ('AK4Puppijet1_eta', 'f', 0), ('AK4Puppijet0_eta', 'f', 0) + ]) + + # AK8 + if not self._fillCA15: + self._branches.extend([('AK8Puppijet0_msd', 'd', -999), ('AK8Puppijet0_pt', 'd', -999), + ('AK8Puppijet0_pt_JERUp', 'd', -999), ('AK8Puppijet0_pt_JERDown', 'd', -999), + ('AK8Puppijet0_pt_JESUp', 'd', -999), ('AK8Puppijet0_pt_JESDown', 'd', -999), + ('AK8Puppijet0_eta', 'd', -999), ('AK8Puppijet0_phi', 'd', -999), + ('AK8Puppijet0_tau21', 'd', -999), ('AK8Puppijet0_tau32', 'd', -999), + ('AK8Puppijet0_N2sdb1', 'd', -999), ('AK8Puppijet0_doublecsv', 'd', -999), + ('AK8Puppijet0_isTightVJet', 'i', 0) + ]) + if not self._minBranches: + self._branches.extend([('AK8Puppijet1_pt', 'd', -999), ('AK8Puppijet2_pt', 'd', -999), + ('AK8Puppijet1_tau21', 'd', -999), ('AK8Puppijet2_tau21', 'd', -999), + ('AK8Puppijet1_msd', 'd', -999), ('AK8Puppijet2_msd', 'd', -999), + ('AK8Puppijet1_doublecsv', 'd', -999), ('AK8Puppijet2_doublecsv', 'i', -999), + ('AK8Puppijet1_isTightVJet', 'i', 0), ('AK8Puppijet2_isTightVJet', 'i', 0) + ]) + else: + self._branches.extend([('CA15Puppijet0_msd', 'd', -999), ('CA15Puppijet0_pt', 'd', -999), + ('CA15Puppijet0_pt_JERUp', 'd', -999), ('CA15Puppijet0_pt_JERDown', 'd', -999), + ('CA15Puppijet0_pt_JESUp', 'd', -999), ('CA15Puppijet0_pt_JESDown', 'd', -999), + ('CA15Puppijet0_eta', 'd', -999), ('CA15Puppijet0_phi', 'd', -999), + ('CA15Puppijet0_tau21', 'd', -999), ('CA15Puppijet0_tau32', 'd', -999), + ('CA15Puppijet0_N2sdb1', 'd', -999,), ('CA15Puppijet0_doublesub', 'd', -999), + ('CA15Puppijet0_isTightVJet', 'i', 0) + ]) + if not self._minBranches: + self._branches.extend([('CA15Puppijet1_pt', 'd', -999), ('CA15Puppijet2_pt', 'd', -999), + ('CA15Puppijet1_tau21', 'd', -999), ('CA15Puppijet2_tau21', 'd', -999), + ('CA15Puppijet1_msd', 'd', -999), ('CA15Puppijet2_msd', 'd', -999), + ('CA15Puppijet1_doublesub', 'd', -999), ('CA15Puppijet2_doublesub', 'i', -999), + ('CA15Puppijet1_isTightVJet', 'i', 0), ('CA15Puppijet2_isTightVJet', 'i', 0) + ]) + + if not self._isData: + self._branches.extend([('genMuFromW', 'i', -999), ('genEleFromW', 'i', -999), ('genTauFromW', 'i', -999)]) + self._branches.extend( + [('genVPt', 'f', -999), ('genVEta', 'f', -999), ('genVPhi', 'f', -999), ('genVMass', 'f', -999), + ('topPtWeight', 'f', -999), ('topPt', 'f', -999), ('antitopPt', 'f', -999)]) + + self._tt.SetBranchStatus("*", 0) + for branch in self._branches: + self._tt.SetBranchStatus(branch[0], 1) + for branch in self._branches: + setattr(self, branch[0].replace(' ', ''), array.array(branch[1], [branch[2]])) + self._tt.SetBranchAddress(branch[0], getattr(self, branch[0].replace(' ', ''))) + + # x = array.array('d',[0]) + # self._tt.SetBranchAddress( "h_n_ak4", n_ak4 ) + + if not self._fillCA15: + self._jet_type = "AK8" + self._rhobins = 50 + self._lrhobin = -7 + self._hrhobin = -1 + self._lrhocut = -6.0 + self._hrhocut = -2.1 + else: + self._jet_type = "CA15" + self._rhobins = 42 + self._lrhobin = -5 + self._hrhobin = 0 + self._lrhocut = -4.7 + self._hrhocut = -1.0 + + # define histograms + histos1d = { + 'h_npv': ["h_" + self._name + "_npv", "; number of PV;;", 100, 0, 100], + 'h_nmuLoose': ["h_" + self._name + "_nmuLoose", "; number of Loose muons;;", 20, 0, 20], + 'h_dPhi_muCR4': ["h_" + self._name + "_dPhi_muCR4", "; dPhi(muon, " + self._jet_type + " leading p_{T}); ",50, 0, 3], + 'h_N2ddt_muCR4': ["h_" + self._name + "_N2ddt", "; N2ddt ;", 50, -1, 1], + 'h_N2_muCR4': ["h_" + self._name + "_N2", "; N2 ;", 50, -1, 1], + 'h_met_muCR4': ["h_" + self._name + "_met_muCR4", "; E_{T}^{miss} (GeV) ;", 50, 0, 500], + 'h_eta_mu_muCR4_N2': ["h_" + self._name + "_eta_mu_muCR4_N2", "; leading muon #eta;", 50, -2.5, 2.5], + 'h_pt_ak8_muCR4_N2': ["h_" + self._name + "_pt_ak8_muCR4_N2", "; " + self._jet_type + " leading p_{T} (GeV);", 50, 300, 2100], + 'h_eta_ak8_muCR4_N2': ["h_" + self._name + "_eta_ak8_muCR4_N2", "; " + self._jet_type + " leading #eta;",50, -3, 3], + 'h_dbtag_ak8_muCR4_N2': ["h_" + self._name + "_dbtag_ak8_muCR4_N2", "; p_{T}-leading double b-tag;", 40, -1,1], + 'h_t21ddt_ak8_muCR4_N2': ["h_" + self._name + "_t21ddt_ak8_muCR4_N2", + "; " + self._jet_type + " #tau_{21}^{DDT};", 25, 0, 1.5], + 'h_msd_ak8_muCR4_N2': ["h_" + self._name + "_msd_ak8_muCR4_N2", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, + 40, 201], + 'h_msd_ak8_muCR4_N2_pass_JESUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_JESUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_JESDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_JESDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_JERUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_JERUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_JERDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_JERDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_mutriggerUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_mutriggerUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_mutriggerDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_mutriggerDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_muidUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_muidUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_muidDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_muidDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_muisoUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_muisoUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_muisoDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_muisoDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_PuUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_PuUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_pass_PuDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_pass_PuDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, + 40, 201], + 'h_msd_ak8_muCR4_N2_fail_JESUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_JESUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_JESDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_JESDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_JERUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_JERUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_JERDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_JERDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_mutriggerUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_mutriggerUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_mutriggerDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_mutriggerDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_muidUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_muidUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_muidDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_muidDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_muisoUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_muisoUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_muisoDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_muisoDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_PuUp': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_PuUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_N2_fail_PuDown': ["h_" + self._name + "_msd_ak8_muCR4_N2_fail_PuDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + } + if not self._minBranches: + histos1d_ext = { + 'h_Cuts': ["h_" + self._name + "_Cuts", "; Cut ", 7, 0, 7], + 'h_n_ak4': ["h_" + self._name + "_n_ak4", "; AK4 n_{jets}, p_{T} > 30 GeV;", 20, 0, 20], + 'h_ht': ["h_" + self._name + "_ht", "; HT (GeV);;", 50, 300, 2100], + 'h_pt_bbleading': ["h_" + self._name + "_pt_bbleading", "; " + self._jet_type + " leading p_{T} (GeV);", + 50, 300, 2100], + 'h_bb_bbleading': ["h_" + self._name + "_bb_bbleading", "; double b-tag ;", 40, -1, 1], + 'h_msd_bbleading': ["h_" + self._name + "_msd_bbleading", + "" + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 30, 40, 250], + 'h_n_ak4fwd': ["h_" + self._name + "_n_ak4fwd", "; AK4 n_{jets}, p_{T} > 30 GeV, 2.5<|#eta|<4.5;", 20, + 0, 20], + 'h_n_ak4L': ["h_" + self._name + "_n_ak4L", "; AK4 n_{L b-tags}, #DeltaR > 0.8, p_{T} > 40 GeV;", 20, 0, + 20], + 'h_n_ak4M': ["h_" + self._name + "_n_ak4M", "; AK4 n_{M b-tags}, #DeltaR > 0.8, p_{T} > 40 GeV;", 20, 0, + 20], + 'h_n_ak4T': ["h_" + self._name + "_n_ak4T", "; AK4 n_{T b-tags}, #DeltaR > 0.8, p_{T} > 40 GeV;", 20, 0, + 20], + 'h_n_ak4_dR0p8': ["h_" + self._name + "_n_ak4_dR0p8", "; AK4 n_{jets}, #DeltaR > 0.8, p_{T} > 30 GeV;", + 20, 0, 20], + 'h_isolationCA15': ["h_" + self._name + "_isolationCA15", "; " + self._jet_type + "/CA15 p_{T} ratio ;", + 50, 0.5, 1.5], + 'h_met': ["h_" + self._name + "_met", "; E_{T}^{miss} (GeV) ;", 50, 0, 500], + 'h_pt_ak8': ["h_" + self._name + "_pt_ak8", "; " + self._jet_type + " leading p_{T} (GeV);", 50, 300, + 2100], + 'h_eta_ak8': ["h_" + self._name + "_eta_ak8", "; " + self._jet_type + " leading #eta;", 50, -3, 3], + 'h_pt_ak8_sub1': ["h_" + self._name + "_pt_ak8_sub1", + "; " + self._jet_type + " subleading p_{T} (GeV);", 50, 300, 2100], + 'h_pt_ak8_sub2': ["h_" + self._name + "_pt_ak8_sub2", + "; " + self._jet_type + " 3rd leading p_{T} (GeV);", 50, 300, 2100], + 'h_pt_ak8_dbtagCut': ["h_" + self._name + "_pt_ak8_dbtagCut", + "; " + self._jet_type + " leading p_{T} (GeV);", 45, 300, + 2100], + 'h_msd_ak8': ["h_" + self._name + "_msd_ak8", "; p_{T}-leading m_{SD} (GeV);", 23, 40, 201], + 'h_rho_ak8': ["h_" + self._name + "_rho_ak8", "; p_{T}-leading #rho=log(m_{SD}^{2}/p_{T}^{2}) ;", 50, + -7, -1], + 'h_msd_ak8_raw': ["h_" + self._name + "_msd_ak8_raw", + "; " + self._jet_type + " m_{SD}^{PUPPI} no correction (GeV);", 23, + 40, 201], + 'h_msd_ak8_inc': ["h_" + self._name + "_msd_ak8_inc", "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", + 100, 0, 500], + 'h_msd_ak8_dbtagCut': ["h_" + self._name + "_msd_ak8_dbtagCut", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, + 201], + 'h_msd_ak8_t21ddtCut': ["h_" + self._name + "_msd_ak8_t21ddtCut", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, + 201], + 'h_msd_ak8_t21ddtCut_inc': ["h_" + self._name + "_msd_ak8_t21ddtCut_inc", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", + 100, 0, 500], + 'h_msd_ak8_N2Cut': ["h_" + self._name + "_msd_ak8_N2Cut", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_dbtag_ak8': ["h_" + self._name + "_dbtag_ak8", "; p_{T}-leading double b-tag;", 40, -1, 1], + 'h_dbtag_ak8_sub1': ["h_" + self._name + "_dbtag_ak8_sub1", "; 2nd p_{T}-leading double b-tag;", 40, -1, + 1], + 'h_dbtag_ak8_sub2': ["h_" + self._name + "_dbtag_ak8_sub2", "; 3rd p_{T}-leading double b-tag;", 40, -1, + 1], + 'h_t21_ak8': ["h_" + self._name + "_t21_ak8", "; " + self._jet_type + " #tau_{21};", 25, 0, 1.5], + 'h_t21ddt_ak8': ["h_" + self._name + "_t21ddt_ak8", "; " + self._jet_type + " #tau_{21}^{DDT};", 25, 0, + 1.5], + 'h_t32_ak8': ["h_" + self._name + "_t32_ak8", "; " + self._jet_type + " #tau_{32};", 25, 0, 1.5], + 'h_t32_ak8_t21ddtCut': ["h_" + self._name + "_t32_ak8_t21ddtCut", "; " + self._jet_type + " #tau_{32};", + 20, 0, 1.5], + 'h_n2b1sd_ak8': ["h_" + self._name + "_n2b1sd_ak8", "; " + self._jet_type + " N_{2}^{1} (SD);", 25, + -0.5, 0.5], + 'h_n2b1sdddt_ak8': ["h_" + self._name + "_n2b1sdddt_ak8", + "; " + self._jet_type + " N_{2}^{1,DDT} (SD);", 25, -0.5, 0.5], + 'h_n2b1sdddt_ak8_aftercut': ["h_" + self._name + "_n2b1sdddt_ak8_aftercut", + "; p_{T}-leading N_{2}^{1,DDT};", 25, -0.5, 0.5], + 'h_dbtag_ak8_aftercut': ["h_" + self._name + "_dbtag_ak8_aftercut", "; p_{T}-leading double-b tagger;", + 33, -1, 1], + 'h_msd_ak8_raw_SR_fail': ["h_" + self._name + "_msd_ak8_raw_SR_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} no corr (GeV);", 23, 40, 201], + 'h_msd_ak8_raw_SR_pass': ["h_" + self._name + "_msd_ak8_raw_SR_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} no corr (GeV);", 23, 40, 201], + + 'h_n_ak4L100': ["h_" + self._name + "_n_ak4L100", "; AK4 n_{L b-tags}, #DeltaR > 0.8, p_{T} > 100 GeV;", + 10, 0, 10], + 'h_n_ak4L150': ["h_" + self._name + "_n_ak4L150", "; AK4 n_{L b-tags}, #DeltaR > 0.8, p_{T} > 150 GeV;", + 10, 0, 10], + 'h_n_ak4M100': ["h_" + self._name + "_n_ak4M100", "; AK4 n_{M b-tags}, #DeltaR > 0.8, p_{T} > 100 GeV;", + 10, 0, 10], + 'h_n_ak4M150': ["h_" + self._name + "_n_ak4M150", "; AK4 n_{M b-tags}, #DeltaR > 0.8, p_{T} > 150 GeV;", + 10, 0, 10], + 'h_n_ak4T100': ["h_" + self._name + "_n_ak4T100", "; AK4 n_{T b-tags}, #DeltaR > 0.8, p_{T} > 100 GeV;", + 10, 0, 10], + 'h_n_ak4T150': ["h_" + self._name + "_n_ak4T150", "; AK4 n_{T b-tags}, #DeltaR > 0.8, p_{T} > 150 GeV;", + 10, 0, 10], + + 'h_msd_ak8_muCR1': ["h_" + self._name + "_msd_ak8_muCR1", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR2': ["h_" + self._name + "_msd_ak8_muCR2", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR3': ["h_" + self._name + "_msd_ak8_muCR3", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_pt_mu_muCR4': ["h_" + self._name + "_pt_mu_muCR4", "; leading muon p_{T} (GeV);", 50, 30, 500], + 'h_eta_mu_muCR4': ["h_" + self._name + "_eta_mu_muCR4", "; leading muon #eta;", 50, -2.5, 2.5], + 'h_pt_ak8_muCR4': ["h_" + self._name + "_pt_ak8_muCR4", "; " + self._jet_type + " leading p_{T} (GeV);", + 50, 300, 2100], + 'h_eta_ak8_muCR4': ["h_" + self._name + "_eta_ak8_muCR4", "; " + self._jet_type + " leading #eta;", 50, + -3, 3], + 'h_dbtag_ak8_muCR4': ["h_" + self._name + "_dbtag_ak8_muCR4", "; p_{T}-leading double b-tag;", 40, -1, + 1], + 'h_t21ddt_ak8_muCR4': ["h_" + self._name + "_t21ddt_ak8_muCR4", + "; " + self._jet_type + " #tau_{21}^{DDT};", 25, 0, 1.5], + 'h_msd_ak8_muCR4': ["h_" + self._name + "_msd_ak8_muCR4", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass': ["h_" + self._name + "_msd_ak8_muCR4_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, + 40, 201], + 'h_msd_ak8_muCR4_pass_JESUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_JESUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_JESDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_JESDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_JERUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_JERUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_JERDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_JERDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_mutriggerUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_mutriggerUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_mutriggerDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_mutriggerDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_muidUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_muidUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_muidDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_muidDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_muisoUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_muisoUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_muisoDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_muisoDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_PuUp': ["h_" + self._name + "_msd_ak8_muCR4_pass_PuUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_pass_PuDown': ["h_" + self._name + "_msd_ak8_muCR4_pass_PuDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail': ["h_" + self._name + "_msd_ak8_muCR4_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, + 40, 201], + 'h_msd_ak8_muCR4_fail_JESUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_JESUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_JESDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_JESDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_JERUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_JERUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_JERDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_JERDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_mutriggerUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_mutriggerUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_mutriggerDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_mutriggerDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_muidUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_muidUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_muidDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_muidDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_muisoUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_muisoUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_muisoDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_muisoDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_PuUp': ["h_" + self._name + "_msd_ak8_muCR4_fail_PuUp", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR4_fail_PuDown': ["h_" + self._name + "_msd_ak8_muCR4_fail_PuDown", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR5': ["h_" + self._name + "_msd_ak8_muCR5", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_muCR6': ["h_" + self._name + "_msd_ak8_muCR6", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_bbleading_muCR4_pass': ["h_" + self._name + "_msd_ak8_bbleading_muCR4_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_msd_ak8_bbleading_muCR4_fail': ["h_" + self._name + "_msd_ak8_bbleading_muCR4_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV);", 23, 40, 201], + 'h_pt_ca15': ["h_" + self._name + "_pt_ca15", "; CA15 p{T} (GeV);", 100, 300, 3000], + 'h_msd_ca15': ["h_" + self._name + "_msd_ca15", "; CA15 m_{SD}^{PUPPI} (GeV);", 35, 50, 400], + 'h_msd_ca15_t21ddtCut': ["h_" + self._name + "_msd_ca15_t21ddtCut", "; CA15 m_{SD}^{PUPPI} (GeV);", 35, + 50, 400], + 'h_t21_ca15': ["h_" + self._name + "_t21_ca15", "; CA15 #tau_{21};", 25, 0, 1.5], + 'h_t21ddt_ca15': ["h_" + self._name + "_t21ddt_ca15", "; CA15 #tau_{21};", 25, 0, 1.5] + } + histos1d = dict(histos1d.items() + histos1d_ext.items()) + + msd_binBoundaries = [] + for i in range(0, 24): + msd_binBoundaries.append(40. + i * 7) + pt_binBoundaries = [450, 500, 550, 600, 675, 800, 1000] + + histos2d_fix = { + 'h_rhop_v_t21_ak8': ["h_" + self._name + "_rhop_v_t21_ak8", + "; " + self._jet_type + " rho^{DDT}; " + self._jet_type + " <#tau_{21}>", 15, -5, 10, + 25, 0, 1.5], + 'h_rhop_v_t21_ca15': ["h_" + self._name + "_rhop_v_t21_ca15", "; CA15 rho^{DDT}; CA15 <#tau_{21}>", 15, -5, + 10, 25, 0, 1.5] + } + + histos2d = { + 'h_msd_v_pt_ak8_muCR4_N2_pass': ["h_" + self._name + "_msd_v_pt_ak8_muCR4_N2_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"], + 'h_msd_v_pt_ak8_muCR4_N2_fail': ["h_" + self._name + "_msd_v_pt_ak8_muCR4_N2_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"] + } + + if not self._minBranches: + histos2d_ext = { + 'h_msd_v_pt_ak8_muCR4_pass': ["h_" + self._name + "_msd_v_pt_ak8_muCR4_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"], + 'h_msd_v_pt_ak8_muCR4_fail': ["h_" + self._name + "_msd_v_pt_ak8_muCR4_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"], + 'h_msd_v_pt_ak8_bbleading_muCR4_pass': ["h_" + self._name + "_msd_v_pt_ak8_bbleading_muCR4_pass", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"], + 'h_msd_v_pt_ak8_bbleading_muCR4_fail': ["h_" + self._name + "_msd_v_pt_ak8_bbleading_muCR4_fail", + "; " + self._jet_type + " m_{SD}^{PUPPI} (GeV); " + self._jet_type + " p_{T} (GeV)"], + } + + histos2d = dict(histos2d.items() + histos2d_ext.items()) + + for key, val in histos1d.iteritems(): + setattr(self, key, ROOT.TH1F(val[0], val[1], val[2], val[3], val[4])) + (getattr(self, key)).Sumw2() + for key, val in histos2d_fix.iteritems(): + setattr(self, key, ROOT.TH2F(val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7])) + (getattr(self, key)).Sumw2() + for key, val in histos2d.iteritems(): + tmp = ROOT.TH2F(val[0], val[1], len(msd_binBoundaries) - 1, array.array('d', msd_binBoundaries), + len(pt_binBoundaries) - 1, array.array('d', pt_binBoundaries)) + setattr(self, key, tmp) + (getattr(self, key)).Sumw2() + + # loop + if len(fn) > 0: + self.loop() + + def loop(self): + # looping + nent = self._tt.GetEntries() + print nent + cut = [] + cut = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.] + + self._tt.SetNotify(self._cutFormula) + for i in xrange(nent): + if i % self._sf != 0: continue + + # self._tt.LoadEntry(i) + self._tt.LoadTree(i) + selected = False + for j in range(self._cutFormula.GetNdata()): + if (self._cutFormula.EvalInstance(j)): + selected = True + break + if not selected: continue + + self._tt.GetEntry(i) + + if (nent / 100 > 0 and i % (1 * nent / 100) == 0): + sys.stdout.write("\r[" + "=" * int(20 * i / nent) + " " + str(round(100. * i / nent, 0)) + "% done") + sys.stdout.flush() + + puweight = self.puWeight[0] # corrected + nPuForWeight = min(self.npu[0], 49.5) + # $print(puweight,self._puw.GetBinContent(self._puw.FindBin(nPuForWeight))) + # puweight = self._puw.GetBinContent(self._puw.FindBin(nPuForWeight)) + puweight_up = self._puw_up.GetBinContent(self._puw_up.FindBin(nPuForWeight)) + puweight_down = self._puw_down.GetBinContent(self._puw_down.FindBin(nPuForWeight)) + # print(self.puWeight[0],puweight,puweight_up,puweight_down) + fbweight = self.scale1fb[0] * self._lumi + # if self._name=='tqq' or 'TTbar' in self._name: + # fbweight = fbweight/self.topPtWeight[0] # remove top pt reweighting (assuming average weight is ~ 1) + vjetsKF = 1. + wscale = [1.0, 1.0, 1.0, 1.20, 1.25, 1.25, 1.0] + ptscale = [0, 500, 600, 700, 800, 900, 1000, 3000] + ptKF = 1. + if self._name == 'wqq' or self._name == 'W': + # print self._name + for i in range(0, len(ptscale)): + if self.genVPt[0] > ptscale[i] and self.genVPt[0] < ptscale[i + 1]: ptKF = wscale[i] + vjetsKF = self.kfactor[0] * 1.35 * ptKF # ==1 for not V+jets events + elif self._name == 'zqq' or self._name == 'DY': + # print self._name + vjetsKF = self.kfactor[0] * 1.45 # ==1 for not V+jets events + # trigger weight + if not self._fillCA15: + massForTrig = min(self.AK8Puppijet0_msd[0], 300.) + ptForTrig = max(200., min(self.AK8Puppijet0_pt[0], 1000.)) + else: + massForTrig = min(self.CA15Puppijet0_msd[0], 300.) + ptForTrig = max(200., min(self.CA15Puppijet0_pt[0], 1000.)) + trigweight = self._trig_eff.GetEfficiency(self._trig_eff.FindFixBin(massForTrig, ptForTrig)) + trigweightUp = trigweight + self._trig_eff.GetEfficiencyErrorUp( + self._trig_eff.FindFixBin(massForTrig, ptForTrig)) + trigweightDown = trigweight - self._trig_eff.GetEfficiencyErrorLow( + self._trig_eff.FindFixBin(massForTrig, ptForTrig)) + if trigweight <= 0 or trigweightDown <= 0 or trigweightUp <= 0: + print 'trigweights are %f, %f, %f, setting all to 1' % (trigweight, trigweightUp, trigweightDown) + trigweight = 1 + trigweightDown = 1 + trigweightUp = 1 + + weight = puweight * fbweight * self._sf * vjetsKF * trigweight + weight_triggerUp = puweight * fbweight * self._sf * vjetsKF * trigweightUp + weight_triggerDown = puweight * fbweight * self._sf * vjetsKF * trigweightDown + weight_pu_up = puweight_up * fbweight * self._sf * vjetsKF * trigweight + weight_pu_down = puweight_down * fbweight * self._sf * vjetsKF * trigweight + + mutrigweight = 1 + mutrigweightDown = 1 + mutrigweightUp = 1 + if self.nmuLoose[0] > 0: + muPtForTrig = max(52., min(self.vmuoLoose0_pt[0], 700.)) + muEtaForTrig = min(abs(self.vmuoLoose0_eta[0]), 2.3) + mutrigweight = self._mutrig_eff.GetBinContent(self._mutrig_eff.FindBin(muPtForTrig, muEtaForTrig)) + mutrigweightUp = mutrigweight + self._mutrig_eff.GetBinError( + self._mutrig_eff.FindBin(muPtForTrig, muEtaForTrig)) + mutrigweightDown = mutrigweight - self._mutrig_eff.GetBinError( + self._mutrig_eff.FindBin(muPtForTrig, muEtaForTrig)) + if mutrigweight <= 0 or mutrigweightDown <= 0 or mutrigweightUp <= 0: + print 'mutrigweights are %f, %f, %f, setting all to 1' % ( + mutrigweight, mutrigweightUp, mutrigweightDown) + mutrigweight = 1 + mutrigweightDown = 1 + mutrigweightUp = 1 + + muidweight = 1 + muidweightDown = 1 + muidweightUp = 1 + if self.nmuLoose[0] > 0: + muPtForId = max(20., min(self.vmuoLoose0_pt[0], 100.)) + muEtaForId = min(abs(self.vmuoLoose0_eta[0]), 2.3) + muidweight = self._muid_eff.GetBinContent(self._muid_eff.FindBin(muPtForId, muEtaForId)) + muidweightUp = muidweight + self._muid_eff.GetBinError(self._muid_eff.FindBin(muPtForId, muEtaForId)) + muidweightDown = muidweight - self._muid_eff.GetBinError(self._muid_eff.FindBin(muPtForId, muEtaForId)) + if muidweight <= 0 or muidweightDown <= 0 or muidweightUp <= 0: + print 'muidweights are %f, %f, %f, setting all to 1' % (muidweight, muidweightUp, muidweightDown) + muidweight = 1 + muidweightDown = 1 + muidweightUp = 1 + + muisoweight = 1 + muisoweightDown = 1 + muisoweightUp = 1 + if self.nmuLoose[0] > 0: + muPtForIso = max(20., min(self.vmuoLoose0_pt[0], 100.)) + muEtaForIso = min(abs(self.vmuoLoose0_eta[0]), 2.3) + muisoweight = self._muiso_eff.GetBinContent(self._muiso_eff.FindBin(muPtForIso, muEtaForIso)) + muisoweightUp = muisoweight + self._muiso_eff.GetBinError( + self._muiso_eff.FindBin(muPtForIso, muEtaForIso)) + muisoweightDown = muisoweight - self._muiso_eff.GetBinError( + self._muiso_eff.FindBin(muPtForIso, muEtaForIso)) + if muisoweight <= 0 or muisoweightDown <= 0 or muisoweightUp <= 0: + print 'muisoweights are %f, %f, %f, setting all to 1' % ( + muisoweight, muisoweightUp, muisoweightDown) + muisoweight = 1 + muisoweightDown = 1 + muisoweightUp = 1 + + weight_mu = puweight * fbweight * self._sf * vjetsKF * mutrigweight * muidweight * muisoweight + weight_mutriggerUp = puweight * fbweight * self._sf * vjetsKF * mutrigweightUp * muidweight * muisoweight + weight_mutriggerDown = puweight * fbweight * self._sf * vjetsKF * mutrigweightDown * muidweight * muisoweight + weight_muidUp = puweight * fbweight * self._sf * vjetsKF * mutrigweight * muidweightUp * muisoweight + weight_muidDown = puweight * fbweight * self._sf * vjetsKF * mutrigweight * muidweightDown * muisoweight + weight_muisoUp = puweight * fbweight * self._sf * vjetsKF * mutrigweight * muidweight * muisoweightUp + weight_muisoDown = puweight * fbweight * self._sf * vjetsKF * mutrigweight * muidweight * muisoweightDown + weight_mu_pu_up = puweight_up * fbweight * self._sf * vjetsKF * mutrigweight * muidweight * muisoweight + weight_mu_pu_down = puweight_down * fbweight * self._sf * vjetsKF * mutrigweight * muidweight * muisoweight + + if self._isData: + weight = 1 + weight_triggerUp = 1 + weight_triggerDown = 1 + weight_pu_up = 1 + weight_pu_down = 1 + weight_mu = 1 + weight_mutriggerUp = 1 + weight_mutriggerDown = 1 + weight_muidUp = 1 + weight_muidDown = 1 + weight_muisoUp = 1 + weight_muisoDown = 1 + weight_mu_pu_up = 1 + weight_mu_pu_down = 1 + + if not self._fillCA15: # AK8 info + jmsd_raw = self.AK8Puppijet0_msd[0] + jpt = self.AK8Puppijet0_pt[0] + jpt_JERUp = self.AK8Puppijet0_pt_JERUp[0] + jpt_JERDown = self.AK8Puppijet0_pt_JERDown[0] + jpt_JESUp = self.AK8Puppijet0_pt_JESUp[0] + jpt_JESDown = self.AK8Puppijet0_pt_JESDown[0] + # print "AK8", jpt, jpt_JESUp, jpt_JESDown, jpt_JERUp, jpt_JERDown + jeta = self.AK8Puppijet0_eta[0] + jmsd = self.AK8Puppijet0_msd[0] * self.PUPPIweight(jpt, jeta) + jphi = self.AK8Puppijet0_phi[0] + if not self._minBranches: + jpt_sub1 = self.AK8Puppijet1_pt[0] + jpt_sub2 = self.AK8Puppijet2_pt[0] + jt21 = self.AK8Puppijet0_tau21[0] + jt32 = self.AK8Puppijet0_tau32[0] + jtN2b1sd = self.AK8Puppijet0_N2sdb1[0] + else: # CA15 info + jmsd_raw = self.CA15Puppijet0_msd[0] + jpt = self.CA15Puppijet0_pt[0] + jpt_JERUp = self.CA15Puppijet0_pt_JERUp[0] + jpt_JERDown = self.CA15Puppijet0_pt_JERDown[0] + jpt_JESUp = self.CA15Puppijet0_pt_JESUp[0] + jpt_JESDown = self.CA15Puppijet0_pt_JESDown[0] + # print "CA15", jpt, jpt_JESUp, jpt_JESDown, jpt_JERUp, jpt_JERDown + jeta = self.CA15Puppijet0_eta[0] + jmsd = self.CA15Puppijet0_msd[0] * self.PUPPIweight(jpt, jeta) + jphi = self.CA15Puppijet0_phi[0] + if not self._minBranches: + jpt_sub1 = self.CA15Puppijet1_pt[0] + jpt_sub2 = self.CA15Puppijet2_pt[0] + jt21 = self.CA15Puppijet0_tau21[0] + jt32 = self.CA15Puppijet0_tau32[0] + jtN2b1sd = self.CA15Puppijet0_N2sdb1[0] + if jmsd <= 0: jmsd = 0.01 + rh = math.log(jmsd * jmsd / jpt / jpt) + rhP = math.log(jmsd * jmsd / jpt) + jt21P = jt21 + 0.063 * rhP + + jmsd_8_raw = self.AK8Puppijet0_msd[0] + jpt_8 = self.AK8Puppijet0_pt[0] + jpt_8_JERUp = self.AK8Puppijet0_pt_JERUp[0] + jpt_8_JERDown = self.AK8Puppijet0_pt_JERDown[0] + jpt_8_JESUp = self.AK8Puppijet0_pt_JESUp[0] + jpt_8_JESDown = self.AK8Puppijet0_pt_JESDown[0] + jeta_8 = self.AK8Puppijet0_eta[0] + jmsd_8 = self.AK8Puppijet0_msd[0] * self.PUPPIweight(jpt_8, jeta_8) + jphi_8 = self.AK8Puppijet0_phi[0] + if not self._minBranches: + jpt_8_sub1 = self.AK8Puppijet1_pt[0] + jpt_8_sub2 = self.AK8Puppijet2_pt[0] + if jmsd_8 <= 0: jmsd_8 = 0.01 + + # N2DDT transformation + cur_rho_index = self._trans_h2ddt.GetXaxis().FindBin(rh) + cur_pt_index = self._trans_h2ddt.GetYaxis().FindBin(jpt) + if rh > self._trans_h2ddt.GetXaxis().GetBinUpEdge( + self._trans_h2ddt.GetXaxis().GetNbins()): cur_rho_index = self._trans_h2ddt.GetXaxis().GetNbins() + if rh < self._trans_h2ddt.GetXaxis().GetBinLowEdge(1): cur_rho_index = 1 + if jpt > self._trans_h2ddt.GetYaxis().GetBinUpEdge( + self._trans_h2ddt.GetYaxis().GetNbins()): cur_pt_index = self._trans_h2ddt.GetYaxis().GetNbins() + if jpt < self._trans_h2ddt.GetYaxis().GetBinLowEdge(1): cur_pt_index = 1 + jtN2b1sdddt = jtN2b1sd - self._trans_h2ddt.GetBinContent(cur_rho_index, cur_pt_index) + + if not self._fillCA15: # AK8 info + jdb = self.AK8Puppijet0_doublecsv[0] + if not self._minBranches: + if self.AK8Puppijet1_doublecsv[0] > 1: + jdb_sub1 = -99 + else: + jdb_sub1 = self.AK8Puppijet1_doublecsv[0] + if self.AK8Puppijet2_doublecsv[0] > 1: + jdb_sub2 = -99 + else: + jdb_sub2 = self.AK8Puppijet2_doublecsv[0] + + else: # CA15 info + jdb = self.CA15Puppijet0_doublesub[0] + if not self._minBranches: + if self.CA15Puppijet1_doublesub[0] > 1: + jdb_sub1 = -99 + else: + jdb_sub1 = self.CA15Puppijet1_doublesub[0] + if self.CA15Puppijet2_doublesub[0] > 1: + jdb_sub2 = -99 + else: + jdb_sub2 = self.CA15Puppijet2_doublesub[0] + + n_4 = self.nAK4PuppijetsPt30[0] + if not self._minBranches: + n_fwd_4 = self.nAK4PuppijetsfwdPt30[0] + n_dR0p8_4 = self.nAK4PuppijetsPt30dR08_0[0] + # due to bug, don't use jet counting JER/JES Up/Down for now + # n_dR0p8_4_JERUp = self.nAK4PuppijetsPt30dR08jerUp_0[0] + # n_dR0p8_4_JERDown = self.nAK4PuppijetsPt30dR08jerDown_0[0] + # n_dR0p8_4_JESUp = self.nAK4PuppijetsPt30dR08jesUp_0[0] + # n_dR0p8_4_JESDown = self.nAK4PuppijetsPt30dR08jesDown_0[0] + n_dR0p8_4_JERUp = n_dR0p8_4 + n_dR0p8_4_JERDown = n_dR0p8_4 + n_dR0p8_4_JESUp = n_dR0p8_4 + n_dR0p8_4_JESDown = n_dR0p8_4 + + n_MdR0p8_4 = self.nAK4PuppijetsMPt50dR08_0[0] + if not self._minBranches: + n_LdR0p8_4 = self.nAK4PuppijetsLPt50dR08_0[0] + n_TdR0p8_4 = self.nAK4PuppijetsTPt50dR08_0[0] + n_LPt100dR0p8_4 = self.nAK4PuppijetsLPt100dR08_0[0] + n_MPt100dR0p8_4 = self.nAK4PuppijetsMPt100dR08_0[0] + n_TPt100dR0p8_4 = self.nAK4PuppijetsTPt100dR08_0[0] + n_LPt150dR0p8_4 = self.nAK4PuppijetsLPt150dR08_0[0] + n_MPt150dR0p8_4 = self.nAK4PuppijetsMPt150dR08_0[0] + n_TPt150dR0p8_4 = self.nAK4PuppijetsTPt150dR08_0[0] + + met = self.pfmet[0] # puppet[0] + metphi = self.pfmetphi[0] # puppetphi[0] + met_x = met * ROOT.TMath.Cos(metphi) + met_y = met * ROOT.TMath.Sin(metphi) + met_JESUp = ROOT.TMath.Sqrt( + (met_x + self.MetXCorrjesUp[0]) * (met_x + self.MetXCorrjesUp[0]) + (met_y + self.MetYCorrjesUp[0]) * ( + met_y + self.MetYCorrjesUp[0])) + met_JESDown = ROOT.TMath.Sqrt((met_x + self.MetXCorrjesDown[0]) * (met_x + self.MetXCorrjesDown[0]) + ( + met_y + self.MetYCorrjesDown[0]) * (met_y + self.MetYCorrjesDown[0])) + met_JERUp = ROOT.TMath.Sqrt( + (met_x + self.MetXCorrjerUp[0]) * (met_x + self.MetXCorrjerUp[0]) + (met_y + self.MetYCorrjerUp[0]) * ( + met_y + self.MetYCorrjerUp[0])) + met_JERDown = ROOT.TMath.Sqrt((met_x + self.MetXCorrjerDown[0]) * (met_x + self.MetXCorrjerDown[0]) + ( + met_y + self.MetYCorrjerDown[0]) * (met_y + self.MetYCorrjerDown[0])) + + ratioCA15_04 = self.AK8Puppijet0_ratioCA15_04[0] + + ntau = self.ntau[0] + nmuLoose = self.nmuLoose[0] + neleLoose = self.neleLoose[0] + nphoLoose = self.nphoLoose[0] + if not self._fillCA15: + isTightVJet = self.AK8Puppijet0_isTightVJet[0] + else: + isTightVJet = self.CA15Puppijet0_isTightVJet[0] + + # muon info + vmuoLoose0_pt = self.vmuoLoose0_pt[0] + vmuoLoose0_eta = self.vmuoLoose0_eta[0] + vmuoLoose0_phi = self.vmuoLoose0_phi[0] + + self.h_npv.Fill(self.npv[0], weight) + + # gen-matching for scale/smear systematic + dphi = 9999 + dpt = 9999 + dmass = 9999 + if (not self._isData): + genVPt = self.genVPt[0] + genVEta = self.genVEta[0] + genVPhi = self.genVPhi[0] + genVMass = self.genVMass[0] + if genVPt > 0 and genVMass > 0: + dphi = math.fabs(delta_phi(genVPhi, jphi)) + dpt = math.fabs(genVPt - jpt) / genVPt + dmass = math.fabs(genVMass - jmsd) / genVMass + + # Single Muon Control Regions + + if jpt > PTCUTMUCR and jmsd > MASSCUT and neleLoose == 0 and ntau == 0 and isTightVJet: + self.h_nmuLoose.Fill(nmuLoose) + + if jpt > PTCUTMUCR and jmsd > MASSCUT and nmuLoose >= 1 and neleLoose == 0 and ntau == 0 and vmuoLoose0_pt > MUONPTCUT and abs( + vmuoLoose0_eta) < 2.1 and isTightVJet and met > 50: + # and abs(vmuoLoose0_phi - jphi) > 2. * ROOT.TMath.Pi() / 3. : + ht_ = 0. + if (abs(self.AK4Puppijet0_eta[0]) < 2.4 and self.AK4Puppijet0_pt[0] > 30): ht_ = ht_ + \ + self.AK4Puppijet0_pt[ + 0] + if (abs(self.AK4Puppijet1_eta[0]) < 2.4 and self.AK4Puppijet1_pt[0] > 30): ht_ = ht_ + \ + self.AK4Puppijet1_pt[ + 0] + if (abs(self.AK4Puppijet2_eta[0]) < 2.4 and self.AK4Puppijet2_pt[0] > 30): ht_ = ht_ + \ + self.AK4Puppijet2_pt[ + 0] + if (abs(self.AK4Puppijet3_eta[0]) < 2.4 and self.AK4Puppijet3_pt[0] > 30): ht_ = ht_ + \ + self.AK4Puppijet3_pt[ + 0] + self.h_ht.Fill(ht_, weight) + if jt21P < T21DDTCUT: + self.h_msd_ak8_muCR1.Fill(jmsd, weight_mu) + if jdb > self.DBTAGCUT: + self.h_msd_ak8_muCR2.Fill(jmsd, weight_mu) + if jt21P < 0.4: + self.h_msd_ak8_muCR3.Fill(jmsd, weight_mu) + + self.h_met_muCR4.Fill(met, weight_mu) + self.h_dPhi_muCR4.Fill(abs(vmuoLoose0_phi - jphi), weight_mu) + self.h_N2ddt_muCR4.Fill(jtN2b1sdddt, weight_mu) + self.h_N2_muCR4.Fill(jtN2b1sd, weight_mu) + self.h_t21ddt_ak8_muCR4.Fill(jt21P, weight_mu) + self.h_t21ddt_ak8_muCR4.Fill(jt21P, weight_mu) + self.h_dbtag_ak8_muCR4.Fill(jdb, weight_mu) + self.h_msd_ak8_muCR4.Fill(jmsd, weight_mu) + self.h_pt_ak8_muCR4.Fill(jpt, weight_mu) + self.h_eta_ak8_muCR4.Fill(jeta, weight_mu) + self.h_pt_mu_muCR4.Fill(vmuoLoose0_pt, weight_mu) + self.h_eta_mu_muCR4.Fill(vmuoLoose0_eta, weight_mu) + if jdb > self.DBTAGCUT: + self.h_msd_ak8_muCR4_pass.Fill(jmsd, weight_mu) + self.h_msd_v_pt_ak8_muCR4_pass.Fill(jmsd, jpt, weight_mu) + elif jdb > self.DBTAGCUTMIN: + self.h_msd_ak8_muCR4_fail.Fill(jmsd, weight_mu) + self.h_msd_v_pt_ak8_muCR4_fail.Fill(jmsd, jpt, weight_mu) + + if jdb > 0.7 and jt21P < 0.4: + self.h_msd_ak8_muCR5.Fill(jmsd, weight_mu) + if jdb > 0.7 and jt21P < T21DDTCUT: + self.h_msd_ak8_muCR6.Fill(jmsd, weight_mu) + + if jtN2b1sdddt < 0: + self.h_dbtag_ak8_muCR4_N2.Fill(jdb, weight_mu) + self.h_msd_ak8_muCR4_N2.Fill(jmsd, weight_mu) + self.h_pt_ak8_muCR4_N2.Fill(jpt, weight_mu) + self.h_eta_ak8_muCR4_N2.Fill(jeta, weight_mu) + if jdb > self.DBTAGCUT: + self.h_msd_ak8_muCR4_N2_pass.Fill(jmsd, weight_mu) + self.h_msd_v_pt_ak8_muCR4_N2_pass.Fill(jmsd, jpt, weight_mu) + self.h_msd_ak8_muCR4_N2_pass_mutriggerUp.Fill(jmsd, weight_mutriggerUp) + self.h_msd_ak8_muCR4_N2_pass_mutriggerDown.Fill(jmsd, weight_mutriggerDown) + self.h_msd_ak8_muCR4_N2_pass_muidUp.Fill(jmsd, weight_muidUp) + self.h_msd_ak8_muCR4_N2_pass_muidDown.Fill(jmsd, weight_muidDown) + self.h_msd_ak8_muCR4_N2_pass_muisoUp.Fill(jmsd, weight_muisoUp) + self.h_msd_ak8_muCR4_N2_pass_muisoDown.Fill(jmsd, weight_muisoDown) + self.h_msd_ak8_muCR4_N2_pass_PuUp.Fill(jmsd, weight_mu_pu_up) + self.h_msd_ak8_muCR4_N2_pass_PuDown.Fill(jmsd, weight_mu_pu_down) + elif jdb > self.DBTAGCUTMIN: + self.h_msd_ak8_muCR4_N2_fail.Fill(jmsd, weight_mu) + self.h_msd_v_pt_ak8_muCR4_N2_fail.Fill(jmsd, jpt, weight_mu) + self.h_msd_ak8_muCR4_N2_fail_mutriggerUp.Fill(jmsd, weight_mutriggerUp) + self.h_msd_ak8_muCR4_N2_fail_mutriggerDown.Fill(jmsd, weight_mutriggerDown) + self.h_msd_ak8_muCR4_N2_fail_muidUp.Fill(jmsd, weight_muidUp) + self.h_msd_ak8_muCR4_N2_fail_muidDown.Fill(jmsd, weight_muidDown) + self.h_msd_ak8_muCR4_N2_fail_muisoUp.Fill(jmsd, weight_muisoUp) + self.h_msd_ak8_muCR4_N2_fail_muisoDown.Fill(jmsd, weight_muisoDown) + self.h_msd_ak8_muCR4_N2_fail_PuUp.Fill(jmsd, weight_mu_pu_up) + self.h_msd_ak8_muCR4_N2_fail_PuDown.Fill(jmsd, weight_mu_pu_down) + + for syst in ['JESUp', 'JESDown', 'JERUp', 'JERDown']: + if eval( + 'jpt_%s' % syst) > PTCUTMUCR and jmsd > MASSCUT and nmuLoose >= 1 and neleLoose == 0 and ntau == 0 and vmuoLoose0_pt > MUONPTCUT and abs( + vmuoLoose0_eta) < 2.1 and isTightVJet and jtN2b1sdddt < 0 : + if jdb > self.DBTAGCUT: + (getattr(self, 'h_msd_ak8_muCR4_N2_pass_%s' % syst)).Fill(jmsd, weight) + elif jdb > self.DBTAGCUTMIN: + (getattr(self, 'h_msd_ak8_muCR4_N2_fail_%s' % syst)).Fill(jmsd, weight) + + if not self._minBranches: + jmsd_sub1 = self.AK8Puppijet1_msd[0] + jmsd_sub2 = self.AK8Puppijet2_msd[0] + n_MPt100dR0p8_4_sub1 = self.nAK4PuppijetsMPt100dR08_1[0] + n_MPt100dR0p8_4_sub2 = self.nAK4PuppijetsMPt100dR08_2[0] + + jt21_sub1 = self.AK8Puppijet1_tau21[0] + rhP_sub1 = -999 + jt21P_sub1 = -999 + if jpt_sub1 > 0 and jmsd_sub1 > 0: + rhP_sub1 = math.log(jmsd_sub1 * jmsd_sub1 / jpt_sub1) + jt21P_sub1 = jt21_sub1 + 0.063 * rhP_sub1 + + jt21_sub2 = self.AK8Puppijet2_tau21[0] + rhP_sub2 = -999 + jt21P_sub2 = -999 + if jpt_sub2 > 0 and jmsd_sub2 > 0: + rhP_sub2 = math.log(jmsd_sub2 * jmsd_sub2 / jpt_sub2) + jt21P_sub2 = jt21_sub2 + 0.063 * rhP_sub2 + + isTightVJet_sub1 = self.AK8Puppijet1_isTightVJet + isTightVJet_sub2 = self.AK8Puppijet2_isTightVJet + + bb_idx = [[jmsd, jpt, jdb, n_MPt100dR0p8_4, jt21P, isTightVJet], + [jmsd_sub1, jpt_sub1, jdb_sub1, n_MPt100dR0p8_4_sub1, jt21P_sub1, isTightVJet_sub1], + [jmsd_sub2, jpt_sub2, jdb_sub2, n_MPt100dR0p8_4_sub2, jt21P_sub2, isTightVJet_sub2] + ] + + a = 0 + for i in sorted(bb_idx, key=lambda bbtag: bbtag[2], reverse=True): + if a > 0: continue + a = a + 1 + if i[1] > PTCUTMUCR and i[ + 0] > MASSCUT and nmuLoose >= 1 and neleLoose == 0 and ntau == 0 and vmuoLoose0_pt > MUONPTCUT and abs( + vmuoLoose0_eta) < 2.1 and i[4] < T21DDTCUT and i[5]: + if i[2] > self.DBTAGCUT: + self.h_msd_ak8_bbleading_muCR4_pass.Fill(i[0], weight_mu) + self.h_msd_v_pt_ak8_bbleading_muCR4_pass.Fill(i[0], i[1], weight_mu) + else: + self.h_msd_ak8_bbleading_muCR4_fail.Fill(i[0], weight_mu) + self.h_msd_v_pt_ak8_bbleading_muCR4_fail.Fill(i[0], i[1], weight_mu) + + if jpt > PTCUT: + cut[3] = cut[3] + 1 + if jpt > PTCUT and jmsd > MASSCUT: + cut[4] = cut[4] + 1 + if jpt > PTCUT and jmsd > MASSCUT and isTightVJet: + cut[5] = cut[5] + 1 + if jpt > PTCUT and jmsd > MASSCUT and isTightVJet and neleLoose == 0 : #and nphoLoose == 0: + cut[0] = cut[0] + 1 + if jpt > PTCUT and jmsd > MASSCUT and isTightVJet and neleLoose == 0 and ntau == 0 :# and nphoLoose == 0: + cut[1] = cut[1] + 1 + if jpt > PTCUT and jmsd > MASSCUT and isTightVJet and neleLoose == 0 and nmuLoose >= 1 and ntau == 0: # and nphoLoose == 0: + cut[2] = cut[2] + 1 + if jtN2b1sdddt < 0 and jpt > PTCUT and jmsd > MASSCUT and isTightVJet and neleLoose == 0 and nmuLoose >= 1 and ntau == 0 : #and nphoLoose == 0: + cut[8] = cut[8] + 1 + + if jpt > PTCUT: + self.h_msd_ak8_inc.Fill(jmsd, weight) + if jt21P < T21DDTCUT: + self.h_msd_ak8_t21ddtCut_inc.Fill(jmsd, weight) + + # Lepton and photon vet + if neleLoose != 0 or ntau != 0: continue # or nphoLoose != 0: continue + + if not self._minBranches: + a = 0 + for i in sorted(bb_idx, key=lambda bbtag: bbtag[2], reverse=True): + if a > 0: continue + a = a + 1 + if i[2] > self.DBTAGCUT and i[0] > MASSCUT and i[1] > PTCUT: + self.h_msd_bbleading.Fill(i[0], weight) + # print sorted(bb_idx, key=lambda bbtag: bbtag[2],reverse=True) + self.h_pt_bbleading.Fill(i[1], weight) + # print(i[0],i[1],i[2]) + self.h_bb_bbleading.Fill(i[2], weight) + + if jpt > PTCUT and jmsd > MASSCUT: + self.h_rho_ak8.Fill(rh, weight) + + if jpt > PTCUT and jmsd > MASSCUT and rh < -2.1 and rh > -6.: + self.h_pt_ak8.Fill(jpt, weight) + self.h_eta_ak8.Fill(jeta, weight) + self.h_pt_ak8_sub1.Fill(jpt_sub1, weight) + self.h_pt_ak8_sub2.Fill(jpt_sub2, weight) + self.h_msd_ak8.Fill(jmsd, weight) + self.h_rho_ak8.Fill(rh, weight) + self.h_msd_ak8_raw.Fill(jmsd_raw, weight) + self.h_dbtag_ak8.Fill(jdb, weight) + self.h_dbtag_ak8_sub1.Fill(jdb_sub1, weight) + self.h_dbtag_ak8_sub2.Fill(jdb_sub2, weight) + self.h_t21_ak8.Fill(jt21, weight) + self.h_t32_ak8.Fill(jt32, weight) + self.h_t21ddt_ak8.Fill(jt21P, weight) + self.h_rhop_v_t21_ak8.Fill(rhP, jt21, weight) + self.h_n2b1sd_ak8.Fill(jtN2b1sd, weight) + self.h_n2b1sdddt_ak8.Fill(jtN2b1sdddt, weight) + + self.h_n_ak4.Fill(n_4, weight) + self.h_n_ak4_dR0p8.Fill(n_dR0p8_4, weight) + self.h_n_ak4fwd.Fill(n_fwd_4, weight) + self.h_n_ak4L.Fill(n_LdR0p8_4, weight) + self.h_n_ak4L100.Fill(n_LPt100dR0p8_4, weight) + self.h_n_ak4M.Fill(n_MdR0p8_4, weight) + self.h_n_ak4M100.Fill(n_MPt100dR0p8_4, weight) + self.h_n_ak4T.Fill(n_TdR0p8_4, weight) + self.h_n_ak4T100.Fill(n_TPt100dR0p8_4, weight) + self.h_n_ak4L150.Fill(n_LPt150dR0p8_4, weight) + self.h_n_ak4M150.Fill(n_MPt150dR0p8_4, weight) + self.h_n_ak4T150.Fill(n_TPt150dR0p8_4, weight) + self.h_isolationCA15.Fill(ratioCA15_04, weight) + self.h_met.Fill(met, weight) + + if jpt > PTCUT and jt21P < T21DDTCUT and jmsd > MASSCUT: + self.h_msd_ak8_t21ddtCut.Fill(jmsd, weight) + self.h_t32_ak8_t21ddtCut.Fill(jt32, weight) + + if jpt > PTCUT and jtN2b1sdddt < 0 and jmsd > MASSCUT: + self.h_msd_ak8_N2Cut.Fill(jmsd, weight) + + if jpt > PTCUT and jmsd > MASSCUT and met < METCUT and isTightVJet: + cut[6] = cut[6] + 1 + # if jpt > PTCUT and jmsd > MASSCUT and met < METCUT and n_dR0p8_4 < NJETCUT and isTightVJet: + # cut[7] = cut[7] + 1 + if jpt > PTCUT and jmsd > MASSCUT and met < METCUT and n_dR0p8_4 < NJETCUT and isTightVJet and jdb > self.DBTAGCUT and rh < -2.1 and rh > -6.: + if (not self._minBranches): self.h_n2b1sdddt_ak8_aftercut.Fill(jtN2b1sdddt, weight) + #if jpt > PTCUT and jmsd > MASSCUT and met < METCUT and n_dR0p8_4 < NJETCUT and jtN2b1sdddt < 0 and isTightVJet: + # cut[8] = cut[8] + 1 + # if rh < -2.1 and rh > -6.: + # cut[7] = cut[7] + 1 + + if not self._minBranches: + + if jpt > PTCUT and jdb > self.DBTAGCUT and jmsd > MASSCUT: + self.h_msd_ak8_dbtagCut.Fill(jmsd, weight) + self.h_pt_ak8_dbtagCut.Fill(jpt, weight) + + ##### CA15 info + if not self._fillCA15: continue + + jmsd_15 = self.CA15Puppijet0_msd[0] + jpt_15 = self.CA15Puppijet0_pt[0] + if jmsd_15 <= 0: jmsd_15 = 0.01 + rhP_15 = math.log(jmsd_15 * jmsd_15 / jpt_15) + jt21_15 = self.CA15Puppijet0_tau21[0] + jt21P_15 = jt21_15 + 0.075 * rhP_15 + + if jpt_15 > PTCUT: + self.h_pt_ca15.Fill(jpt_15, weight) + self.h_msd_ca15.Fill(jmsd_15, weight) + self.h_t21_ca15.Fill(jt21_15, weight) + self.h_t21ddt_ca15.Fill(jt21P_15, weight) + self.h_rhop_v_t21_ca15.Fill(rhP_15, jt21_15, weight) + + if jpt_15 > PTCUT and jt21P_15 < 0.4: + self.h_msd_ca15_t21ddtCut.Fill(jmsd_15, weight) + ##### + print "\n" + print "finish" + if not self._minBranches and cut[3] > 0.: + self.h_Cuts.SetBinContent(4, float(cut[0] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(5, float(cut[1] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(6, float(cut[2] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(1, float(cut[3] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(2, float(cut[4] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(3, float(cut[5] / cut[3] * 100.)) + # self.h_Cuts.SetBinContent(7, float(cut[6] / cut[3] * 100.)) + # self.h_Cuts.SetBinContent(7, float(cut[7] / cut[3] * 100.)) + # self.h_Cuts.SetBinContent(9,float(cut[8]/nent*100.)) + #self.h_Cuts.SetBinContent(8, float(cut[7] / cut[3] * 100.)) + self.h_Cuts.SetBinContent(7, float(cut[8]) / cut[3] * 100.) + print(cut[0] / nent * 100., cut[7], cut[8], cut[9]) + a_Cuts = self.h_Cuts.GetXaxis() + a_Cuts.SetBinLabel(4, "ele veto") + a_Cuts.SetBinLabel(5, "#tau veto") + a_Cuts.SetBinLabel(6, "muon loose") + a_Cuts.SetBinLabel(1, "p_{T}>250 GeV") + a_Cuts.SetBinLabel(2, "m_{SD}>40 GeV") + a_Cuts.SetBinLabel(3, "tight ID") + # a_Cuts.SetBinLabel(6, "MET<140") + # a_Cuts.SetBinLabel(7, "njet<5") + a_Cuts.SetBinLabel(7, "N2^{DDT}<0") + #a_Cuts.SetBinLabel(8, "-6<#rho<-2.1") + + self.h_rhop_v_t21_ak8_Px = self.h_rhop_v_t21_ak8.ProfileX() + self.h_rhop_v_t21_ca15_Px = self.h_rhop_v_t21_ca15.ProfileX() + self.h_rhop_v_t21_ak8_Px.SetTitle("; rho^{DDT}; <#tau_{21}>") + self.h_rhop_v_t21_ca15_Px.SetTitle("; rho^{DDT}; <#tau_{21}>") + + def PUPPIweight(self, puppipt=30., puppieta=0.): + + genCorr = 1. + recoCorr = 1. + totalWeight = 1. + + genCorr = self.corrGEN.Eval(puppipt) + if (abs(puppieta) < 1.3): + recoCorr = self.corrRECO_cen.Eval(puppipt) + else: + recoCorr = self.corrRECO_for.Eval(puppipt) + totalWeight = genCorr * recoCorr + return totalWeight + +########################################################################################## diff --git a/fitting/PbbJet/Hbb_create.py b/fitting/PbbJet/Hbb_create.py index 5e81a4e..b559762 100644 --- a/fitting/PbbJet/Hbb_create.py +++ b/fitting/PbbJet/Hbb_create.py @@ -18,7 +18,7 @@ def main(options, args): muonCR = options.muonCR dbtagmin = options.dbtagmin - fileName = 'hist_1DZbb_pt_scalesmear.root' + fileName = 'hist_1DZbb_pt_scalesmear_looserWZ.root' if options.bb: fileName = 'hist_1DZbb_sortByBB.root' elif muonCR: @@ -27,8 +27,11 @@ def main(options, args): outfile = ROOT.TFile(options.odir + "/" + fileName, "recreate") tfiles = { - 'hqq125': [idir + '/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted_corrected.root'],#GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted.root'], - # idir+'/GluGluHToBB_M125_13TeV_powheg_pythia8_ext_1000pb_weighted.root'], + 'hqq125': #[idir + '/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted_corrected.root'], + #[idir + '/GluGluHToBB_M125_13TeV_powheg_pythia8_all_1000pb_weighted.root'], + #[idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_2Jet_1000pb_weighted.root'], + [idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_CKKW_1000pb_weighted.root'], + #[idirData + '/GluGluHToBB_M125_13TeV_powheg_pythia8_YR4_1000pb_weighted.root'], # 'VBFHbb': [idir+'/VBFHToBB_M125_13TeV_amcatnlo_pythia8_1000pb_weighted.root'], 'vbfhqq125': [idir + '/VBFHToBB_M_125_13TeV_powheg_pythia8_weightfix_all_1000pb_weighted.root'], 'zhqq125': [idir + '/ZH_HToBB_ZToQQ_M125_13TeV_powheg_pythia8_1000pb_weighted.root', diff --git a/fitting/PbbJet/README.md b/fitting/PbbJet/README.md index e4e2758..01272fb 100644 --- a/fitting/PbbJet/README.md +++ b/fitting/PbbJet/README.md @@ -1,8 +1,41 @@ -Instructions to run create cards and run limit +Instructions to run create cards and run limits, etc. + +Create templates: ``` -$ python Hbb_create.py -i /eos/uscms/store/user/jduarte1/zprimebits-v11.061/sklim-v0-Nov29/ --lumi 30 -$ python buildRhalphabetHbb.py --pseudo -$ python makeCardsHbb.py -$ cd cards; combineCards.py cat1=card_rhalphabet_cat1.txt cat2=card_rhalphabet_cat2.txt cat3=card_rhalphabet_cat3.txt cat4=card_rhalphabet_cat4.txt cat5=card_rhalphabet_cat5.txt > card_rhalphabet.txt; cd - -$ combine -M Asymptotic -v 2 cards/card_rhalphabet.txt +# create all templates, with passing region double b-tag > 0.9 +export SKLIMDIR=/eos/uscms/store/user/lpchbb/zprimebits-v12.04/cvernier +python Hbb_create.py -i root://cmseos.fnal.gov/$SKLIMDIR -o output-miniaod-pfmet140-hptckkw-hqq125ptShape --lumi 35.9 + +# create templates for muon CR +python Hbb_create.py -i root://cmseos.fnal.gov/$SKLIMDIR -o output-miniaod-pfmet140-hptckkw-hqq125ptShape --lumi 35.9 -m + +# create looser templates, with passing region double b-tag > 0.8 +# (have to change hard-coded value DBTAGCUT = 0.8 in sampleContainer.py) +python Hbb_create.py -i root://cmseos.fnal.gov/$SKLIMDIR -o output-miniaod-pfmet140-hptckkw-hqq125ptShape-looser --lumi 35.9 --skip-qcd --skip-data +cp output-miniaod-pfmet140-hptckkw-hqq125ptShape-looser/hist_1DZbb_pt_scalesmear.root output-miniaod-pfmet140-hptckkw-hqq125ptShape/hist_1DZbb_pt_scalesmear_looserWZ.root ``` + +Make workspaces and datacards: +``` +# make workspaces +python buildRhalphabetHbb.py -i output-miniaod-pfmet140-hptckkw-hqq125ptShape/hist_1DZbb_pt_scalesmear.root --ifile-loose output-miniaod-pfmet140-hptckkw-hqq125ptShape/hist_1DZbb_pt_scalesmear_looserWZ.root -o output-miniaod-pfmet140-hqq125ptShape/ --remove-unmatched --prefit --addHptShape + +# make datacards +python makeCardsHbb.py -i output-miniaod-pfmet140-hqq125ptShape/hist_1DZbb_pt_scalesmear.root --ifile-loose output-miniaod-pfmet140-hqq125ptShape/hist_1DZbb_pt_scalesmear_looserWZ.root -o output-miniaod-pfmet140-hqq125ptShape/ --remove-unmatched --no-mcstat-shape + +# make muonCR datacards +python writeMuonCRDatacard.py -i output-miniaod-pfmet140-hqq125ptShape/ -o output-miniaod-pfmet140-hqq125ptShape/ +cd output-miniaod-pfmet140-hqq125ptShape/ +``` + +Run combine commands: +``` +# combine cards +combineCards.py cat1=card_rhalphabet_cat1.txt cat2=card_rhalphabet_cat2.txt cat3=card_rhalphabet_cat3.txt cat4=card_rhalphabet_cat4.txt cat5=card_rhalphabet_cat5.txt cat6=card_rhalphabet_cat6.txt muonCR=datacard_muonCR.txt > card_rhalphabet_muonCR.txt + +# convert to binary file +text2workspace.py -P HiggsAnalysis.CombinedLimit.PhysicsModel:multiSignalModel -m 125 --PO verbose --PO 'map=.*/*hqq125:r[1,0,20]' --PO 'map=.*/zqq:r_z[1,0,20]' card_rhalphabet_muonCR.txt -o card_rhalphabet_muonCR_floatZ.root +``` + +Follow other combine instructions: +https://github.com/DAZSLE/ZPrimePlusJet/blob/Hbb_Diff-pT/fitting/PbbJet/README.md diff --git a/fitting/PbbJet/buildRhalphabetHbb.py b/fitting/PbbJet/buildRhalphabetHbb.py index ecc8f8f..3f856f1 100644 --- a/fitting/PbbJet/buildRhalphabetHbb.py +++ b/fitting/PbbJet/buildRhalphabetHbb.py @@ -47,6 +47,8 @@ def main(options, args): rhalphabuilder = RhalphabetBuilder(pass_hists, fail_hists, f, options.odir, nr=options.NR, np=options.NP, mass_nbins=MASS_BINS, mass_lo=MASS_LO, mass_hi=MASS_HI, blind_lo=BLIND_LO, blind_hi=BLIND_HI, rho_lo=RHO_LO, rho_hi=RHO_HI, blind=options.blind, mass_fit=options.massfit, freeze_poly=options.freeze, remove_unmatched=options.removeUnmatched, input_file_loose=fLoose) rhalphabuilder.run() + if options.addHptShape: + rhalphabuilder.addHptShape() if options.prefit: rhalphabuilder.prefit() elif options.loadfit is not None: @@ -78,6 +80,7 @@ def main(options, args): parser.add_option('-r', dest='r', default=0, type='float', help='signal strength for MC pseudodataset') parser.add_option('--remove-unmatched', action='store_true', dest='removeUnmatched', default =False,help='remove unmatched', metavar='removeUnmatched') parser.add_option('--prefit', action='store_true', dest='prefit', default =False,help='do prefit', metavar='prefit') + parser.add_option('--addHptShape',action='store_true',dest='addHptShape',default =False,help='add H pt shape unc', metavar='addHptShape') parser.add_option('--loadfit', dest='loadfit', default=None, help='load qcd polynomial parameters from alternative rhalphabase.root',metavar='loadfit') (options, args) = parser.parse_args() diff --git a/fitting/PbbJet/cccPlot.py b/fitting/PbbJet/cccPlot.py index ba3cf59..30a16d5 100644 --- a/fitting/PbbJet/cccPlot.py +++ b/fitting/PbbJet/cccPlot.py @@ -1,15 +1,29 @@ import ROOT as rt from RootIterator import RootIterator +from optparse import OptionParser + + +poiMap = {'r':"#mu_{H}", + 'r_z':"#mu_{Z}"} + catDict = {} -catDict['muonCR'] = '#splitline{Combined}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat1'] = '#splitline{[450, 500 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat2'] = '#splitline{[500, 550 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat3'] = '#splitline{[550, 600 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat4'] = '#splitline{[600, 675 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat5'] = '#splitline{[675, 800 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -catDict['cat6'] = '#splitline{[800, 1000 GeV]}{ #scale[0.8]{#mu=%.2f^{-%.2f}_{+%.2f}}}' -def cccPlot(poi = "r", rMax=10, filename="ccc.pdf"): +catDict['muonCR','r'] = '#splitline{Combined}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat1','r'] = '#splitline{[450, 500] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat2','r'] = '#splitline{[500, 550] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat3','r'] = '#splitline{[550, 600] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat4','r'] = '#splitline{[600, 675] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat5','r'] = '#splitline{[675, 800] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' +catDict['cat6','r'] = '#splitline{[800, 1000] GeV}{ #scale[0.8]{#mu_{H} = %.1f_{#minus%.1f}^{+%.1f}}}' + +catDict['muonCR','r_z'] = '#splitline{Combined}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat1','r_z'] = '#splitline{[450, 500] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat2','r_z'] = '#splitline{[500, 550] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat3','r_z'] = '#splitline{[550, 600] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat4','r_z'] = '#splitline{[600, 675] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat5','r_z'] = '#splitline{[675, 800] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +catDict['cat6','r_z'] = '#splitline{[800, 1000] GeV}{ #scale[0.8]{#mu_{Z} = %.2f_{#minus%.2f}^{+%.2f}}}' +def cccPlot(poi = "r", rMin =-10, rMax=15, filename="ccc_r.pdf"): c1 = rt.TCanvas("c1") c1.SetLeftMargin(0.4) c1.SetBottomMargin(0.12) @@ -33,7 +47,8 @@ def cccPlot(poi = "r", rMax=10, filename="ccc.pdf"): for a in RootIterator(fit_alternate.floatParsFinal()): if prefix in a.GetName(): nChann+=1 - frame = rt.TH2F("frame",";best fit #sigma/#sigma_{SM};",1,-10,15,nChann,0,nChann) + + frame = rt.TH2F("frame",";%s;"%poiMap[poi],1,rMin,rMax,nChann,0,nChann) iChann = 0 points = rt.TGraphAsymmErrors(nChann) @@ -42,14 +57,19 @@ def cccPlot(poi = "r", rMax=10, filename="ccc.pdf"): if (rt.TString(a.GetName()).Index(prefix) == 0): ri = a channel = a.GetName() - channel = channel.replace(prefix,"") - points.SetPoint(iChann, ri.getVal(), iChann+0.5) - points.SetPointError(iChann, -ri.getAsymErrorLo(), ri.getAsymErrorHi(), 0, 0) + channel = channel.replace(prefix,"") + if channel=='muonCR': + # put at some dummy value + points.SetPoint(iChann, 100, iChann+0.5) + points.SetPointError(iChann, -1, 1, 0, 0) + else: + points.SetPoint(iChann, ri.getVal(), iChann+0.5) + points.SetPointError(iChann, -ri.getAsymErrorLo(), ri.getAsymErrorHi(), 0, 0) iChann+=1 if channel=='muonCR': - frame.GetYaxis().SetBinLabel(iChann, catDict[channel]%(rFit.getVal(),-rFit.getAsymErrorLo(), rFit.getAsymErrorHi())) + frame.GetYaxis().SetBinLabel(iChann, (catDict[channel,options.poi]%(rFit.getVal(),-rFit.getAsymErrorLo(), rFit.getAsymErrorHi())).replace('-','#minus')) else: - frame.GetYaxis().SetBinLabel(iChann, catDict[channel]%(ri.getVal(),-ri.getAsymErrorLo(), ri.getAsymErrorHi())) + frame.GetYaxis().SetBinLabel(iChann, (catDict[channel,options.poi]%(ri.getVal(),-ri.getAsymErrorLo(), ri.getAsymErrorHi())).replace('-','#minus')) points.SetLineColor(rt.kRed) points.SetLineWidth(3) points.SetMarkerStyle(21) @@ -75,7 +95,7 @@ def cccPlot(poi = "r", rMax=10, filename="ccc.pdf"): l.SetTextFont(62) l.DrawLatex(0.41,0.85,"CMS") l.SetTextFont(52) - l.DrawLatex(0.41,0.8,"Internal") + l.DrawLatex(0.41,0.8,"Preliminary") tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%(35.9)) tag1.SetNDC() tag1.SetTextFont(42) @@ -87,7 +107,15 @@ def cccPlot(poi = "r", rMax=10, filename="ccc.pdf"): c1.Print(filename.replace('.pdf','.C')) if __name__ == '__main__': + parser = OptionParser() + parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') + parser.add_option('--rMin',dest='rMin', default=-10 ,type='float',help='minimum of r (signal strength) in profile likelihood plot') + parser.add_option('--rMax',dest='rMax', default=15,type='float',help='maximum of r (signal strength) in profile likelihood plot') + + parser.add_option('-P','--poi' ,action='store',type='string',dest='poi' ,default='r', help='poi name') + + (options, args) = parser.parse_args() rt.gROOT.SetBatch() - f = rt.TFile.Open('cards_2017_03_29_fixtrig_hptcorr/higgsCombineTest.ChannelCompatibilityCheck.mH125.root') - cccPlot() + f = rt.TFile.Open('output-miniaod-pfmet140-hptckkw-hqq125ptShape/higgsCombine%s.ChannelCompatibilityCheck.mH125.root'%options.poi) + cccPlot(options.poi, options.rMin, options.rMax, "ccc_"+options.poi+".pdf") diff --git a/fitting/PbbJet/datacard.tpl b/fitting/PbbJet/datacard.tpl index 1fd328e..eb0a5fa 100644 --- a/fitting/PbbJet/datacard.tpl +++ b/fitting/PbbJet/datacard.tpl @@ -18,7 +18,8 @@ rate -1 -1 -1 -1 -1 -1 -1 1.0 -1 -1 -1 -1 -1 -1 -1 -1 1.0 -1 ---------------------------------------------------------------------------------------------------------------------------------- #lumi_13TeV lnN 1.025 1.025 1.025 1.025 1.025 1.025 1.025 - 1.025 1.025 1.025 1.025 1.025 1.025 1.025 1.025 - 1.025 lumi lnN 1.025 1.025 1.025 1.025 1.025 1.025 1.025 - - 1.025 1.025 1.025 1.025 1.025 1.025 1.025 - - -hqq125pt lnN - - 1.3 - - - - - - - - 1.3 - - - - - - +hqq125pt lnN - - 1.30 - - - - - - - - 1.30 - - - - - - +hqq125ptShape shape - - 1 - - - - - - - - 1 - - - - - - #CMS_eff_v lnN 1.2 1.2 1.2 1.2 1.2 1.2 1.2 - - 1.2 1.2 1.2 1.2 1.2 1.2 1.2 - - #CMS_eff_bb lnN 1.1 1.1 1.1 1.1 1.1 - - - - 1.1 1.1 1.1 1.1 1.1 - - - - veff lnN 1.2 1.2 1.2 1.2 1.2 1.2 1.2 - - 1.2 1.2 1.2 1.2 1.2 1.2 1.2 - - @@ -51,3 +52,13 @@ r0p1 flatParam r1p1 flatParam r2p1 flatParam qcdeff flatParam +#hbb rateParam * tthqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_br_yr4.root:br +#hbb rateParam * whqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_br_yr4.root:br +#hbb rateParam * hqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_br_yr4.root:br +#hbb rateParam * zhqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_br_yr4.root:br +#hbb rateParam * vbfhqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_br_yr4.root:br +#ttH_13TeV rateParam * tthqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_yr4_13TeV.root:xs_13TeV +#WH_13TeV rateParam * whqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_yr4_13TeV.root:xs_13TeV +#ggH_13TeV rateParam * hqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_yr4_13TeV.root:xs_13TeV +#ZH_13TeV rateParam * zhqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_yr4_13TeV.root:xs_13TeV +#vbfH_13TeV rateParam * vbfhqq125 $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/data/lhc-hxswg/sm/sm_yr4_13TeV.root:xs_13TeV diff --git a/fitting/PbbJet/limit.py b/fitting/PbbJet/limit.py index 3e7e019..c73715d 100644 --- a/fitting/PbbJet/limit.py +++ b/fitting/PbbJet/limit.py @@ -177,16 +177,17 @@ def goodnessVals(iFName1): def ftest(base,alt,ntoys,iLabel,options): if not options.justPlot: - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 --algorithm saturated --freezeNuisances tqqnormSF,tqqeffSF -n %s'% (base,base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/base1.root'%(base.replace('.txt',''),options.odir)) - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 --algorithm saturated --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (alt,alt.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/base2.root'%(alt.replace('.txt',''),options.odir)) - exec_me('combine -M GenerateOnly %s --rMax 50 --rMin -50 --toysFrequentist -t %i --expectSignal 1 --saveToys --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (base,ntoys,base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GenerateOnly.mH120.123456.root %s/'%(base.replace('.txt',''),options.odir)) - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --algorithm saturated --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (base,ntoys,options.odir,base.replace('.txt',''),base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/toys1.root'%(base.replace('.txt',''),options.odir)) - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --algorithm saturated --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (alt,ntoys,options.odir,base.replace('.txt',''),alt.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/toys2.root'%(alt.replace('.txt',''),options.odir)) + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 --algorithm saturated -n %s --freezeNuisances %s'% (base,base.split('/')[-1].replace('.root',''), options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/base1.root'%(base.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 --algorithm saturated -n %s --freezeNuisances %s' % (alt,alt.split('/')[-1].replace('.root',''), options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/base2.root'%(alt.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + exec_me('combine -M GenerateOnly %s --rMax 20 --rMin -20 --toysFrequentist -t %i --expectSignal %f --saveToys -n %s' % (base,ntoys,options.r,base.split('/')[-1].replace('.root',''))) + exec_me('cp higgsCombine%s.GenerateOnly.mH120.123456.root %s/'%(base.split('/')[-1].replace('.root',''),options.odir)) + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --algorithm saturated -n %s --freezeNuisances %s' % (base,ntoys,options.odir,base.split('/')[-1].replace('.root',''),base.split('/')[-1].replace('.root',''), options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/toys1.root'%(base.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --algorithm saturated -n %s --freezeNuisances %s' % (alt,ntoys,options.odir,base.split('/')[-1].replace('.root',''),alt.split('/')[-1].replace('.root',''), options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/toys2.root'%(alt.split('/')[-1].replace('.root',''),options.odir)) + if options.dryRun: sys.exit() nllBase=fStat("%s/base1.root"%options.odir,"%s/base2.root"%options.odir,options.p1,options.p2,options.n) nllToys=fStat("%s/toys1.root"%options.odir,"%s/toys2.root"%options.odir,options.p1,options.p2,options.n) lPass=0 @@ -203,12 +204,14 @@ def ftest(base,alt,ntoys,iLabel,options): def goodness(base,ntoys,iLabel,options): if not options.justPlot: - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 --algorithm %s --fixedSignalStrength 0 --freezeNuisances tqqnormSF,tqqeffSF -n %s'% (base,options.algo,base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/goodbase.root'%(base.replace('.txt',''),options.odir)) - exec_me('combine -M GenerateOnly %s --rMax 50 --rMin -50 --toysFrequentist -t %i --expectSignal 0 --saveToys --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (base,ntoys,base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GenerateOnly.mH120.123456.root %s/'%(base.replace('.txt',''),options.odir)) - exec_me('combine -M GoodnessOfFit %s --rMax 50 --rMin -50 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --fixedSignalStrength 0 --algorithm %s --freezeNuisances tqqnormSF,tqqeffSF -n %s' % (base,ntoys,options.odir,base.replace('.txt',''),options.algo,base.replace('.txt',''))) - exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/goodtoys.root'%(base.replace('.txt',''),options.odir)) + # --fixedSignalStrength %f --freezeNuisances tqqnormSF,tqqeffSF + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 --algorithm %s -n %s --freezeNuisances %s'% (base,options.algo,base.split('/')[-1].replace('.root',''),options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.root %s/goodbase.root'%(base.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + exec_me('combine -M GenerateOnly %s --rMax 20 --rMin -20 --toysFrequentist -t %i --expectSignal %f --saveToys -n %s --freezeNuisances %s' % (base,ntoys,options.r,base.split('/')[-1].replace('.root',''),options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GenerateOnly.mH120.123456.root %s/'%(base.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + exec_me('combine -M GoodnessOfFit %s --rMax 20 --rMin -20 -t %i --toysFile %s/higgsCombine%s.GenerateOnly.mH120.123456.root --algorithm %s -n %s --freezeNuisances %s' % (base,ntoys,options.odir,base.split('/')[-1].replace('.root',''),options.algo,base.split('/')[-1].replace('.root',''),options.freezeNuisances),options.dryRun) + exec_me('cp higgsCombine%s.GoodnessOfFit.mH120.123456.root %s/goodtoys.root'%(base.split('/')[-1].replace('.root',''),options.odir),options.dryRun) + if options.dryRun: sys.exit() nllBase=goodnessVals('%s/goodbase.root'%options.odir) nllToys=goodnessVals('%s/goodtoys.root'%options.odir) lPass=0 @@ -220,14 +223,14 @@ def goodness(base,ntoys,iLabel,options): return float(lPass)/float(len(nllToys)) def bias(base,alt,ntoys,mu,iLabel): - exec_me('combine -M GenerateOnly %s --rMax 50 --rMin -50 -t %i --expectSignal %i --saveToys ' % (alt,ntoys,mu)) - exec_me('combine -M MaxLikelihoodFit %s --rMax 50 --rMin -50 -t %i --saveNLL --toysFile higgsCombineTest.GenerateOnly.mH120.123456.root' % (base,ntoys)) + exec_me('combine -M GenerateOnly %s --rMax 20 --rMin -20 -t %i --expectSignal %i --saveToys ' % (alt,ntoys,mu)) + exec_me('combine -M MaxLikelihoodFit %s --rMax 20 --rMin -20 -t %i --saveNLL --toysFile higgsCombineTest.GenerateOnly.mH120.123456.root' % (base,ntoys)) exec_me('rm higgsCombineTest.MaxLikelihoodFit.mH120.123456.root') exec_me('mv mlfit.root toys.root') plotgaus("toys.root",mu,"pull"+iLabel) def fit(base,options): - exec_me('combine -M MaxLikelihoodFit %s -v 2 --freezeNuisances tqqeffSF,tqqnormSF --rMin=-50 --rMax=50 --saveNormalizations --plot --saveShapes --saveWithUncertainties --minimizerTolerance 0.001 --minimizerStrategy 2'%base) + exec_me('combine -M MaxLikelihoodFit %s -v 2 --freezeNuisances tqqeffSF,tqqnormSF --rMin=-20 --rMax=20 --saveNormalizations --plot --saveShapes --saveWithUncertainties --minimizerTolerance 0.001 --minimizerStrategy 2'%base) exec_me('mv mlfit.root %s/'%options.odir) exec_me('mv higgsCombineTest.MaxLikelihoodFit.mH120.root %s/'%options.odir) @@ -290,6 +293,12 @@ def generate(mass,toys): parser.add_option('--just-plot', action='store_true', dest='justPlot', default=False, help='just plot') parser.add_option('--data', action='store_true', dest='isData', default=False, help='is data') parser.add_option('-l','--lumi' ,action='store',type='float',dest='lumi' ,default=36.4, help='lumi') + parser.add_option('-r','--r',dest='r', default=0 ,type='float',help='default value of r') + parser.add_option('--rMin',dest='rMin', default=-20 ,type='float',help='minimum of r (signal strength) in profile likelihood plot') + parser.add_option('--rMax',dest='rMax', default=20,type='float',help='maximum of r (signal strength) in profile likelihood plot') + parser.add_option('--freezeNuisances' ,action='store',type='string',dest='freezeNuisances' ,default='None', help='freeze nuisances') + parser.add_option('--dry-run',dest="dryRun",default=False,action='store_true', + help="Just print out commands to run") (options,args) = parser.parse_args() @@ -328,12 +337,12 @@ def generate(mass,toys): ## plotftest(nllToys,nllBase[0],float(lPass)/float(len(nllToys)),'ftest_r2p2_v_r3p2') if options.method=='GoodnessOfFit': - iLabel= 'goodness_%s'%(options.datacard.split('/')[-1].replace('.txt','')) + iLabel= 'goodness_%s'%(options.datacard.split('/')[-1].replace('.root','')) goodness(options.datacard, options.toys, iLabel, options) elif options.method=='MaxLikelihoodFit': fit(options.datacard,options) elif options.method=='FTest': - iLabel= 'ftest_%s_vs_%s'%(options.datacard.split('/')[-1].replace('.txt',''),options.datacardAlt.split('/')[-1].replace('.txt','')) + iLabel= 'ftest_%s_vs_%s'%(options.datacard.split('/')[-1].replace('.root',''),options.datacardAlt.split('/')[-1].replace('.root','')) ftest(options.datacard, options.datacardAlt, options.toys, iLabel, options) diff --git a/fitting/PbbJet/plotDeltaLL.py b/fitting/PbbJet/plotDeltaLL.py index 0c5f005..0fcf485 100644 --- a/fitting/PbbJet/plotDeltaLL.py +++ b/fitting/PbbJet/plotDeltaLL.py @@ -149,17 +149,28 @@ def main(options,args): if options.poi=='r_z': rFrame.SetXTitle("#mu_{Z}") else: - rFrame.SetXTitle("#mu") + rFrame.SetXTitle("#mu_{H}") rFrame.SetYTitle("-2 #Delta log L(%s)"%dataTag) rFrame.SetTitleSize(0.04,"X") rFrame.SetTitleOffset(0.85,"X") - rFrame.SetTitleSize(0.04,"Y") - rFrame.SetTitleOffset(0.8,"Y") - rFrame.SetLabelSize(0.04,"X") - rFrame.SetLabelSize(0.04,"Y") - rFrame.SetNdivisions(505,"X") - - leg = rt.TLegend(0.68,0.17,0.89,0.33) + rFrame.GetXaxis().SetTitleOffset(1.1) + rFrame.GetXaxis().SetTitleSize(0.055) + rFrame.GetXaxis().SetLabelSize(0.05) + rFrame.GetYaxis().SetTitleSize(0.055) + rFrame.GetYaxis().SetLabelSize(0.05) + rFrame.GetYaxis().SetTitleOffset(1.1) + #rFrame.SetTitleSize(0.04,"Y") + #rFrame.SetTitleOffset(0.8,"Y") + #rFrame.SetLabelSize(0.04,"X") + #rFrame.SetLabelSize(0.04,"Y") + rFrame.SetNdivisions(507,"X") + rt.gPad.Update() + rFrame.Draw() + + if dataTag=='asimov' and options.poi=='r_z': + leg = rt.TLegend(0.18,0.17,0.39,0.33) + else: + leg = rt.TLegend(0.69,0.17,0.90,0.33) leg.SetTextFont(42) leg.SetFillColor(rt.kWhite) leg.SetLineColor(rt.kWhite) diff --git a/fitting/PbbJet/plotDeltaLL2D.py b/fitting/PbbJet/plotDeltaLL2D.py index adb22b3..e163e73 100644 --- a/fitting/PbbJet/plotDeltaLL2D.py +++ b/fitting/PbbJet/plotDeltaLL2D.py @@ -1,8 +1,10 @@ - - import ROOT as rt from tools import * from array import array +from scipy.interpolate import Rbf, interp1d +import itertools +import numpy as np +import glob def exec_me(command,dryRun=True): print command @@ -100,6 +102,41 @@ def contourFromTH2(h2in, threshold, minPoints=20): return finalcurv + +def interpolate2D(hist,epsilon=0.2,smooth=1): + x = array('d',[]) + y = array('d',[]) + z = array('d',[]) + + binWidthX = float(hist.GetXaxis().GetBinWidth(1)) + binWidthY = float(hist.GetYaxis().GetBinWidth(1)) + + for i in range(1, hist.GetNbinsX()+1): + for j in range(1, hist.GetNbinsY()+1): + if hist.GetBinContent(i,j)>0.: + x.append(hist.GetXaxis().GetBinCenter(i)) + y.append(hist.GetYaxis().GetBinCenter(j)) + z.append(hist.GetBinContent(i,j)) + + mgMin = hist.GetXaxis().GetBinCenter(1) + mgMax = hist.GetXaxis().GetBinCenter(hist.GetNbinsX())#+hist.GetXaxis().GetBinWidth(hist.GetNbinsX()) + mchiMin = hist.GetYaxis().GetBinCenter(1) + mchiMax = hist.GetYaxis().GetBinCenter(hist.GetNbinsY())#+hist.GetYaxis().GetBinWidth(hist.GetNbinsY()) + + myX = np.linspace(mgMin, mgMax,int((mgMax-mgMin)/binWidthX+1)) + myY = np.linspace(mchiMin, mchiMax, int((mchiMax-mchiMin)/binWidthY+1)) + myXI, myYI = np.meshgrid(myX,myY) + + rbf = Rbf(x, y, z, function='multiquadric', epsilon=epsilon,smooth=smooth) + myZI = rbf(myXI, myYI) + + for i in range(1, hist.GetNbinsX()+1): + for j in range(1, hist.GetNbinsY()+1): + #if hist.GetBinContent(i,j)<=0.: + hist.SetBinContent(i,j,myZI[j-1][i-1]) + + return hist + if __name__ == '__main__': parser = OptionParser() parser.add_option('--data', action='store_true', dest='isData', default=False, help='is data') @@ -116,24 +153,60 @@ def contourFromTH2(h2in, threshold, minPoints=20): rt.gROOT.SetBatch() rt.gStyle.SetOptTitle(0) rt.gStyle.SetOptStat(0) - rt.gStyle.SetPalette(rt.kBlackBody) + #rt.gStyle.SetPalette(rt.kBlackBody) + #rt.gStyle.SetPalette(rt.kBird) + #rt.gStyle.SetPalette(rt.kCherry) + stops = [ 0.0, 1.0] + red = [ 1.0, 0.3] + green = [ 1.0, 0.3] + blue = [ 1.0, 1.0] + + s = array('d', stops) + r = array('d', red) + g = array('d', green) + b = array('d', blue) + + npoints = len(s) + rt.TColor.CreateGradientColorTable(npoints, s, r, g, b, 999) + rt.gStyle.SetNumberContours(999) #exec_me('combine -M MultiDimFit --minimizerTolerance 0.001 --minimizerStrategy 2 --setPhysicsModelParameterRanges r=0,5:r_z=0,2 --algo grid --points 100 -d card_rhalphabet_muonCR_floatZ.root -n 2D --saveWorkspace',True) c = rt.TCanvas('c','c',500,400) if options.isData: + #dataTag = 'data_nosys' dataTag = 'data' else: + #dataTag = 'asimov_nosys' dataTag = 'asimov' - - tfile = rt.TFile.Open('higgsCombine2D_%s.MultiDimFit.mH120.root'%(dataTag)) - limit = tfile.Get('limit') + + limit = rt.TChain('limit') + for ifile in glob.glob('higgsCombine2D_%s.POINTS.*.MultiDimFit.mH120.root'%dataTag): + limit.Add(ifile) + #tfile = rt.TFile.Open('higgsCombine2D_%s.MultiDimFit.mH120.root'%(dataTag)) + #limit = tfile.Get('limit') fit = bestFit(limit, 'r', 'r_z') - limit.Draw("r_z:r>>htemp(20,-4,8,20,0,3)","2*deltaNLL*(quantileExpected>-1)","colz") + print limit.GetEntries() + limit.Draw("r_z:r>>htemp(100,-4,8,100,0,3)","2*deltaNLL*(quantileExpected>-1)*(deltaNLL>0)*(deltaNLL<100)","colz") + #limit.Draw("r_z:r>>htemp(21,-4,8,21,0,3)","2*deltaNLL*(quantileExpected>-1)*(deltaNLL>0)*(deltaNLL<100)","colz") + #limit.Draw("r_z:r>>htemp(21,-6,12,21,0,3)","2*deltaNLL*(quantileExpected>-1)*(deltaNLL>0)*(deltaNLL<100)","colz") #contours = array('d',[2.3,5.99]) htemp = rt.gPad.GetPrimitive('htemp') - htemp.GetXaxis().SetTitle('#mu') + if options.isData: + htemp.SetBinContent(htemp.FindBin(7.,1.15),0) + htemp.SetBinContent(htemp.FindBin(1.3,0.5),0) + htemp.SetBinContent(htemp.FindBin(3.6,0.5),0) + ## for i in range(2,100): + ## for j in range(2,100): + ## cen = htemp.GetBinContent(i,j) + ## ave = (htemp.GetBinContent(i+1,j) + htemp.GetBinContent(i,j+1) + htemp.GetBinContent(i-1,j) + htemp.GetBinContent(i,j-1) ) /4. + ## if abs(cen-ave)/ave > 0.5: + ## print htemp.GetXaxis().GetBinCenter(i), htemp.GetYaxis().GetBinCenter(j), cen, ave + ## #htemp.SetBinContent(i,j, 16) + + htemp = interpolate2D(htemp) + htemp.GetXaxis().SetTitle('#mu_{H}') htemp.GetYaxis().SetTitle('#mu_{Z}') htemp.GetZaxis().SetTitle('-2 #Delta log L(%s)'%dataTag) htemp.SetMinimum(0.) @@ -145,16 +218,21 @@ def contourFromTH2(h2in, threshold, minPoints=20): cl68 = contourFromTH2(htemp, 2.3) cl95 = contourFromTH2(htemp, 5.99) + cl997 = contourFromTH2(htemp, 11.83) cl68.SetLineColor(rt.kBlack) cl68.SetLineWidth(2) cl68.SetLineStyle(1) cl95.SetLineColor(rt.kBlack) cl95.SetLineWidth(2) cl95.SetLineStyle(2) + cl997.SetLineColor(rt.kBlack) + cl997.SetLineWidth(2) + cl997.SetLineStyle(3) htemp.DrawCopy("colz") cl68.Draw("L SAME") cl95.Draw("L SAME") + #cl997.Draw("L SAME") fit.Draw("P SAME") smx = 1. @@ -166,19 +244,22 @@ def contourFromTH2(h2in, threshold, minPoints=20): m.DrawMarker(smx,smy) lumi = 35.9 - tag1 = rt.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) + tag1 = rt.TLatex(0.65,0.92,"%.1f fb^{-1} (13 TeV)"%lumi) tag1.SetNDC(); tag1.SetTextFont(42) tag1.SetTextSize(0.04) - tag2 = rt.TLatex(0.17,0.92,"CMS") + tag2 = rt.TLatex(0.19,0.82,"CMS") tag2.SetNDC(); tag2.SetTextFont(62) - tag3 = rt.TLatex(0.27,0.92,"Preliminary") + tag3 = rt.TLatex(0.29,0.82,"Preliminary") tag3.SetNDC(); tag3.SetTextFont(52) - tag2.SetTextSize(0.05); tag3.SetTextSize(0.04); tag1.Draw(); tag2.Draw(); tag3.Draw() + tag2.SetTextSize(0.05); tag3.SetTextSize(0.04); tag1.Draw(); tag2.Draw(); #tag3.Draw() - leg = rt.TLegend(0.6,0.7,0.85,0.87) + + leg = rt.TLegend(0.55,0.7,0.8,0.87) + leg.SetBorderSize(0) leg.SetTextFont(42) leg.SetFillColor(rt.kWhite) leg.SetLineColor(rt.kWhite) + leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineWidth(0) leg.AddEntry(fit, "Best fit", "p") @@ -187,15 +268,17 @@ def contourFromTH2(h2in, threshold, minPoints=20): leg.AddEntry(cl95, "95% CL", "l") leg.Draw("same") + - c.Print('deltaLL2D_%s.pdf'%dataTag) - c.Print('deltaLL2D_%s.C'%dataTag) + c.Print('deltaLL2D_%s.pdf'%dataTag.lower()) + c.Print('deltaLL2D_%s.C'%dataTag.lower()) htemp.Draw("axis") cl68.Draw("L SAME") cl95.Draw("L SAME") + #cl997.Draw("L SAME") fit.Draw("P SAME") @@ -217,10 +300,12 @@ def contourFromTH2(h2in, threshold, minPoints=20): tag3.SetNDC(); tag3.SetTextFont(52) tag2.SetTextSize(0.05); tag3.SetTextSize(0.04); tag1.Draw(); tag2.Draw(); tag3.Draw() - leg = rt.TLegend(0.6,0.7,0.85,0.85) + leg = rt.TLegend(0.55,0.7,0.8,0.87) + leg.SetBorderSize(0) leg.SetTextFont(42) leg.SetFillColor(rt.kWhite) leg.SetLineColor(rt.kWhite) + leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineWidth(0) leg.AddEntry(fit, "Best fit", "p") diff --git a/fitting/PbbJet/runFtest.py b/fitting/PbbJet/runFtest.py index a7eef48..d0ce285 100644 --- a/fitting/PbbJet/runFtest.py +++ b/fitting/PbbJet/runFtest.py @@ -25,23 +25,26 @@ def exec_me(command, dryRun=False): parser.add_option('--scale',dest='scale', default=1,type='float',help='scale factor to scale MC (assuming only using a fraction of the data)') parser.add_option('-l','--lumi' ,action='store',type='float',dest='lumi' ,default=36.4, help='lumi') parser.add_option('-i','--ifile', dest='ifile', default = 'hist_1DZbb.root',help='file with histogram inputs', metavar='ifile') + parser.add_option('--ifile-loose', dest='ifile_loose', default=None, help='second file with histogram inputs (looser b-tag cut to take W/Z/H templates)', + metavar='ifile_loose') parser.add_option('-t','--toys' ,action='store',type='int',dest='toys' ,default=200, help='number of toys') - + parser.add_option('-r','--r',dest='r', default=0 ,type='float',help='default value of r') parser.add_option('-n','--n' ,action='store',type='int',dest='n' ,default=5*20, help='number of bins') parser.add_option('--just-plot', action='store_true', dest='justPlot', default=False, help='just plot') parser.add_option('--pseudo', action='store_true', dest='pseudo', default=False, help='run on asimov dataset') parser.add_option('--blind', action='store_true', dest='blind', default=False, help='run on blinded dataset') parser.add_option('--dry-run',dest="dryRun",default=False,action='store_true', help="Just print out commands to run") + parser.add_option('-o', '--odir', dest='odir', default='./', help='directory to write plots', metavar='odir') (options,args) = parser.parse_args() if options.pseudo: - cardsDir1 = 'cards_mc_r%ip%i'%(options.NR1,options.NP1) - cardsDir2 = 'cards_mc_r%ip%i'%(options.NR2,options.NP2) + cardsDir1 = '%s/cards_mc_r%ip%i'%(options.odir,options.NR1,options.NP1) + cardsDir2 = '%s/cards_mc_r%ip%i'%(options.odir,options.NR2,options.NP2) else: - cardsDir1 = 'cards_r%ip%i'%(options.NR1,options.NP1) - cardsDir2 = 'cards_r%ip%i'%(options.NR2,options.NP2) + cardsDir1 = '%s/cards_r%ip%i'%(options.odir,options.NR1,options.NP1) + cardsDir2 = '%s/cards_r%ip%i'%(options.odir,options.NR2,options.NP2) pseudoString = '' if options.pseudo: @@ -50,20 +53,37 @@ def exec_me(command, dryRun=False): blindString = '' if options.blind: blindString = '--blind' - + + exec_me('mkdir -p %s'%options.odir,options.dryRun) + exec_me('mkdir -p %s/ftest_r%ip%i_r%ip%i_muonCR'%(options.odir,options.NR1, options.NP1, options.NR2, options.NP2),options.dryRun) + exec_me('mkdir -p %s/ftest_r%ip%i_r%ip%i'%(options.odir,options.NR1, options.NP1, options.NR2, options.NP2),options.dryRun) exec_me('mkdir -p %s'%cardsDir1,options.dryRun) exec_me('mkdir -p %s'%cardsDir2,options.dryRun) - exec_me('python buildRhalphabetHbb.py -i %s --scale %f -o %s --nr %i --np %i %s %s --use-qcd '%(options.ifile, options.scale, cardsDir1, options.NR1, options.NP1, blindString, pseudoString),options.dryRun ) - exec_me('python buildRhalphabetHbb.py -i %s --scale %f -o %s --nr %i --np %i %s %s --use-qcd '%(options.ifile, options.scale, cardsDir2, options.NR2, options.NP2, blindString, pseudoString),options.dryRun ) - exec_me('python makeCardsHbb.py -i %s -o %s'%(options.ifile,cardsDir1),options.dryRun) - exec_me('python makeCardsHbb.py -i %s -o %s'%(options.ifile,cardsDir2),options.dryRun) - exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt > card_rhalphabet_r%ip%i.txt'%(cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,options.NR1, options.NP1),options.dryRun) - exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt > card_rhalphabet_r%ip%i.txt'%(cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,options.NR2, options.NP2),options.dryRun) - p1 = int((options.NR1+1)*(options.NP1+1)) - p2 = int((options.NR2+1)*(options.NP2+1)) + exec_me('python buildRhalphabetHbb.py -i %s --ifile-loose %s --scale %f -o %s --nr %i --np %i %s %s --remove-unmatched --prefit --use-qcd --addHptShape '%(options.ifile, options.ifile_loose, options.scale, cardsDir1, options.NR1, options.NP1, blindString, pseudoString),options.dryRun ) + exec_me('python buildRhalphabetHbb.py -i %s --ifile-loose %s --scale %f -o %s --nr %i --np %i %s %s --remove-unmatched --prefit --use-qcd --addHptShape '%(options.ifile, options.ifile_loose, options.scale, cardsDir2, options.NR2, options.NP2, blindString, pseudoString),options.dryRun ) + exec_me('python writeMuonCRDatacard.py -i output-miniaod-pfmet140-hptckkw-hqq125ptShape/ -o %s/'%(cardsDir1),options.dryRun) + exec_me('python writeMuonCRDatacard.py -i output-miniaod-pfmet140-hptckkw-hqq125ptShape/ -o %s/'%(cardsDir2),options.dryRun) + exec_me('python makeCardsHbb.py -i %s --ifile-loose %s -o %s --remove-unmatched --no-mcstat-shape'%(options.ifile,options.ifile_loose,cardsDir1),options.dryRun) + exec_me('python makeCardsHbb.py -i %s --ifile-loose %s -o %s --remove-unmatched --no-mcstat-shape'%(options.ifile,options.ifile_loose,cardsDir2),options.dryRun) + exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt %s/datacard_muonCR.txt > %s/card_rhalphabet_muonCR_r%ip%i.txt'%(cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,options.NR1, options.NP1),options.dryRun) + exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt %s/datacard_muonCR.txt > %s/card_rhalphabet_muonCR_r%ip%i.txt'%(cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,options.NR2, options.NP2),options.dryRun) + exec_me("text2workspace.py -P HiggsAnalysis.CombinedLimit.PhysicsModel:multiSignalModel -m 125 --PO verbose --PO 'map=.*/*hqq125:r[1,0,20]' --PO 'map=.*/zqq:r_z[1,0,20]' %s/card_rhalphabet_muonCR_r%ip%i.txt -o %s/card_rhalphabet_muonCR_floatZ_r%ip%i.root"%(cardsDir1, options.NR1, options.NP1, cardsDir1, options.NR1, options.NP1)) + exec_me("text2workspace.py -P HiggsAnalysis.CombinedLimit.PhysicsModel:multiSignalModel -m 125 --PO verbose --PO 'map=.*/*hqq125:r[1,0,20]' --PO 'map=.*/zqq:r_z[1,0,20]' %s/card_rhalphabet_muonCR_r%ip%i.txt -o %s/card_rhalphabet_muonCR_floatZ_r%ip%i.root"%(cardsDir2, options.NR2, options.NP2, cardsDir2, options.NR2, options.NP2)) + exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt > %s/card_rhalphabet_r%ip%i.txt'%(cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,cardsDir1,options.NR1, options.NP1),options.dryRun) + exec_me('combineCards.py cat1=%s/card_rhalphabet_cat1.txt cat2=%s/card_rhalphabet_cat2.txt cat3=%s/card_rhalphabet_cat3.txt cat4=%s/card_rhalphabet_cat4.txt cat5=%s/card_rhalphabet_cat5.txt cat6=%s/card_rhalphabet_cat6.txt > %s/card_rhalphabet_r%ip%i.txt'%(cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,cardsDir2,options.NR2, options.NP2),options.dryRun) + exec_me("text2workspace.py -P HiggsAnalysis.CombinedLimit.PhysicsModel:multiSignalModel -m 125 --PO verbose --PO 'map=.*/*hqq125:r[1,0,20]' --PO 'map=.*/zqq:r_z[1,0,20]' %s/card_rhalphabet_r%ip%i.txt -o %s/card_rhalphabet_floatZ_r%ip%i.root"%(cardsDir1, options.NR1, options.NP1, cardsDir1, options.NR1, options.NP1)) + exec_me("text2workspace.py -P HiggsAnalysis.CombinedLimit.PhysicsModel:multiSignalModel -m 125 --PO verbose --PO 'map=.*/*hqq125:r[1,0,20]' --PO 'map=.*/zqq:r_z[1,0,20]' %s/card_rhalphabet_r%ip%i.txt -o %s/card_rhalphabet_floatZ_r%ip%i.root"%(cardsDir2, options.NR2, options.NP2, cardsDir2, options.NR2, options.NP2)) + + p1 = int((options.NR1+1)*(options.NP1+1)) + 2 # paramaters including floating Hbb and Zbb signals + p2 = int((options.NR2+1)*(options.NP2+1)) + 2 # parameters including floating Hbb and Zbb signals + + + dataString = '' + if not options.pseudo: + dataString = '--data' - exec_me('mkdir -p ftest_r%ip%i_r%ip%i'%(options.NR1, options.NP1, options.NR2, options.NP2),options.dryRun) - exec_me('python limit.py -M FTest --datacard card_rhalphabet_r%ip%i.txt --datacard-alt card_rhalphabet_r%ip%i.txt -o ftest_r%ip%i_r%ip%i -n %i --p1 %i --p2 %i -t %i --lumi %f '%(options.NR1, options.NP1, options.NR2, options.NP2,options.NR1, options.NP1, options.NR2, options.NP2, options.n, p1, p2, options.toys,options.lumi ),options.dryRun) + exec_me('python limit.py -M FTest --datacard %s/card_rhalphabet_muonCR_floatZ_r%ip%i.root --datacard-alt %s/card_rhalphabet_muonCR_floatZ_r%ip%i.root -o %s/ftest_r%ip%i_r%ip%i_muonCR -n %i --p1 %i --p2 %i -t %i --lumi %f %s -r %f'%(cardsDir1, options.NR1, options.NP1, cardsDir2, options.NR2, options.NP2, options.odir, options.NR1, options.NP1, options.NR2, options.NP2, options.n, p1, p2, options.toys, options.lumi, dataString, options.r),options.dryRun) + #exec_me('python limit.py -M FTest --datacard %s/card_rhalphabet_floatZ_r%ip%i.root --datacard-alt %s/card_rhalphabet_floatZ_r%ip%i.root -o %s/ftest_r%ip%i_r%ip%i -n %i --p1 %i --p2 %i -t %i --lumi %f %s -r %f --freezeNuisances tqqeffSF,tqqnormSF'%(cardsDir1, options.NR1, options.NP1, cardsDir2, options.NR2, options.NP2, options.odir, options.NR1, options.NP1, options.NR2, options.NP2, options.n, p1, p2, options.toys, options.lumi, dataString, options.r),options.dryRun) diff --git a/fitting/PbbJet/validateMLFit.py b/fitting/PbbJet/validateMLFit.py index 11b78f2..f6e8984 100644 --- a/fitting/PbbJet/validateMLFit.py +++ b/fitting/PbbJet/validateMLFit.py @@ -144,14 +144,6 @@ def main(options, args): options.sOverSb, options.splitS, options.ratio) -def fun2(x, par): - rho = r.TMath.Log((x[0] * x[0]) / (x[1] * x[1])) - poly0 = par[0] * (1.0 + par[1] * rho + par[2] * rho * rho) - poly1 = par[0] * (par[3] + par[4] * rho + par[5] * rho * rho) * x[1] - poly2 = par[0] * (par[6] + par[7] * rho + par[8] * rho * rho) * x[1] * x[1] - return poly0 + poly1 + poly2 - - def plotCategory(fml, fd, index, fittype): shapes = ['wqq', 'zqq', 'tqq', 'qcd', 'hqq125', 'zhqq125', 'whqq125', 'tthqq125', 'vbfhqq125'] histograms_fail = [] @@ -297,7 +289,7 @@ def makeMLFitCanvas(bkgs, data, hsigs, leg, tag, odir='cards', rBestFit=1, sOver if splitS: l = r.TLegend(0.6, 0.4, 0.75, 0.85) else: - l = r.TLegend(0.6, 0.6, 0.75, 0.85) + l = r.TLegend(0.6, 0.5, 0.75, 0.85) l.SetFillStyle(0) l.SetBorderSize(0) l.SetTextFont(42) @@ -353,7 +345,13 @@ def getDataGraphFromHist(h_data): data.GetXaxis().SetTitle('m_{SD}^{PUPPI} (GeV)') - data.Draw('pez') + data.Draw('pez') + if 'cat1' in tag: + data.GetXaxis().SetRangeUser(40,201 - 7*5) + elif 'cat2' in tag: + data.GetXaxis().SetRangeUser(40,201 - 7*3) + else: + data.GetXaxis().SetRangeUser(40,201) htot.Draw('E2same') # htotsig.Draw('E2same') @@ -385,7 +383,7 @@ def getDataGraphFromHist(h_data): g_data.Draw('pezsame') l.Draw() tag1 = r.TLatex(0.67, 0.92, "%.1f fb^{-1} (13 TeV)" % options.lumi) - tag1.SetNDC(); + tag1.SetNDC() tag1.SetTextFont(42) tag1.SetTextSize(0.045) tag2 = r.TLatex(0.2, 0.82, "CMS") @@ -395,13 +393,41 @@ def getDataGraphFromHist(h_data): tag3 = r.TLatex(0.2, 0.77, "Preliminary") else: tag3 = r.TLatex(0.2, 0.77, "Simulation Preliminary") + + + ptRange = [450, 1000] + if 'cat1' in tag: + ptRange = [450, 500] + elif 'cat2' in tag: + ptRange = [500, 550] + elif 'cat3' in tag: + ptRange = [550, 600] + elif 'cat3' in tag: + ptRange = [550, 600] + elif 'cat4' in tag: + ptRange = [600, 675] + elif 'cat5' in tag: + ptRange = [675, 800] + elif 'cat6' in tag: + ptRange = [800, 1000] + + passTag = 'double-b tag > 0.9' + if 'fail' in tag: + passTag = 'double-b tag < 0.9' + + + tag4 = r.TLatex(0.37, 0.77, "#splitline{%i < p_{T} < %i GeV}{%s}"%(ptRange[0],ptRange[1],passTag)) + tag4.SetNDC() + tag4.SetTextFont(42) tag3.SetNDC() tag3.SetTextFont(52) tag2.SetTextSize(0.055) tag3.SetTextSize(0.045) + tag4.SetTextSize(0.035) tag1.Draw() tag2.Draw() - tag3.Draw() + #tag3.Draw() + tag4.Draw() data.SetMaximum(data.GetMaximum() * 1.2) c.cd() @@ -482,6 +508,12 @@ def getDataGraphFromHist(h_data): iOneWithErrors.SetMarkerSize(0) iOneWithErrors.SetLineWidth(2) iRatio.Draw('pez') + if 'cat1' in tag: + iRatio.GetXaxis().SetRangeUser(40,201 - 7*5) + elif 'cat2' in tag: + iRatio.GetXaxis().SetRangeUser(40,201 - 7*3) + else: + iRatio.GetXaxis().SetRangeUser(40,201) iOneWithErrorsLine = iOneWithErrors.Clone('iOneWithErrorsLine%s' % tag) iOneWithErrorsLine.SetFillStyle(0) @@ -544,13 +576,20 @@ def fun2(x, par): return poly0 + poly1 + poly2 +def fun2rho(x, par): + rho = x[0] + poly0 = par[0]*(1.0 + par[1]*rho + par[2]*rho*rho) + poly1 = par[0]*(par[3] + par[4]*rho + par[5]*rho*rho)*x[1] + poly2 = par[0]*(par[6] + par[7]*rho + par[8]*rho*rho)*x[1]*x[1] + return poly0+poly1+poly2 + def makeTF(pars, ratio): ratio.GetXaxis().SetTitle('m_{SD}^{PUPPI} (GeV)') ratio.GetYaxis().SetTitle('p_{T} (GeV)') ratio.GetXaxis().SetTitleOffset(1.5) ratio.GetYaxis().SetTitleOffset(1.5) - ratio.GetZaxis().SetTitle('Ratio') + ratio.GetZaxis().SetTitle('Pass-to-fail Ratio') ratio.GetXaxis().SetNdivisions(504) ratio.GetYaxis().SetNdivisions(504) ratio.GetZaxis().SetNdivisions(504) @@ -616,6 +655,237 @@ def makeTF(pars, ratio): # r.gPad.Update() # c.SaveAs(options.odir+"/mlfit/tf_%03d.png"%i) + + c.SetLogz(0) + Npoints = 10 + f2graph = r.TGraph2D() + N = -1 + for i in range(Npoints+1): + for j in range(Npoints+1): + N+=1 + x = ratio.GetXaxis().GetXmin() + i*(ratio.GetXaxis().GetXmax()-ratio.GetXaxis().GetXmin())/Npoints + y = ratio.GetYaxis().GetXmin() + j*(ratio.GetYaxis().GetXmax()-ratio.GetYaxis().GetXmin())/Npoints + z = f2.Eval(x,y) + #if math.log(x*x/(y*y)) < -6 or math.log(x*x/(y*y)) > -2.1: + # z = 0 + #print x, y, z + f2graph.SetPoint(N,x,y,z) + + rhoxy = r.TF2("rhoxy","log(x*x/y/y)",30,221,400,1100) + contours = array.array('d',[-6 ,-2.1]) + rhoxy.SetContour(2,contours) + rhoxy.Draw("CONT Z LIST") + r.gPad.Update() + conts = r.gROOT.GetListOfSpecials().FindObject("contours") + contour0 = conts.At(0) + rhocurv1 = contour0.First().Clone() + rhocurv1.SetLineWidth(-503) + rhocurv1.SetFillStyle(3004) + rhocurv1.SetFillColor(r.kBlack) + rhocurv1.SetLineColor(r.kBlack) + contour0 = conts.At(1) + rhocurv2 = contour0.First().Clone() + rhocurv2.SetLineWidth(503) + rhocurv2.SetFillStyle(3004) + rhocurv2.SetFillColor(r.kBlack) + rhocurv2.SetLineColor(r.kBlack) + + mxy = r.TF2("mxy", "sqrt(exp(x))*y",-6.5, -1.5, 400, 1100) + contours = array.array('d',[40 ,201]) + mxy.SetContour(2,contours) + mxy.Draw("CONT Z LIST") + r.gPad.Update() + conts = r.gROOT.GetListOfSpecials().FindObject("contours") + contour0 = conts.At(0) + mcurv1 = contour0.First().Clone() + mcurv1.SetLineWidth(503) + mcurv1.SetFillStyle(3004) + mcurv1.SetFillColor(r.kBlack) + mcurv1.SetLineColor(r.kBlack) + contour0 = conts.At(1) + mcurv2 = contour0.First().Clone() + mcurv2.SetLineWidth(-503) + mcurv2.SetFillStyle(3004) + mcurv2.SetFillColor(r.kBlack) + mcurv2.SetLineColor(r.kBlack) + + r.gStyle.SetNumberContours(999) + + ratiorho = r.TH2D('ratiorho','ratiorho',Npoints,-6,-2.1,Npoints,ratio.GetYaxis().GetXmin(),ratio.GetYaxis().GetXmax()) + ratiorho.GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + ratiorho.GetXaxis().SetTitle('#rho') + ratiorho.GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + ratiorhograph = r.TGraph2D() + N = -1 + for i in range(1,ratio.GetNbinsX()+1): + for j in range(1,ratio.GetNbinsY()+1): + N+=1 + m = ratio.GetXaxis().GetBinCenter(i) + y = ratio.GetYaxis().GetBinCenter(j) + x = math.log(m*m/(y*y)) + z = ratio.GetBinContent(i,j) + #print N, x, y, z + ratiorhograph.SetPoint(N,x,y,z) + f2rho = r.TF2("f2",fun2rho,-6,-2.1,ratio.GetYaxis().GetXmin(),ratio.GetYaxis().GetXmax(),npar) + f2rho.SetParameters(f2params) + f2rhograph = r.TGraph2D() + N = -1 + for i in range(Npoints+1): + for j in range(Npoints+1): + N+=1 + x = -6 + i*(-2.1+6)/Npoints + y = ratio.GetYaxis().GetXmin() + j*(ratio.GetYaxis().GetXmax()-ratio.GetYaxis().GetXmin())/Npoints + z = f2rho.Eval(x,y) + m = math.sqrt(math.exp(x))*y + #if m < 40 or m > 201: + # z = 0 + #print x, y, z + f2rhograph.SetPoint(N,x,y,z) + #ratiorho.Draw('surf1') + ratiorhograph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + ratiorhograph.GetHistogram().GetXaxis().SetTitle('#rho') + ratiorhograph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + ratiorhograph.GetHistogram().GetYaxis().SetNdivisions(505) + ratiorhograph.GetHistogram().GetXaxis().SetNdivisions(505) + ratiorhograph.GetHistogram().GetXaxis().SetTitleOffset(1.5) + ratiorhograph.GetHistogram().GetYaxis().SetTitleOffset(1.5) + ratiorhograph.Draw("surf1") + f2rho.Draw("surf fb bb same") + #f2rhograph.SetLineColor(r.kRed) + #f2rhograph.Draw("surf fb bb same") + tag1 = r.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%options.lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = r.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = r.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + c.SaveAs(options.odir + "/mlfit/tf_rho.pdf") + c.SaveAs(options.odir + "/mlfit/tf_rho.C") + + # to plot TF2 + #f2.Draw("colz") + c.SetRightMargin(0.20) + # to plot TGraph: + f2graph.Draw("colz") + rhocurv1.Draw('same') + rhocurv2.Draw('same') + + f2graph.GetHistogram().GetXaxis().SetTitle(ratio.GetXaxis().GetTitle()) + f2graph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + f2graph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + f2graph.GetHistogram().GetZaxis().SetTitleOffset(1.3) + tag1 = r.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%options.lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = r.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = r.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + pave_param = r.TPaveText(0.17,0.72,0.27,0.82,"NDC") + pave_param.SetTextFont(42) + pave_param.SetFillColor(0) + pave_param.SetBorderSize(0) + pave_param.SetFillStyle(0) + pave_param.SetTextAlign(11) + pave_param.SetTextSize(0.045) + text = pave_param.AddText("#rho = #minus6") + text.SetTextAngle(75) + text.SetTextAlign(22) + text.SetTextSize(0.045) + pave_param.Draw() + + pave_param2 = r.TPaveText(0.62,0.18,0.72,0.28,"NDC") + pave_param2.SetTextFont(42) + pave_param2.SetFillColor(0) + pave_param2.SetBorderSize(0) + pave_param2.SetFillStyle(0) + pave_param2.SetTextAlign(11) + pave_param2.SetTextSize(0.045) + text2 = pave_param2.AddText("#rho = #minus2.1") + text2.SetTextAngle(40) + text2.SetTextAlign(22) + text2.SetTextSize(0.045) + pave_param2.Draw() + + + + c.SaveAs(options.odir + "/mlfit/tf_msdcolz.pdf") + c.SaveAs(options.odir + "/mlfit/tf_msdcolz.C") + + # to plot TF2 + #f2rho.Draw("colz") + # to plot TGraph: + #f2rhograph.SetContours(999) + f2rhograph.Draw("colz") + mcurv1.Draw('same') + mcurv2.Draw('same') + f2rhograph.GetHistogram().GetXaxis().SetTitle('#rho') + f2rhograph.GetHistogram().GetYaxis().SetTitle(ratio.GetYaxis().GetTitle()) + f2rhograph.GetHistogram().GetZaxis().SetTitle(ratio.GetZaxis().GetTitle()) + f2rhograph.GetHistogram().GetZaxis().SetTitleOffset(1.3) + Tag1 = r.TLatex(0.67,0.92,"%.1f fb^{-1} (13 TeV)"%options.lumi) + tag1.SetNDC(); tag1.SetTextFont(42) + tag1.SetTextSize(0.045) + tag2 = r.TLatex(0.15,0.92,"CMS") + tag2.SetNDC() + tag2.SetTextFont(62) + tag3 = r.TLatex(0.25,0.92,"Preliminary") + tag3.SetNDC() + tag3.SetTextFont(52) + tag2.SetTextSize(0.055) + tag3.SetTextSize(0.045) + tag1.Draw() + tag2.Draw() + tag3.Draw() + + + pave_param = r.TPaveText(0.18,0.5,0.28,0.6,"NDC") + pave_param.SetTextFont(42) + pave_param.SetFillColor(0) + pave_param.SetBorderSize(0) + pave_param.SetFillStyle(0) + pave_param.SetTextAlign(11) + pave_param.SetTextSize(0.045) + text = pave_param.AddText("m_{SD} = 40 GeV") + text.SetTextAngle(-70) + text.SetTextAlign(22) + text.SetTextSize(0.045) + pave_param.Draw() + + pave_param2 = r.TPaveText(0.57,0.65,0.67,0.75,"NDC") + pave_param2.SetTextFont(42) + pave_param2.SetFillColor(0) + pave_param2.SetBorderSize(0) + pave_param2.SetFillStyle(0) + pave_param2.SetTextAlign(11) + pave_param2.SetTextSize(0.045) + text2 = pave_param2.AddText("m_{SD} = 201 GeV") + text2.SetTextAngle(-72) + text2.SetTextAlign(22) + text2.SetTextSize(0.045) + pave_param2.Draw() + + c.SaveAs(options.odir + "/mlfit/tf_rhocolz.pdf") + c.SaveAs(options.odir + "/mlfit/tf_rhocolz.C") + + ##------------------------------------------------------------------------------------- if __name__ == '__main__': @@ -646,6 +916,22 @@ def makeTF(pars, ratio): r.gStyle.SetPaintTextFormat("1.1f") r.gStyle.SetOptFit(0000) r.gROOT.SetBatch() - # r.gStyle.SetPalette(r.kBird) + #r.gStyle.SetPalette(r.kBird) + #r.gStyle.SetPalette(r.kBlackBody) + stops = [ 0.0, 1.0] + red = [ 1.0, 0.3] + green = [ 1.0, 0.3] + blue = [ 1.0, 1.0] + + s = array.array('d', stops) + rs = array.array('d', red) + g = array.array('d', green) + b = array.array('d', blue) + + npoints = len(s) + r.TColor.CreateGradientColorTable(npoints, s, rs, g, b, 999) + + r.gStyle.SetNumberContours(999) + main(options, args) ##------------------------------------------------------------------------------------- diff --git a/fitting/rhalphabet_builder.py b/fitting/rhalphabet_builder.py index f97987d..c530aaa 100644 --- a/fitting/rhalphabet_builder.py +++ b/fitting/rhalphabet_builder.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -import ROOT as r,sys,math,os +import ROOT as r, sys, math, os from multiprocessing import Process from optparse import OptionParser from operator import add @@ -8,10 +8,11 @@ import time import array import re + #r.gSystem.Load("~/Dropbox/RazorAnalyzer/python/lib/libRazorRun2.so") r.gSystem.Load(os.getenv('CMSSW_BASE')+'/lib/'+os.getenv('SCRAM_ARCH')+'/libHiggsAnalysisCombinedLimit.so') -#r.gInterpreter.GenerateDictionary("std::pair", "map;string;RooDataHist.h") -#r.gInterpreter.GenerateDictionary("std::map", "map;string;RooDataHist.h") +# r.gInterpreter.GenerateDictionary("std::pair", "map;string;RooDataHist.h") +# r.gInterpreter.GenerateDictionary("std::map", "map;string;RooDataHist.h") # including other directories @@ -24,14 +25,17 @@ V_SF = 0.993 V_SF_ERR = 0.043 + ############################################################################## ############################################################################## #### B E G I N N I N G O F C L A S S ############################################################################## ############################################################################## -class RhalphabetBuilder(): - def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass_nbins=23, mass_lo=40, mass_hi=201, blind_lo=110, blind_hi=131, rho_lo=-6, rho_hi= -2.1, blind=False, mass_fit=False, freeze_poly=False, remove_unmatched=False, input_file_loose=None): +class RhalphabetBuilder(): + def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass_nbins=23, mass_lo=40, mass_hi=201, + blind_lo=110, blind_hi=131, rho_lo=-6, rho_hi=-2.1, blind=False, mass_fit=False, freeze_poly=False, + remove_unmatched=False, input_file_loose=None): self._pass_hists = pass_hists self._fail_hists = fail_hists self._mass_fit = mass_fit @@ -45,8 +49,8 @@ def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass self._outfile_validation = r.TFile.Open("{}/validation.root".format(out_dir), "RECREATE"); self._mass_nbins = mass_nbins - self._mass_lo = mass_lo - self._mass_hi = mass_hi + self._mass_lo = mass_lo + self._mass_hi = mass_hi self._blind = blind self._mass_blind_lo = blind_lo self._mass_blind_hi = blind_hi @@ -56,43 +60,47 @@ def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass # self._mass_lo = pass_hists[0].GetXaxis().GetBinLowEdge( 1 ) # self._mass_hi = pass_hists[0].GetXaxis().GetBinUpEdge( self._mass_nbins ) - self._remove_unmatched = remove_unmatched + self._remove_unmatched = remove_unmatched print "number of mass bins and lo/hi: ", self._mass_nbins, self._mass_lo, self._mass_hi; - #polynomial order for fit - self._poly_degree_rho = nr #1 = linear ; 2 is quadratic - self._poly_degree_pt = np #1 = linear ; 2 is quadratic + # polynomial order for fit + self._poly_degree_rho = nr # 1 = linear ; 2 is quadratic + self._poly_degree_pt = np # 1 = linear ; 2 is quadratic self._nptbins = pass_hists["data_obs"].GetYaxis().GetNbins() - self._pt_lo = pass_hists["data_obs"].GetYaxis().GetBinLowEdge( 1 ) - self._pt_hi = pass_hists["data_obs"].GetYaxis().GetBinUpEdge( self._nptbins ) + self._pt_lo = pass_hists["data_obs"].GetYaxis().GetBinLowEdge(1) + self._pt_hi = pass_hists["data_obs"].GetYaxis().GetBinUpEdge(self._nptbins) + self._ptbins = [] + for ipt in range(0,self._nptbins+1): + self._ptbins.append(pass_hists["data_obs"].GetYaxis().GetBinLowEdge(ipt+1)) # define RooRealVars - self._lMSD = r.RooRealVar("x","x",self._mass_lo,self._mass_hi) - self._lMSD.setRange('Low',self._mass_lo,self._mass_blind_lo) - self._lMSD.setRange('Blind',self._mass_blind_lo,self._mass_blind_hi) - self._lMSD.setRange('High',self._mass_blind_hi,self._mass_hi) - #self._lMSD.setBins(self._mass_nbins) - self._lPt = r.RooRealVar("pt","pt",self._pt_lo,self._pt_hi) + self._lMSD = r.RooRealVar("x", "x", self._mass_lo, self._mass_hi) + self._lMSD.setRange('Low', self._mass_lo, self._mass_blind_lo) + self._lMSD.setRange('Blind', self._mass_blind_lo, self._mass_blind_hi) + self._lMSD.setRange('High', self._mass_blind_hi, self._mass_hi) + # self._lMSD.setBins(self._mass_nbins) + self._lPt = r.RooRealVar("pt", "pt", self._pt_lo, self._pt_hi) self._lPt.setBins(self._nptbins) - self._lRho = r.RooFormulaVar("rho","log(x*x/pt/pt)",r.RooArgList(self._lMSD,self._lPt)) + self._lRho = r.RooFormulaVar("rho", "log(x*x/pt/pt)", r.RooArgList(self._lMSD, self._lPt)) - self._lEff = r.RooRealVar("veff" ,"veff" ,0.5 ,0.,1.0) + self._lEff = r.RooRealVar("veff", "veff", 0.5, 0., 1.0) - self._lEffQCD = r.RooRealVar("qcdeff" ,"qcdeff" ,0.01,0.,10.) + self._lEffQCD = r.RooRealVar("qcdeff", "qcdeff", 0.01, 0., 10.) qcd_pass_integral = 0 qcd_fail_integral = 0 - for i in range(1,fail_hists["qcd"].GetNbinsX()+1): - for j in range(1,fail_hists["qcd"].GetNbinsY()+1): - if fail_hists["qcd"].GetXaxis().GetBinCenter(i) > self._mass_lo and fail_hists["qcd"].GetXaxis().GetBinCenter(i) < self._mass_hi: - qcd_fail_integral += fail_hists["qcd"].GetBinContent(i,j) - qcd_pass_integral += pass_hists["qcd"].GetBinContent(i,j) - if qcd_fail_integral>0: + for i in range(1, fail_hists["qcd"].GetNbinsX() + 1): + for j in range(1, fail_hists["qcd"].GetNbinsY() + 1): + if fail_hists["qcd"].GetXaxis().GetBinCenter(i) > self._mass_lo and fail_hists[ + "qcd"].GetXaxis().GetBinCenter(i) < self._mass_hi: + qcd_fail_integral += fail_hists["qcd"].GetBinContent(i, j) + qcd_pass_integral += pass_hists["qcd"].GetBinContent(i, j) + if qcd_fail_integral > 0: qcdeff = qcd_pass_integral / qcd_fail_integral self._lEffQCD.setVal(qcdeff) - print "qcdeff = %f"%qcdeff - self._lDM = r.RooRealVar("dm","dm", 0.,-10,10) - self._lShift = r.RooFormulaVar("shift",self._lMSD.GetName()+"-dm",r.RooArgList(self._lMSD,self._lDM)) + print "qcdeff = %f" % qcdeff + self._lDM = r.RooRealVar("dm", "dm", 0., -10, 10) + self._lShift = r.RooFormulaVar("shift", self._lMSD.GetName() + "-dm", r.RooArgList(self._lMSD, self._lDM)) self._all_vars = [] self._all_shapes = [] @@ -102,7 +110,7 @@ def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass self._background_names = ["wqq", "zqq", "qcd", "tqq"] self._signal_names = [] # for Pbb - #for mass in [50,75,125,100,150,250,300]: + # for mass in [50,75,125,100,150,250,300]: # self._signal_names.append("Pbb_" + str(mass)) # for Hbb for mass in [125]: @@ -112,13 +120,105 @@ def __init__(self, pass_hists, fail_hists, input_file, out_dir, nr=2, np=1, mass def run(self): self.LoopOverPtBins() + def addHptShape(self): + fbase = r.TFile.Open(self._output_path, 'update') + + categories = ['pass_cat1', 'pass_cat2', 'pass_cat3', 'pass_cat4', 'pass_cat5', 'pass_cat6', + 'fail_cat1', 'fail_cat2', 'fail_cat3', 'fail_cat4', 'fail_cat5', 'fail_cat6'] + + sigs = self._signal_names + wbase = {} + for cat in categories: + wbase[cat] = fbase.Get('w_%s' % cat) + x = wbase[categories[0]].var('x') + rooCat = r.RooCategory('cat', 'cat') + + histpdf = {} + datahist = {} + hptpdfUp_s = {} + hptpdfDown_s = {} + signorm = {} + all_int = 0 + all_int_rescale_Down = 0 + all_int_rescale_Up = 0 + proc = 'hqq125' + total_unc = 1.3 # -> cat6 has 130% SF w.r.t cat1 + #total_unc = 1.6 # -> cat6 has 160% SF w.r.t. cat1 + #total_unc = 3.0 # -> cat6 has 300% SF w.r.t. cat1 + iptlo = self._ptbins[0] + ipthi = self._ptbins[-2] + for cat in categories: + iptbin = int(cat[-1])-1 # returns 0 for cat1, 1 for cat2, etc. + ipt = self._ptbins[iptbin] + rooCat.defineType(cat) + datahist['%s_%s' % (proc, cat)] = wbase[cat].data('%s_%s' % (proc, cat)) + myint = datahist['%s_%s' % (proc, cat)].sumEntries() + all_int_rescale_Up += myint * (1 + (ipt-iptlo) * (total_unc-1.) / (ipthi-iptlo)) + all_int_rescale_Down += myint / (1 + (ipt-iptlo) * (total_unc-1.) / (ipthi-iptlo)) + all_int += myint + print cat, (1 + (ipt-iptlo) * (total_unc-1.) / (ipthi-iptlo)) + + for cat in categories: + iptbin = int(cat[-1])-1 # returns 0 for cat1, 1 for cat2, etc. + ipt = self._ptbins[iptbin] + rooCat.defineType(cat) + histpdf['%s_%s' % (proc, cat)] = r.RooHistPdf('histpdf_%s_%s' % (proc, cat), + 'histpdf_%s_%s' % (proc, cat), + r.RooArgSet(wbase[cat].var('x')), + datahist['%s_%s' % (proc, cat)]) + + hist_up = histpdf['%s_%s' % (proc, cat)].createHistogram("x") + hist_down = histpdf['%s_%s' % (proc, cat)].createHistogram("x") + + rescaled_int_up = datahist['%s_%s' % (proc, cat)].sumEntries() * (1. + (ipt-iptlo) * (total_unc-1.) / (ipthi-iptlo)) * (all_int / all_int_rescale_Up) + rescaled_int_down = datahist['%s_%s' % (proc, cat)].sumEntries() / (1. + (ipt-iptlo) * (total_unc-1.) / (ipthi-iptlo)) * (all_int / all_int_rescale_Down) + + hist_up.Scale(rescaled_int_up/hist_up.Integral()) + hist_down.Scale(rescaled_int_down/hist_down.Integral()) + + # validation + self._outfile_validation.cd() + hist_up.SetName('%s_%s_%s'%(proc,cat,'hqq125ptShapeUp')) + hist_up.Write() + hist_down.SetName('%s_%s_%s'%(proc,cat,'hqq125ptShapeDown')) + hist_down.Write() + + + hptpdfUp_s[cat] = r.RooDataHist('%s_%s_%s'%(proc,cat,'hqq125ptShapeUp'), '%s_%s_%s'%(proc,cat,'hqq125ptShapeUp'), r.RooArgList(x), hist_up) + hptpdfDown_s[cat] = r.RooDataHist('%s_%s_%s'%(proc,cat,'hqq125ptShapeDown'), '%s_%s_%s'%(proc,cat,'hqq125ptShapeDown'), r.RooArgList(x), hist_down) + + getattr(wbase[cat], 'import')(hptpdfUp_s[cat], r.RooFit.RecycleConflictNodes()) + getattr(wbase[cat], 'import')(hptpdfDown_s[cat], r.RooFit.RecycleConflictNodes()) + + up = 0 + down = 0 + nom = 0 + for cat in categories: + nom += datahist['%s_%s' % (proc, cat)].sumEntries() + up += hptpdfUp_s[cat].sumEntries() + down += hptpdfDown_s[cat].sumEntries() + print cat, datahist['%s_%s' % (proc, cat)].sumEntries() + print cat, hptpdfUp_s[cat].sumEntries() + print cat, hptpdfDown_s[cat].sumEntries() + print "total", nom + print "total", up + print "total", down + + icat = 0 + for cat in categories: + if icat == 0: + wbase[cat].writeToFile(self._output_path, True) + else: + wbase[cat].writeToFile(self._output_path, False) + icat += 1 + def prefit(self): - fbase = r.TFile.Open(self._output_path,'update') - fralphabase = r.TFile.Open(self._rhalphabet_output_path,'update') + fbase = r.TFile.Open(self._output_path, 'update') + fralphabase = r.TFile.Open(self._rhalphabet_output_path, 'update') - categories = ['pass_cat1','pass_cat2','pass_cat3','pass_cat4','pass_cat5','pass_cat6', - 'fail_cat1','fail_cat2','fail_cat3','fail_cat4','fail_cat5','fail_cat6'] + categories = ['pass_cat1', 'pass_cat2', 'pass_cat3', 'pass_cat4', 'pass_cat5', 'pass_cat6', + 'fail_cat1', 'fail_cat2', 'fail_cat3', 'fail_cat4', 'fail_cat5', 'fail_cat6'] bkgs = self._background_names sigs = self._signal_names @@ -126,16 +226,16 @@ def prefit(self): wbase = {} wralphabase = {} for cat in categories: - wbase[cat] = fbase.Get('w_%s'%cat) - wralphabase[cat] = fralphabase.Get('w_%s'%cat) + wbase[cat] = fbase.Get('w_%s' % cat) + wralphabase[cat] = fralphabase.Get('w_%s' % cat) w = r.RooWorkspace('w') w.factory('mu[1.,0.,20.]') x = wbase[categories[0]].var('x') - rooCat = r.RooCategory('cat','cat') + rooCat = r.RooCategory('cat', 'cat') mu = w.var('mu') - epdf_b = {} + epdf_b = {} epdf_s = {} datahist = {} histpdf = {} @@ -145,58 +245,59 @@ def prefit(self): for cat in categories: rooCat.defineType(cat) - for cat in categories: + for cat in categories: norms_b = r.RooArgList() norms_s = r.RooArgList() - norms_b.add(wralphabase[cat].function('qcd_%s_norm'%cat)) - norms_s.add(wralphabase[cat].function('qcd_%s_norm'%cat)) + norms_b.add(wralphabase[cat].function('qcd_%s_norm' % cat)) + norms_s.add(wralphabase[cat].function('qcd_%s_norm' % cat)) pdfs_b = r.RooArgList() pdfs_s = r.RooArgList() - pdfs_b.add(wralphabase[cat].pdf('qcd_%s'%cat)) - pdfs_s.add(wralphabase[cat].pdf('qcd_%s'%cat)) - - data[cat] = wbase[cat].data('data_obs_%s'%cat) - for proc in (bkgs+sigs): - if proc=='qcd': continue - - datahist['%s_%s'%(proc,cat)] = wbase[cat].data('%s_%s'%(proc,cat)) - histpdf['%s_%s'%(proc,cat)] = r.RooHistPdf('histpdf_%s_%s'%(proc,cat), - 'histpdf_%s_%s'%(proc,cat), - r.RooArgSet(wbase[cat].var('x')), - datahist['%s_%s'%(proc,cat)]) - getattr(w,'import')(datahist['%s_%s'%(proc,cat)],r.RooFit.RecycleConflictNodes()) - getattr(w,'import')(histpdf['%s_%s'%(proc,cat)],r.RooFit.RecycleConflictNodes()) + pdfs_b.add(wralphabase[cat].pdf('qcd_%s' % cat)) + pdfs_s.add(wralphabase[cat].pdf('qcd_%s' % cat)) + + data[cat] = wbase[cat].data('data_obs_%s' % cat) + for proc in (bkgs + sigs): + if proc == 'qcd': continue + + datahist['%s_%s' % (proc, cat)] = wbase[cat].data('%s_%s' % (proc, cat)) + histpdf['%s_%s' % (proc, cat)] = r.RooHistPdf('histpdf_%s_%s' % (proc, cat), + 'histpdf_%s_%s' % (proc, cat), + r.RooArgSet(wbase[cat].var('x')), + datahist['%s_%s' % (proc, cat)]) + getattr(w, 'import')(datahist['%s_%s' % (proc, cat)], r.RooFit.RecycleConflictNodes()) + getattr(w, 'import')(histpdf['%s_%s' % (proc, cat)], r.RooFit.RecycleConflictNodes()) if 'hqq125' in proc: # signal - signorm['%s_%s'%(proc,cat)] = r.RooRealVar('signorm_%s_%s'%(proc,cat), - 'signorm_%s_%s'%(proc,cat), - datahist['%s_%s'%(proc,cat)].sumEntries(), - 0,10.*datahist['%s_%s'%(proc,cat)].sumEntries()) - signorm['%s_%s'%(proc,cat)].setConstant(True) - getattr(w,'import')(signorm['%s_%s'%(proc,cat)],r.RooFit.RecycleConflictNodes()) - histpdfnorm['%s_%s'%(proc,cat)] = r.RooFormulaVar('histpdfnorm_%s_%s'%(proc,cat), - '@0*@1',r.RooArgList(mu,signorm['%s_%s'%(proc,cat)])) - pdfs_s.add(histpdf['%s_%s'%(proc,cat)]) - norms_s.add(histpdfnorm['%s_%s'%(proc,cat)]) + signorm['%s_%s' % (proc, cat)] = r.RooRealVar('signorm_%s_%s' % (proc, cat), + 'signorm_%s_%s' % (proc, cat), + datahist['%s_%s' % (proc, cat)].sumEntries(), + 0, 10. * datahist['%s_%s' % (proc, cat)].sumEntries()) + signorm['%s_%s' % (proc, cat)].setConstant(True) + getattr(w, 'import')(signorm['%s_%s' % (proc, cat)], r.RooFit.RecycleConflictNodes()) + histpdfnorm['%s_%s' % (proc, cat)] = r.RooFormulaVar('histpdfnorm_%s_%s' % (proc, cat), + '@0*@1', r.RooArgList(mu, signorm[ + '%s_%s' % (proc, cat)])) + pdfs_s.add(histpdf['%s_%s' % (proc, cat)]) + norms_s.add(histpdfnorm['%s_%s' % (proc, cat)]) else: # background - histpdfnorm['%s_%s'%(proc,cat)] = r.RooRealVar('histpdfnorm_%s_%s'%(proc,cat), - 'histpdfnorm_%s_%s'%(proc,cat), - datahist['%s_%s'%(proc,cat)].sumEntries(), - 0,10.*datahist['%s_%s'%(proc,cat)].sumEntries()) - histpdfnorm['%s_%s'%(proc,cat)].setConstant(True) - getattr(w,'import')(histpdfnorm['%s_%s'%(proc,cat)],r.RooFit.RecycleConflictNodes()) - pdfs_b.add(histpdf['%s_%s'%(proc,cat)]) - pdfs_s.add(histpdf['%s_%s'%(proc,cat)]) - norms_b.add(histpdfnorm['%s_%s'%(proc,cat)]) - norms_s.add(histpdfnorm['%s_%s'%(proc,cat)]) - - - epdf_b[cat] = r.RooAddPdf('epdf_b_'+cat,'epdf_b_'+cat,pdfs_b,norms_b) - epdf_s[cat] = r.RooAddPdf('epdf_s_'+cat,'epdf_s_'+cat,pdfs_s,norms_s) - - getattr(w,'import')(epdf_b[cat],r.RooFit.RecycleConflictNodes()) - getattr(w,'import')(epdf_s[cat],r.RooFit.RecycleConflictNodes()) + histpdfnorm['%s_%s' % (proc, cat)] = r.RooRealVar('histpdfnorm_%s_%s' % (proc, cat), + 'histpdfnorm_%s_%s' % (proc, cat), + datahist['%s_%s' % (proc, cat)].sumEntries(), + 0, 10. * datahist[ + '%s_%s' % (proc, cat)].sumEntries()) + histpdfnorm['%s_%s' % (proc, cat)].setConstant(True) + getattr(w, 'import')(histpdfnorm['%s_%s' % (proc, cat)], r.RooFit.RecycleConflictNodes()) + pdfs_b.add(histpdf['%s_%s' % (proc, cat)]) + pdfs_s.add(histpdf['%s_%s' % (proc, cat)]) + norms_b.add(histpdfnorm['%s_%s' % (proc, cat)]) + norms_s.add(histpdfnorm['%s_%s' % (proc, cat)]) + + epdf_b[cat] = r.RooAddPdf('epdf_b_' + cat, 'epdf_b_' + cat, pdfs_b, norms_b) + epdf_s[cat] = r.RooAddPdf('epdf_s_' + cat, 'epdf_s_' + cat, pdfs_s, norms_s) + + getattr(w, 'import')(epdf_b[cat], r.RooFit.RecycleConflictNodes()) + getattr(w, 'import')(epdf_s[cat], r.RooFit.RecycleConflictNodes()) ## arguments = ["data_obs","data_obs",r.RooArgList(x),rooCat] @@ -204,29 +305,29 @@ def prefit(self): ## for cat in categories: ## m.insert(r.std.pair('string, RooDataHist*')(cat, data[cat])) ## arguments.append(m) - + ## combData = getattr(r,'RooDataHist')(*arguments) - + cat = categories[0] args = data[cat].get(0) - + combiner = r.CombDataSetFactory(args, rooCat) - + for cat in categories: combiner.addSetBin(cat, data[cat]) - combData = combiner.done('data_obs','data_obs') + combData = combiner.done('data_obs', 'data_obs') - simPdf_b = r.RooSimultaneous('simPdf_b','simPdf_b',rooCat) - simPdf_s = r.RooSimultaneous('simPdf_s','simPdf_s',rooCat) + simPdf_b = r.RooSimultaneous('simPdf_b', 'simPdf_b', rooCat) + simPdf_s = r.RooSimultaneous('simPdf_s', 'simPdf_s', rooCat) for cat in categories: - simPdf_b.addPdf(epdf_b[cat],cat) - simPdf_s.addPdf(epdf_s[cat],cat) + simPdf_b.addPdf(epdf_b[cat], cat) + simPdf_s.addPdf(epdf_s[cat], cat) - mu.setVal(1.) + mu.setVal(1.) - getattr(w,'import')(simPdf_b,r.RooFit.RecycleConflictNodes()) - getattr(w,'import')(simPdf_s,r.RooFit.RecycleConflictNodes()) - getattr(w,'import')(combData,r.RooFit.RecycleConflictNodes()) + getattr(w, 'import')(simPdf_b, r.RooFit.RecycleConflictNodes()) + getattr(w, 'import')(simPdf_s, r.RooFit.RecycleConflictNodes()) + getattr(w, 'import')(combData, r.RooFit.RecycleConflictNodes()) w.Print('v') simPdf_b = w.pdf('simPdf_b') @@ -242,7 +343,7 @@ def prefit(self): opt = r.RooLinkedList() opt.Add(r.RooFit.CloneData(False)) allParams = simPdf_b.getParameters(combData) - r.RooStats.RemoveConstantParameters(allParams) + r.RooStats.RemoveConstantParameters(allParams) opt.Add(r.RooFit.Constrain(allParams)) mu.setVal(1) @@ -258,32 +359,32 @@ def prefit(self): m2.setEps(1e-5) m2.optimizeConst(2) - migrad_status = m2.minimize('Minuit2','migrad') - improve_status = m2.minimize('Minuit2','improve') - hesse_status = m2.minimize('Minuit2','hesse') + migrad_status = m2.minimize('Minuit2', 'migrad') + improve_status = m2.minimize('Minuit2', 'improve') + hesse_status = m2.minimize('Minuit2', 'hesse') fr = m2.save() fr.Print('v') icat = 0 for cat in categories: - reset(wralphabase[cat],fr) - if icat==0: - getattr(wralphabase[cat],'import')(fr) - wralphabase[cat].writeToFile(self._rhalphabet_output_path,True) + reset(wralphabase[cat], fr) + if icat == 0: + getattr(wralphabase[cat], 'import')(fr) + wralphabase[cat].writeToFile(self._rhalphabet_output_path, True) else: - wralphabase[cat].writeToFile(self._rhalphabet_output_path,False) + wralphabase[cat].writeToFile(self._rhalphabet_output_path, False) icat += 1 - def loadfit(self,fitToLoad): + def loadfit(self, fitToLoad): - fralphabase_load = r.TFile.Open(fitToLoad,'read') + fralphabase_load = r.TFile.Open(fitToLoad, 'read') fr = fralphabase_load.Get('w_pass_cat1').obj('nll_simPdf_s_data_obs') - - fbase = r.TFile.Open(self._output_path,'update') - fralphabase = r.TFile.Open(self._rhalphabet_output_path,'update') - categories = ['pass_cat1','pass_cat2','pass_cat3','pass_cat4','pass_cat5','pass_cat6', - 'fail_cat1','fail_cat2','fail_cat3','fail_cat4','fail_cat5','fail_cat6'] + fbase = r.TFile.Open(self._output_path, 'update') + fralphabase = r.TFile.Open(self._rhalphabet_output_path, 'update') + + categories = ['pass_cat1', 'pass_cat2', 'pass_cat3', 'pass_cat4', 'pass_cat5', 'pass_cat6', + 'fail_cat1', 'fail_cat2', 'fail_cat3', 'fail_cat4', 'fail_cat5', 'fail_cat6'] bkgs = self._background_names sigs = self._signal_names @@ -291,88 +392,100 @@ def loadfit(self,fitToLoad): wbase = {} wralphabase = {} for cat in categories: - wbase[cat] = fbase.Get('w_%s'%cat) - wralphabase[cat] = fralphabase.Get('w_%s'%cat) + wbase[cat] = fbase.Get('w_%s' % cat) + wralphabase[cat] = fralphabase.Get('w_%s' % cat) icat = 0 for cat in categories: - reset(wralphabase[cat],fr,exclude='qcd_fail_cat') - if icat==0: - wralphabase[cat].writeToFile(self._rhalphabet_output_path,True) + reset(wralphabase[cat], fr, exclude='qcd_fail_cat') + if icat == 0: + wralphabase[cat].writeToFile(self._rhalphabet_output_path, True) else: - wralphabase[cat].writeToFile(self._rhalphabet_output_path,False) + wralphabase[cat].writeToFile(self._rhalphabet_output_path, False) icat += 1 - + def LoopOverPtBins(self): print "number of pt bins = ", self._nptbins; - for pt_bin in range(1,self._nptbins+1): - # for pt_bin in range(1,2): - print "------- pT bin number ",pt_bin + for pt_bin in range(1, self._nptbins + 1): + # for pt_bin in range(1,2): + print "------- pT bin number ", pt_bin # 1d histograms in each pT bin (in the order... data, w, z, qcd, top, signals) pass_hists_ptbin = {} fail_hists_ptbin = {} for name, hist in self._pass_hists.iteritems(): - pass_hists_ptbin[name] = tools.proj("cat",str(pt_bin),hist,self._mass_nbins,self._mass_lo,self._mass_hi) + pass_hists_ptbin[name] = tools.proj("cat", str(pt_bin), hist, self._mass_nbins, self._mass_lo, + self._mass_hi) for name, hist in self._fail_hists.iteritems(): - fail_hists_ptbin[name] = tools.proj("cat",str(pt_bin),hist,self._mass_nbins,self._mass_lo,self._mass_hi) + fail_hists_ptbin[name] = tools.proj("cat", str(pt_bin), hist, self._mass_nbins, self._mass_lo, + self._mass_hi) # make RooDataset, RooPdfs, and histograms # GetWorkspaceInputs returns: RooDataHist (data), then RooHistPdf of each electroweak - (data_pass_rdh, data_fail_rdh, pass_rhps, fail_rhps) = self.GetWorkspaceInputs(pass_hists_ptbin, fail_hists_ptbin,"cat"+str(pt_bin)) - #Get approximate pt bin value - this_pt = self._pass_hists["data_obs"].GetYaxis().GetBinLowEdge(pt_bin)+self._pass_hists["data_obs"].GetYaxis().GetBinWidth(pt_bin)*0.3; - print "------- this bin pT value ",this_pt - - #Make the rhalphabet fit for this pt bin - (rhalphabet_hist_pass, rhalphabet_hist_fail) = self.MakeRhalphabet(["data_obs", "wqq", "zqq", "tqq"], fail_hists_ptbin, this_pt, "cat"+str(pt_bin)) + (data_pass_rdh, data_fail_rdh, pass_rhps, fail_rhps) = self.GetWorkspaceInputs(pass_hists_ptbin, + fail_hists_ptbin, + "cat" + str(pt_bin)) + # Get approximate pt bin value + this_pt = self._pass_hists["data_obs"].GetYaxis().GetBinLowEdge(pt_bin) + self._pass_hists[ + "data_obs"].GetYaxis().GetBinWidth( + pt_bin) * 0.3; + print "------- this bin pT value ", this_pt + + # Make the rhalphabet fit for this pt bin + (rhalphabet_hist_pass, rhalphabet_hist_fail) = self.MakeRhalphabet(["data_obs", "wqq", "zqq", "tqq"], + fail_hists_ptbin, this_pt, + "cat" + str(pt_bin)) # Get signals - (signal_rdhs_pass, signal_rdhs_fail) = self.GetSignalInputs(pass_hists_ptbin, fail_hists_ptbin, "cat"+str(pt_bin)) + (signal_rdhs_pass, signal_rdhs_fail) = self.GetSignalInputs(pass_hists_ptbin, fail_hists_ptbin, + "cat" + str(pt_bin)) pass_rhps.update(signal_rdhs_pass) fail_rhps.update(signal_rdhs_fail) # #Write to file print "pass_rhps = " print pass_rhps - self.MakeWorkspace(self._output_path, [data_pass_rdh] + pass_rhps.values(), "pass_cat"+str(pt_bin), True, True, this_pt) - self.MakeWorkspace(self._output_path, [data_fail_rdh] + fail_rhps.values(), "fail_cat"+str(pt_bin), True, True, this_pt) + self.MakeWorkspace(self._output_path, [data_pass_rdh] + pass_rhps.values(), "pass_cat" + str(pt_bin), True, + True, this_pt) + self.MakeWorkspace(self._output_path, [data_fail_rdh] + fail_rhps.values(), "fail_cat" + str(pt_bin), True, + True, this_pt) - - for pt_bin in range(1,self._nptbins+1): - for mass_bin in range(1,self._mass_nbins+1): + for pt_bin in range(1, self._nptbins + 1): + for mass_bin in range(1, self._mass_nbins + 1): print "qcd_fail_cat%i_Bin%i flatParam" % (pt_bin, mass_bin) # iHs = dict of fail histograms def MakeRhalphabet(self, samples, fail_histograms, pt, category): - print "---- [MakeRhalphabet]" + print "---- [MakeRhalphabet]" - rhalph_bkgd_name ="qcd"; - lUnity = r.RooConstVar("unity","unity",1.) - lZero = r.RooConstVar("lZero","lZero",0.) + rhalph_bkgd_name = "qcd"; + lUnity = r.RooConstVar("unity", "unity", 1.) + lZero = r.RooConstVar("lZero", "lZero", 0.) - #Fix the pt (top) and the qcd eff + # Fix the pt (top) and the qcd eff self._lPt.setVal(pt) self._lEffQCD.setConstant(False) polynomial_variables = [] - self.buildPolynomialArray(polynomial_variables,self._poly_degree_pt,self._poly_degree_rho,"p","r",-30,30) + self.buildPolynomialArray(polynomial_variables, self._poly_degree_pt, self._poly_degree_rho, "p", "r", -30, 30) print "polynomial_variables=", print polynomial_variables - #Now build the function + # Now build the function pass_bins = r.RooArgList() fail_bins = r.RooArgList() - for mass_bin in range(1,self._mass_nbins+1): + for mass_bin in range(1, self._mass_nbins + 1): self._lMSD.setVal(fail_histograms["data_obs"].GetXaxis().GetBinCenter(mass_bin)) - if self._mass_fit : + if self._mass_fit: print ("Pt/mass poly") - roopolyarray = self.buildRooPolyArray(self._lPt.getVal(),self._lMSD.getVal(),lUnity,lZero,polynomial_variables) - else : + roopolyarray = self.buildRooPolyArray(self._lPt.getVal(), self._lMSD.getVal(), lUnity, lZero, + polynomial_variables) + else: print ("Pt/Rho poly") - roopolyarray = self.buildRooPolyRhoArray(self._lPt.getVal(),self._lRho.getVal(),lUnity,lZero,polynomial_variables) + roopolyarray = self.buildRooPolyRhoArray(self._lPt.getVal(), self._lRho.getVal(), lUnity, lZero, + polynomial_variables) print "RooPolyArray:" roopolyarray.Print() fail_bin_content = 0 @@ -380,134 +493,143 @@ def MakeRhalphabet(self, samples, fail_histograms, pt, category): if sample == "data_obs": print sample, fail_histograms[sample].GetName(), "add data" print "\t+={}".format(fail_histograms[sample].GetBinContent(mass_bin)) - fail_bin_content += fail_histograms[sample].GetBinContent(mass_bin) # add data - else: + fail_bin_content += fail_histograms[sample].GetBinContent(mass_bin) # add data + else: print sample, fail_histograms[sample].GetName(), "subtract W/Z/ttbar" print "\t-={}".format(fail_histograms[sample].GetBinContent(mass_bin)) - fail_bin_content -= fail_histograms[sample].GetBinContent(mass_bin) # subtract W/Z/ttbar from data + fail_bin_content -= fail_histograms[sample].GetBinContent(mass_bin) # subtract W/Z/ttbar from data if fail_bin_content < 0: fail_bin_content = 0. - print rhalph_bkgd_name+"_fail_"+category+"_Bin"+str(mass_bin), fail_bin_content + print rhalph_bkgd_name + "_fail_" + category + "_Bin" + str(mass_bin), fail_bin_content - #50 sigma range + 10 events - fail_bin_unc = math.sqrt(fail_bin_content)*50.+10. - #Define the failing category - fail_bin_var = r.RooRealVar(rhalph_bkgd_name+"_fail_"+category+"_Bin"+str(mass_bin),rhalph_bkgd_name+"_fail_"+category+"_Bin"+str(mass_bin),fail_bin_content,0.,max(fail_bin_content+fail_bin_unc,0.)) + # 50 sigma range + 10 events + fail_bin_unc = math.sqrt(fail_bin_content) * 50. + 10. + # Define the failing category + fail_bin_var = r.RooRealVar(rhalph_bkgd_name + "_fail_" + category + "_Bin" + str(mass_bin), + rhalph_bkgd_name + "_fail_" + category + "_Bin" + str(mass_bin), + fail_bin_content, 0., max(fail_bin_content + fail_bin_unc, 0.)) print "[david debug] fail_bin_var:" fail_bin_var.Print() - #Now define the passing cateogry based on the failing (make sure it can't go negative) - lArg = r.RooArgList(fail_bin_var,roopolyarray,self._lEffQCD) - pass_bin_var = r.RooFormulaVar(rhalph_bkgd_name+"_pass_"+category+"_Bin"+str(mass_bin),rhalph_bkgd_name+"_pass_"+category+"_Bin"+str(mass_bin),"@0*max(@1,0)*@2",lArg) + # Now define the passing cateogry based on the failing (make sure it can't go negative) + lArg = r.RooArgList(fail_bin_var, roopolyarray, self._lEffQCD) + pass_bin_var = r.RooFormulaVar(rhalph_bkgd_name + "_pass_" + category + "_Bin" + str(mass_bin), + rhalph_bkgd_name + "_pass_" + category + "_Bin" + str(mass_bin), + "@0*max(@1,0)*@2", lArg) print "Pass=fail*poly*eff RooFormulaVar:" print pass_bin_var.Print() # print pass_bin_var.GetName() - #If the number of events in the failing is small remove the bin from being free in the fit + # If the number of events in the failing is small remove the bin from being free in the fit if fail_bin_content < 4: print "too small number of events", fail_bin_content, "Bin", str(mass_bin) fail_bin_var.setConstant(True) - pass_bin_var = r.RooRealVar(rhalph_bkgd_name+"_pass_"+category+"_Bin"+str(mass_bin),rhalph_bkgd_name+"_pass_"+category+"_Bin"+str(mass_bin),0,0,0) + pass_bin_var = r.RooRealVar(rhalph_bkgd_name + "_pass_" + category + "_Bin" + str(mass_bin), + rhalph_bkgd_name + "_pass_" + category + "_Bin" + str(mass_bin), 0, 0, 0) pass_bin_var.setConstant(True) - #Add bins to the array + # Add bins to the array pass_bins.add(pass_bin_var) fail_bins.add(fail_bin_var) - self._all_vars.extend([pass_bin_var,fail_bin_var]) - self._all_pars.extend([pass_bin_var,fail_bin_var]) + self._all_vars.extend([pass_bin_var, fail_bin_var]) + self._all_pars.extend([pass_bin_var, fail_bin_var]) # print fail_bin_var.GetName(),"flatParam",lPass#,lPass+"/("+lFail+")*@0" - #print "Printing pass_bins:" - #for i in xrange(pass_bins.getSize()): + # print "Printing pass_bins:" + # for i in xrange(pass_bins.getSize()): # pass_bins[i].Print() - pass_rparh = r.RooParametricHist(rhalph_bkgd_name+"_pass_"+category,rhalph_bkgd_name+"_pass_"+category,self._lMSD,pass_bins,fail_histograms["data_obs"]) - fail_rparh = r.RooParametricHist(rhalph_bkgd_name+"_fail_"+category,rhalph_bkgd_name+"_fail_"+category,self._lMSD,fail_bins,fail_histograms["data_obs"]) + pass_rparh = r.RooParametricHist(rhalph_bkgd_name + "_pass_" + category, rhalph_bkgd_name + "_pass_" + category, + self._lMSD, pass_bins, fail_histograms["data_obs"]) + fail_rparh = r.RooParametricHist(rhalph_bkgd_name + "_fail_" + category, rhalph_bkgd_name + "_fail_" + category, + self._lMSD, fail_bins, fail_histograms["data_obs"]) print "Print pass and fail RooParametricHists" pass_rparh.Print() fail_rparh.Print() - pass_norm = r.RooAddition(rhalph_bkgd_name+"_pass_"+category+"_norm",rhalph_bkgd_name+"_pass_"+category+"_norm",pass_bins) - fail_norm = r.RooAddition(rhalph_bkgd_name+"_fail_"+category+"_norm",rhalph_bkgd_name+"_fail_"+category+"_norm",fail_bins) + pass_norm = r.RooAddition(rhalph_bkgd_name + "_pass_" + category + "_norm", + rhalph_bkgd_name + "_pass_" + category + "_norm", pass_bins) + fail_norm = r.RooAddition(rhalph_bkgd_name + "_fail_" + category + "_norm", + rhalph_bkgd_name + "_fail_" + category + "_norm", fail_bins) print "Printing NPass and NFail variables:" pass_norm.Print() - fail_norm.Print() - self._all_shapes.extend([pass_rparh,fail_rparh,pass_norm,fail_norm]) - - #Now write the wrokspace with the rooparamhist - pass_workspace = r.RooWorkspace("w_pass_"+str(category)) - fail_workspace = r.RooWorkspace("w_fail_"+str(category)) - getattr(pass_workspace,'import')(pass_rparh,r.RooFit.RecycleConflictNodes()) - getattr(pass_workspace,'import')(pass_norm,r.RooFit.RecycleConflictNodes()) - getattr(fail_workspace,'import')(fail_rparh,r.RooFit.RecycleConflictNodes()) - getattr(fail_workspace,'import')(fail_norm,r.RooFit.RecycleConflictNodes()) + fail_norm.Print() + self._all_shapes.extend([pass_rparh, fail_rparh, pass_norm, fail_norm]) + + # Now write the wrokspace with the rooparamhist + pass_workspace = r.RooWorkspace("w_pass_" + str(category)) + fail_workspace = r.RooWorkspace("w_fail_" + str(category)) + getattr(pass_workspace, 'import')(pass_rparh, r.RooFit.RecycleConflictNodes()) + getattr(pass_workspace, 'import')(pass_norm, r.RooFit.RecycleConflictNodes()) + getattr(fail_workspace, 'import')(fail_rparh, r.RooFit.RecycleConflictNodes()) + getattr(fail_workspace, 'import')(fail_norm, r.RooFit.RecycleConflictNodes()) print "Printing rhalphabet workspace:" pass_workspace.Print() if category.find("1") > -1: pass_workspace.writeToFile(self._rhalphabet_output_path) else: - pass_workspace.writeToFile(self._rhalphabet_output_path,False) - fail_workspace.writeToFile(self._rhalphabet_output_path,False) - return [pass_rparh,fail_rparh] + pass_workspace.writeToFile(self._rhalphabet_output_path, False) + fail_workspace.writeToFile(self._rhalphabet_output_path, False) + return [pass_rparh, fail_rparh] - def buildRooPolyArray(self,iPt,iMass,iQCD,iZero,iVars): + def buildRooPolyArray(self, iPt, iMass, iQCD, iZero, iVars): # print "---- [buildRooPolyArray]" # print len(iVars); - lPt = r.RooConstVar("Var_Pt_" +str(iPt)+"_"+str(iMass), "Var_Pt_" +str(iPt)+"_"+str(iMass),(iPt)) - lMass = r.RooConstVar("Var_Mass_"+str(iPt)+"_"+str(iMass), "Var_Mass_"+str(iPt)+"_"+str(iMass),(iMass)) + lPt = r.RooConstVar("Var_Pt_" + str(iPt) + "_" + str(iMass), "Var_Pt_" + str(iPt) + "_" + str(iMass), (iPt)) + lMass = r.RooConstVar("Var_Mass_" + str(iPt) + "_" + str(iMass), "Var_Mass_" + str(iPt) + "_" + str(iMass), + (iMass)) lMassArray = r.RooArgList() - lNCount=0 - for pRVar in range(0,self._poly_degree_rho+1): + lNCount = 0 + for pRVar in range(0, self._poly_degree_rho + 1): lTmpArray = r.RooArgList() - for pVar in range(0,self._poly_degree_pt+1): + for pVar in range(0, self._poly_degree_pt + 1): if lNCount == 0: - lTmpArray.add(iQCD) # for the very first constant (e.g. p0r0), just set that to 1 + lTmpArray.add(iQCD) # for the very first constant (e.g. p0r0), just set that to 1 else: lTmpArray.add(iVars[lNCount]) - lNCount=lNCount+1 - pLabel="Var_Pol_Bin_"+str(round(iPt,2))+"_"+str(round(iMass,3))+"_"+str(pRVar) - pPol = r.RooPolyVar(pLabel,pLabel,lPt,lTmpArray) + lNCount = lNCount + 1 + pLabel = "Var_Pol_Bin_" + str(round(iPt, 2)) + "_" + str(round(iMass, 3)) + "_" + str(pRVar) + pPol = r.RooPolyVar(pLabel, pLabel, lPt, lTmpArray) lMassArray.add(pPol) self._all_vars.append(pPol) - lLabel="Var_MassPol_Bin_"+str(round(iPt,2))+"_"+str(round(iMass,3)) - lMassPol = r.RooPolyVar(lLabel,lLabel,lMass,lMassArray) - self._all_vars.extend([lPt,lMass,lMassPol]) + lLabel = "Var_MassPol_Bin_" + str(round(iPt, 2)) + "_" + str(round(iMass, 3)) + lMassPol = r.RooPolyVar(lLabel, lLabel, lMass, lMassArray) + self._all_vars.extend([lPt, lMass, lMassPol]) return lMassPol - def buildRooPolyRhoArray(self,iPt,iRho,iQCD,iZero,iVars): + def buildRooPolyRhoArray(self, iPt, iRho, iQCD, iZero, iVars): # print "---- [buildRooPolyArray]" - lPt = r.RooConstVar("Var_Pt_" +str(iPt)+"_"+str(iRho), "Var_Pt_" +str(iPt)+"_"+str(iRho),(iPt)) - lRho = r.RooConstVar("Var_Rho_"+str(iPt)+"_"+str(iRho), "Var_Rho_"+str(iPt)+"_"+str(iRho),(iRho)) + lPt = r.RooConstVar("Var_Pt_" + str(iPt) + "_" + str(iRho), "Var_Pt_" + str(iPt) + "_" + str(iRho), (iPt)) + lRho = r.RooConstVar("Var_Rho_" + str(iPt) + "_" + str(iRho), "Var_Rho_" + str(iPt) + "_" + str(iRho), (iRho)) lRhoArray = r.RooArgList() - lNCount=0 - for pRVar in range(0,self._poly_degree_rho+1): + lNCount = 0 + for pRVar in range(0, self._poly_degree_rho + 1): lTmpArray = r.RooArgList() - for pVar in range(0,self._poly_degree_pt+1): - if lNCount == 0: - lTmpArray.add(iQCD); # for the very first constant (e.g. p0r0), just set that to 1 - else: + for pVar in range(0, self._poly_degree_pt + 1): + if lNCount == 0: + lTmpArray.add(iQCD); # for the very first constant (e.g. p0r0), just set that to 1 + else: print "lNCount = " + str(lNCount) lTmpArray.add(iVars[lNCount]) - lNCount=lNCount+1 - pLabel="Var_Pol_Bin_"+str(round(iPt,2))+"_"+str(round(iRho,3))+"_"+str(pRVar) - pPol = r.RooPolyVar(pLabel,pLabel,lPt,lTmpArray) + lNCount = lNCount + 1 + pLabel = "Var_Pol_Bin_" + str(round(iPt, 2)) + "_" + str(round(iRho, 3)) + "_" + str(pRVar) + pPol = r.RooPolyVar(pLabel, pLabel, lPt, lTmpArray) print "pPol:" print pPol.Print() lRhoArray.add(pPol); self._all_vars.append(pPol) - lLabel="Var_RhoPol_Bin_"+str(round(iPt,2))+"_"+str(round(iRho,3)) - lRhoPol = r.RooPolyVar(lLabel,lLabel,lRho,lRhoArray) - self._all_vars.extend([lPt,lRho,lRhoPol]) + lLabel = "Var_RhoPol_Bin_" + str(round(iPt, 2)) + "_" + str(round(iRho, 3)) + lRhoPol = r.RooPolyVar(lLabel, lLabel, lRho, lRhoArray) + self._all_vars.extend([lPt, lRho, lRhoPol]) return lRhoPol - - def buildPolynomialArray(self, iVars,iNVar0,iNVar1,iLabel0,iLabel1,iXMin0,iXMax0): + def buildPolynomialArray(self, iVars, iNVar0, iNVar1, iLabel0, iLabel1, iXMin0, iXMax0): print "---- [buildPolynomialArray]" ## form of polynomial @@ -525,128 +647,148 @@ def buildPolynomialArray(self, iVars,iNVar0,iNVar1,iLabel0,iLabel1,iXMin0,iXMax0 r1p2 = 2.2058e-04 +/- 1.10e-09 r2p2 = -2.2425e-07 +/- 1.64e-12 ''' - value = [ 0., - -3.7215e-03, - 2.4063e-06, - -2.1088e-01, - 3.6847e-05, - -3.8415e-07, - -8.5276e-02, - 2.2058e-04, - -2.2425e-07] + value = [0., + -3.7215e-03, + 2.4063e-06, + -2.1088e-01, + 3.6847e-05, + -3.8415e-07, + -8.5276e-02, + 2.2058e-04, + -2.2425e-07] error = [iXMax0, - 1.71e-08, - 2.76e-11, - 2.72e-06, - 4.66e-09, - 7.23e-12, - 6.90e-07, - 1.10e-09, - 1.64e-12] - - for i0 in range(iNVar0+1): - for i1 in range(iNVar1+1): - pVar = iLabel1+str(i1)+iLabel0+str(i0); - if self._freeze : - - start = value [i0*3+i1] - pXMin = value [i0*3+i1]-error[i0*3+i1] - pXMax = value [i0*3+i1]+error[i0*3+i1] - - else: + 1.71e-08, + 2.76e-11, + 2.72e-06, + 4.66e-09, + 7.23e-12, + 6.90e-07, + 1.10e-09, + 1.64e-12] + + for i0 in range(iNVar0 + 1): + for i1 in range(iNVar1 + 1): + pVar = iLabel1 + str(i1) + iLabel0 + str(i0); + if self._freeze: + + start = value[i0 * 3 + i1] + pXMin = value[i0 * 3 + i1] - error[i0 * 3 + i1] + pXMax = value[i0 * 3 + i1] + error[i0 * 3 + i1] + + else: start = 0.0 pXMin = iXMin0 pXMax = iXMax0 - - pRooVar = r.RooRealVar(pVar,pVar,0.0,pXMin,pXMax) - #print("======== here i0 %s i1 %s"%(i0,i1)) + + pRooVar = r.RooRealVar(pVar, pVar, 0.0, pXMin, pXMax) + # print("======== here i0 %s i1 %s"%(i0,i1)) print pVar - #print(" is : %s +/- %s"%(value[i0*3+i1],error[i0*3+i1])) + # print(" is : %s +/- %s"%(value[i0*3+i1],error[i0*3+i1])) iVars.append(pRooVar) self._all_vars.append(pRooVar) - def GetWorkspaceInputs(self, pass_histograms, fail_histograms,iBin): + def GetWorkspaceInputs(self, pass_histograms, fail_histograms, iBin): - roocategories = r.RooCategory("sample","sample") - roocategories.defineType("pass",1) - roocategories.defineType("fail",0) - data_rdh_pass = r.RooDataHist("data_obs_pass_"+iBin,"data_obs_pass_"+iBin,r.RooArgList(self._lMSD),pass_histograms["data_obs"]) - data_rdh_fail = r.RooDataHist("data_obs_fail_"+iBin,"data_obs_fail_"+iBin,r.RooArgList(self._lMSD), fail_histograms["data_obs"]) - data_rdh_comb = r.RooDataHist("comb_data_obs","comb_data_obs",r.RooArgList(self._lMSD),r.RooFit.Index(roocategories),r.RooFit.Import("pass",data_rdh_pass),r.RooFit.Import("fail",data_rdh_fail)) + roocategories = r.RooCategory("sample", "sample") + roocategories.defineType("pass", 1) + roocategories.defineType("fail", 0) + data_rdh_pass = r.RooDataHist("data_obs_pass_" + iBin, "data_obs_pass_" + iBin, r.RooArgList(self._lMSD), + pass_histograms["data_obs"]) + data_rdh_fail = r.RooDataHist("data_obs_fail_" + iBin, "data_obs_fail_" + iBin, r.RooArgList(self._lMSD), + fail_histograms["data_obs"]) + data_rdh_comb = r.RooDataHist("comb_data_obs", "comb_data_obs", r.RooArgList(self._lMSD), + r.RooFit.Index(roocategories), r.RooFit.Import("pass", data_rdh_pass), + r.RooFit.Import("fail", data_rdh_fail)) roofit_shapes = {} for sample in ["wqq", "zqq", "qcd", "tqq"]: - roofit_shapes[sample] = self.GetRoofitHistObjects(pass_histograms[sample], fail_histograms[sample], sample, iBin) - - total_pdf_pass = r.RooAddPdf("tot_pass"+iBin,"tot_pass"+iBin,r.RooArgList(roofit_shapes["qcd"]["pass_epdf"])) - total_pdf_fail = r.RooAddPdf("tot_fail"+iBin,"tot_fail"+iBin,r.RooArgList(roofit_shapes["qcd"]["fail_epdf"])) - ewk_pdf_pass = r.RooAddPdf("ewk_pass"+iBin,"ewk_pass"+iBin,r.RooArgList(roofit_shapes["wqq"]["pass_epdf"],roofit_shapes["zqq"]["pass_epdf"], roofit_shapes["tqq"]["pass_epdf"])) - ewk_pdf_fail = r.RooAddPdf("ewk_fail"+iBin,"ewk_fail"+iBin,r.RooArgList(roofit_shapes["wqq"]["fail_epdf"],roofit_shapes["zqq"]["fail_epdf"], roofit_shapes["tqq"]["fail_epdf"])) - - total_simulpdf = r.RooSimultaneous("tot","tot",roocategories) - total_simulpdf.addPdf(total_pdf_pass,"pass") - total_simulpdf.addPdf(total_pdf_fail,"fail") - self._all_data.extend([data_rdh_pass,data_rdh_fail]) - self._all_shapes.extend([total_pdf_pass,total_pdf_fail,ewk_pdf_pass,ewk_pdf_fail]) + roofit_shapes[sample] = self.GetRoofitHistObjects(pass_histograms[sample], fail_histograms[sample], sample, + iBin) + + total_pdf_pass = r.RooAddPdf("tot_pass" + iBin, "tot_pass" + iBin, + r.RooArgList(roofit_shapes["qcd"]["pass_epdf"])) + total_pdf_fail = r.RooAddPdf("tot_fail" + iBin, "tot_fail" + iBin, + r.RooArgList(roofit_shapes["qcd"]["fail_epdf"])) + ewk_pdf_pass = r.RooAddPdf("ewk_pass" + iBin, "ewk_pass" + iBin, + r.RooArgList(roofit_shapes["wqq"]["pass_epdf"], roofit_shapes["zqq"]["pass_epdf"], + roofit_shapes["tqq"]["pass_epdf"])) + ewk_pdf_fail = r.RooAddPdf("ewk_fail" + iBin, "ewk_fail" + iBin, + r.RooArgList(roofit_shapes["wqq"]["fail_epdf"], roofit_shapes["zqq"]["fail_epdf"], + roofit_shapes["tqq"]["fail_epdf"])) + + total_simulpdf = r.RooSimultaneous("tot", "tot", roocategories) + total_simulpdf.addPdf(total_pdf_pass, "pass") + total_simulpdf.addPdf(total_pdf_fail, "fail") + self._all_data.extend([data_rdh_pass, data_rdh_fail]) + self._all_shapes.extend([total_pdf_pass, total_pdf_fail, ewk_pdf_pass, ewk_pdf_fail]) ## find out which to make global ## RooDataHist (data), then RooHistPdf of each electroweak # Previous return values 2 and 3 (RooAbsPdf (qcd,ewk)) removed by David on 19/1/2017, because they don't seem to be used. return [ - data_rdh_pass, - data_rdh_fail, - #{"qcd":total_pdf_pass, "ewk":ewk_pdf_pass}, - #{"qcd":total_pdf_fail, "ewk":ewk_pdf_fail}, - {"wqq":roofit_shapes["wqq"]["pass_rdh"], "zqq":roofit_shapes["zqq"]["pass_rdh"], "tqq":roofit_shapes["tqq"]["pass_rdh"]}, - {"wqq":roofit_shapes["wqq"]["fail_rdh"], "zqq":roofit_shapes["zqq"]["fail_rdh"], "tqq":roofit_shapes["tqq"]["fail_rdh"]}, + data_rdh_pass, + data_rdh_fail, + # {"qcd":total_pdf_pass, "ewk":ewk_pdf_pass}, + # {"qcd":total_pdf_fail, "ewk":ewk_pdf_fail}, + {"wqq": roofit_shapes["wqq"]["pass_rdh"], "zqq": roofit_shapes["zqq"]["pass_rdh"], + "tqq": roofit_shapes["tqq"]["pass_rdh"]}, + {"wqq": roofit_shapes["wqq"]["fail_rdh"], "zqq": roofit_shapes["zqq"]["fail_rdh"], + "tqq": roofit_shapes["tqq"]["fail_rdh"]}, ] # Get (RooHistPdf, RooExtendPdf, RooDataHist) for a pair of pass/fail histograms # - The RooExtendPdfs are coupled via their normalizations, N*eff or N*(1-eff). def GetRoofitHistObjects(self, hist_pass, hist_fail, label="w", category="_cat0"): # normalization - total_norm = r.RooRealVar(label+"norm"+category, label+"norm"+category, (hist_pass.Integral()+hist_fail.Integral()), 0., 5.*(hist_pass.Integral()+hist_fail.Integral())) - pass_norm = r.RooFormulaVar(label+"fpass"+category, label+"norm"+category+"*(veff)", r.RooArgList(total_norm,self._lEff)) - fail_norm = r.RooFormulaVar(label+"fqail"+category, label+"norm"+category+"*(1-veff)", r.RooArgList(total_norm,self._lEff)) + total_norm = r.RooRealVar(label + "norm" + category, label + "norm" + category, + (hist_pass.Integral() + hist_fail.Integral()), 0., + 5. * (hist_pass.Integral() + hist_fail.Integral())) + pass_norm = r.RooFormulaVar(label + "fpass" + category, label + "norm" + category + "*(veff)", + r.RooArgList(total_norm, self._lEff)) + fail_norm = r.RooFormulaVar(label + "fqail" + category, label + "norm" + category + "*(1-veff)", + r.RooArgList(total_norm, self._lEff)) # shapes - pass_rdh = r.RooDataHist(label+"_pass_"+category, label+"_pass_"+category, r.RooArgList(self._lMSD),hist_pass) - fail_rdh = r.RooDataHist(label+"_fail_"+category, label+"_fail_"+category, r.RooArgList(self._lMSD),hist_fail) - pass_rhp = r.RooHistPdf (label+"passh"+category, label+"passh"+category, r.RooArgList(self._lShift), r.RooArgList(self._lMSD), pass_rdh, 0) - fail_rhp = r.RooHistPdf (label+"failh"+category, label+"failh"+category, r.RooArgList(self._lShift), r.RooArgList(self._lMSD), fail_rdh, 0) + pass_rdh = r.RooDataHist(label + "_pass_" + category, label + "_pass_" + category, r.RooArgList(self._lMSD), + hist_pass) + fail_rdh = r.RooDataHist(label + "_fail_" + category, label + "_fail_" + category, r.RooArgList(self._lMSD), + hist_fail) + pass_rhp = r.RooHistPdf(label + "passh" + category, label + "passh" + category, r.RooArgList(self._lShift), + r.RooArgList(self._lMSD), pass_rdh, 0) + fail_rhp = r.RooHistPdf(label + "failh" + category, label + "failh" + category, r.RooArgList(self._lShift), + r.RooArgList(self._lMSD), fail_rdh, 0) # extended likelihood from normalization and shape above - pass_epdf = r.RooExtendPdf(label+"_passe_" +category, label+"pe" +category, pass_rhp, pass_norm) - fail_epdf = r.RooExtendPdf(label+"_faile_" +category, label+"fe" +category, fail_rhp, fail_norm) + pass_epdf = r.RooExtendPdf(label + "_passe_" + category, label + "pe" + category, pass_rhp, pass_norm) + fail_epdf = r.RooExtendPdf(label + "_faile_" + category, label + "fe" + category, fail_rhp, fail_norm) - #lHist = [pass_pdf,fail_rhp,pass_epdf,fail_epdf,pass_rdh,fail_rdh] + # lHist = [pass_pdf,fail_rhp,pass_epdf,fail_epdf,pass_rdh,fail_rdh] return_dict = { - "pass_rdh":pass_rdh, - "fail_rdh":fail_rdh, - "pass_pdf":pass_rhp, - "fail_pdf":fail_rhp, - "pass_epdf":pass_epdf, - "fail_epdf":fail_epdf + "pass_rdh": pass_rdh, + "fail_rdh": fail_rdh, + "pass_pdf": pass_rhp, + "fail_pdf": fail_rhp, + "pass_epdf": pass_epdf, + "fail_epdf": fail_epdf } self._all_vars.extend([total_norm, pass_norm, fail_norm]) self._all_shapes.extend(return_dict.values()) return return_dict - def GetSignalInputs(self,iHP,iHF,iBin): + def GetSignalInputs(self, iHP, iHF, iBin): # get signals - lPSigs = {} - lFSigs = {} + lPSigs = {} + lFSigs = {} for signal_name in self._signal_names: - roofit_shapes = self.GetRoofitHistObjects(iHP[signal_name], iHF[signal_name],signal_name,iBin) + roofit_shapes = self.GetRoofitHistObjects(iHP[signal_name], iHF[signal_name], signal_name, iBin) lPSigs[signal_name] = roofit_shapes["pass_rdh"] lFSigs[signal_name] = roofit_shapes["fail_rdh"] - return (lPSigs,lFSigs) + return (lPSigs, lFSigs) - - #def MakeWorkspace(self,iOutput,iDatas,iFuncs,iVars,iCat="cat0",iShift=True): + # def MakeWorkspace(self,iOutput,iDatas,iFuncs,iVars,iCat="cat0",iShift=True): def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=True, do_syst=True, pt_val=500.): print "Making workspace " + "w_" + str(category) - workspace = r.RooWorkspace("w_"+str(category)) + workspace = r.RooWorkspace("w_" + str(category)) # get the pT bin iPt = category[-1:] @@ -656,7 +798,7 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T process = import_object.GetName().split('_')[0] cat = import_object.GetName().split('_')[1] mass = 0 - systematics = ['JES', 'JER', 'trigger', 'mcstat','Pu'] + systematics = ['JES', 'JER', 'trigger', 'mcstat', 'Pu'] if do_syst and ('tqq' in process or 'wqq' in process or 'zqq' in process or 'hqq' in process): # get systematic histograms hout = [] @@ -666,16 +808,24 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T matchingString = '' if self._remove_unmatched and ('wqq' in process or 'zqq' in process): matchingString = '_matched' - if self._inputfile_loose is not None and ('wqq' in process or 'zqq' in process) and 'pass' in cat: - tmph = self._inputfile_loose.Get(process + '_' + cat + matchingString).Clone(process + '_' + cat) + if self._inputfile_loose is not None and ( + 'wqq' in process or 'zqq' in process) and 'pass' in cat: + tmph = self._inputfile_loose.Get(process + '_' + cat + matchingString).Clone( + process + '_' + cat) tmph_up = self._inputfile_loose.Get(process + '_' + cat + matchingString).Clone( process + '_' + cat + '_' + syst + 'Up') tmph_down = self._inputfile_loose.Get(process + '_' + cat + matchingString).Clone( process + '_' + cat + '_' + syst + 'Down') - tmph.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, iPt)) - tmph_up.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, iPt)) - tmph_down.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, iPt)) - else: + tmph.Scale( + GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, + iPt)) + tmph_up.Scale( + GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, + iPt)) + tmph_down.Scale( + GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, + iPt)) + else: tmph = self._inputfile.Get(process + '_' + cat + matchingString).Clone(process + '_' + cat) tmph_up = self._inputfile.Get(process + '_' + cat + matchingString).Clone( process + '_' + cat + '_' + syst + 'Up') @@ -685,33 +835,40 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T tmph_up.Scale(GetSF(process, cat, self._inputfile)) tmph_down.Scale(GetSF(process, cat, self._inputfile)) tmph_mass = tools.proj('cat', str(iPt), tmph, self._mass_nbins, self._mass_lo, self._mass_hi) - tmph_mass_up = tools.proj('cat', str(iPt), tmph_up, self._mass_nbins, self._mass_lo, self._mass_hi) + tmph_mass_up = tools.proj('cat', str(iPt), tmph_up, self._mass_nbins, self._mass_lo, + self._mass_hi) tmph_mass_down = tools.proj('cat', str(iPt), tmph_down, self._mass_nbins, self._mass_lo, - self._mass_hi) + self._mass_hi) for i in range(1, tmph_mass_up.GetNbinsX() + 1): mcstatup = tmph_mass_up.GetBinContent(i) + tmph_mass_up.GetBinError(i) mcstatdown = max(0., tmph_mass_down.GetBinContent(i) - tmph_mass_down.GetBinError(i)) tmph_mass_up.SetBinContent(i, mcstatup) tmph_mass_down.SetBinContent(i, mcstatdown) tmph_mass.SetName(import_object.GetName()) - tmph_mass_up.SetName(import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Up') - tmph_mass_down.SetName(import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Down') + tmph_mass_up.SetName( + import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Up') + tmph_mass_down.SetName( + import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Down') histDict[import_object.GetName()] = tmph_mass - histDict[import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Up'] = tmph_mass_up + histDict[import_object.GetName() + '_' + import_object.GetName().replace('_', + '') + syst + 'Up'] = tmph_mass_up histDict[ - import_object.GetName() + '_' + import_object.GetName().replace('_', '') + syst + 'Down'] = tmph_mass_down + import_object.GetName() + '_' + import_object.GetName().replace('_', + '') + syst + 'Down'] = tmph_mass_down if 'tqq' in process: hout.append(tmph_mass) # hout.append(tmph_mass_up) # hout.append(tmph_mass_down) else: + print process, cat, syst tmph_up = self._inputfile.Get(process + '_' + cat + '_' + syst + 'Up').Clone() tmph_down = self._inputfile.Get(process + '_' + cat + '_' + syst + 'Down').Clone() tmph_up.Scale(GetSF(process, cat, self._inputfile)) tmph_down.Scale(GetSF(process, cat, self._inputfile)) - tmph_mass_up = tools.proj('cat', str(iPt), tmph_up, self._mass_nbins, self._mass_lo, self._mass_hi) + tmph_mass_up = tools.proj('cat', str(iPt), tmph_up, self._mass_nbins, self._mass_lo, + self._mass_hi) tmph_mass_down = tools.proj('cat', str(iPt), tmph_down, self._mass_nbins, self._mass_lo, - self._mass_hi) + self._mass_hi) tmph_mass_up.SetName(import_object.GetName() + '_' + syst + 'Up') tmph_mass_down.SetName(import_object.GetName() + '_' + syst + 'Down') hout.append(tmph_mass_up) @@ -728,12 +885,13 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T rhoVal = r.TMath.Log(massVal * massVal / pt_val / pt_val) if self._blind and massVal > self._mass_blind_lo and massVal < self._mass_blind_hi: print "blinding signal region for %s, mass bin [%i,%i] " % ( - h.GetName(), h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) + h.GetName(), h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) h.SetBinContent(i, 0.) h.SetBinError(i, 0.) if rhoVal < self._rho_lo or rhoVal > self._rho_hi: print "removing rho = %.2f for %s, pt_val = %.2f, mass bin [%i,%i]" % ( - rhoVal, h.GetName(), pt_val, h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) + rhoVal, h.GetName(), pt_val, h.GetXaxis().GetBinLowEdge(i), + h.GetXaxis().GetBinUpEdge(i)) h.SetBinContent(i, 0.) h.SetBinError(i, 0.) tmprdh = r.RooDataHist(h.GetName(), h.GetName(), r.RooArgList(self._lMSD), h) @@ -747,26 +905,29 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T mass = 80. elif process == 'zqq': mass = 91. - elif 'hqq' in process : + elif 'hqq' in process: mass = float(process[-3:]) # hqq125 -> 125 elif 'Pbb' in process: mass = float(process.split('_')[-1]) # Pbb_75 -> 75 # get the matched and unmatched hist - - if self._inputfile_loose is not None and ('wqq' in process or 'zqq' in process) and 'pass' in cat: + + if self._inputfile_loose is not None and ('wqq' in process or 'zqq' in process) and 'pass' in cat: tmph_matched = self._inputfile_loose.Get(process + '_' + cat + '_matched').Clone() tmph_unmatched = self._inputfile_loose.Get(process + '_' + cat + '_unmatched').Clone() - tmph_matched.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, iPt)) - tmph_unmatched.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, False)) # doesn't matter if removing unmatched so just remove that option + tmph_matched.Scale( + GetSF(process, cat, self._inputfile, self._inputfile_loose, self._remove_unmatched, iPt)) + tmph_unmatched.Scale(GetSF(process, cat, self._inputfile, self._inputfile_loose, + False)) # doesn't matter if removing unmatched so just remove that option else: tmph_matched = self._inputfile.Get(process + '_' + cat + '_matched').Clone() tmph_unmatched = self._inputfile.Get(process + '_' + cat + '_unmatched').Clone() tmph_matched.Scale(GetSF(process, cat, self._inputfile)) tmph_unmatched.Scale(GetSF(process, cat, self._inputfile)) - tmph_mass_matched = tools.proj('cat', str(iPt), tmph_matched, self._mass_nbins, self._mass_lo, self._mass_hi) + tmph_mass_matched = tools.proj('cat', str(iPt), tmph_matched, self._mass_nbins, self._mass_lo, + self._mass_hi) tmph_mass_unmatched = tools.proj('cat', str(iPt), tmph_unmatched, self._mass_nbins, self._mass_lo, - self._mass_hi) + self._mass_hi) # smear/shift the matched hist_container = hist([mass], [tmph_mass_matched]) @@ -784,10 +945,10 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T s_mc_err = 0.607 mass_shift = m_data / m_mc mass_shift_unc = math.sqrt((m_data_err / m_data) * (m_data_err / m_data) + (m_mc_err / m_mc) * ( - m_mc_err / m_mc)) * 10. # (10 sigma shift) + m_mc_err / m_mc)) * 10. # (10 sigma shift) res_shift = s_data / s_mc res_shift_unc = math.sqrt((s_data_err / s_data) * (s_data_err / s_data) + (s_mc_err / s_mc) * ( - s_mc_err / s_mc)) * 2. # (2 sigma shift) + s_mc_err / s_mc)) * 2. # (2 sigma shift) # get new central value shift_val = mass - mass * mass_shift tmp_shifted_h = hist_container.shift(tmph_mass_matched, shift_val) @@ -796,22 +957,22 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T tmp_smeared_h = hist_container.smear(tmp_shifted_h[0], smear_val) hmatched_new_central = tmp_smeared_h[0] if smear_val <= 0: hmatched_new_central = tmp_smeared_h[1] - - if re.match('zqq',tmph_mass_matched.GetName()): + + if re.match('zqq', tmph_mass_matched.GetName()): print tmph_mass_matched.GetName() print mass_shift print mass_shift_unc print shift_val print "before shift", tmph_mass_matched.Integral() print "after shift", tmp_shifted_h[0].Integral() - + print res_shift - print res_shift_unc - print smear_val + print res_shift_unc + print smear_val print "before smear", tmph_mass_matched.Integral() print "after smear", hmatched_new_central.Integral() - #sys.exit() - + # sys.exit() + # get shift up/down shift_unc = mass * mass_shift * mass_shift_unc hmatchedsys_shift = hist_container.shift(hmatched_new_central, mass * mass_shift_unc) @@ -840,11 +1001,12 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T rhoVal = r.TMath.Log(massVal * massVal / pt_val / pt_val) if self._blind and massVal > self._mass_blind_lo and massVal < self._mass_blind_hi: print "blinding signal region for %s, mass bin [%i,%i] " % ( - h.GetName(), h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) + h.GetName(), h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) h.SetBinContent(i, 0.) if rhoVal < self._rho_lo or rhoVal > self._rho_hi: print "removing rho = %.2f for %s, pt_val = %.2f, mass bin [%i,%i]" % ( - rhoVal, h.GetName(), pt_val, h.GetXaxis().GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i)) + rhoVal, h.GetName(), pt_val, h.GetXaxis().GetBinLowEdge(i), + h.GetXaxis().GetBinUpEdge(i)) h.SetBinContent(i, 0.) tmprdh = r.RooDataHist(h.GetName(), h.GetName(), r.RooArgList(self._lMSD), h) getattr(workspace, 'import')(tmprdh, r.RooFit.RecycleConflictNodes()) @@ -852,23 +1014,24 @@ def MakeWorkspace(self, output_path, import_objects, category="cat0", do_shift=T pName = h.GetName().replace("scale", "scalept") tmprdh = r.RooDataHist(pName, pName, r.RooArgList(self._lMSD), h) getattr(workspace, 'import')(tmprdh, r.RooFit.RecycleConflictNodes()) - #pName = h.GetName().replace("scale", "shiftMH") - #tmprdh = r.RooDataHist(pName, pName, r.RooArgList(self._lMSD), h) - #getattr(workspace, 'import')(tmprdh, r.RooFit.RecycleConflictNodes()) + # pName = h.GetName().replace("scale", "shiftMH") + # tmprdh = r.RooDataHist(pName, pName, r.RooArgList(self._lMSD), h) + # getattr(workspace, 'import')(tmprdh, r.RooFit.RecycleConflictNodes()) # validation self._outfile_validation.cd() h.Write() else: print "Importing {}".format(import_object.GetName()) - getattr(workspace,'import')(import_object, r.RooFit.RecycleConflictNodes()) + getattr(workspace, 'import')(import_object, r.RooFit.RecycleConflictNodes()) if category.find("pass_cat1") == -1: - workspace.writeToFile(output_path,False) + workspace.writeToFile(output_path, False) else: - workspace.writeToFile(output_path) + workspace.writeToFile(output_path) workspace.Print() # workspace.writeToFile(output_path) + ############################################################################## ############################################################################## #### E N D O F C L A S S @@ -886,13 +1049,13 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ fail_hists_bkg = {} background_names = ["wqq", "zqq", "qcd", "tqq"] for i, bkg in enumerate(background_names): - if bkg=='qcd': + if bkg == 'qcd': qcd_fail = f.Get('qcd_fail') qcd_fail.Scale(1. / scale) qcd_fail.SetBinContent(13, 4, ( - qcd_fail.GetBinContent(12, 4) + qcd_fail.GetBinContent(14, 4)) / 2.) # REMOVE HIGH WEIGHT EVENT BIN + qcd_fail.GetBinContent(12, 4) + qcd_fail.GetBinContent(14, 4)) / 2.) # REMOVE HIGH WEIGHT EVENT BIN qcd_fail.SetBinError(13, 4, ( - qcd_fail.GetBinError(12, 4) + qcd_fail.GetBinError(14, 4)) / 2.) # REMOVE HIGH WEIGHT EVENT BIN + qcd_fail.GetBinError(12, 4) + qcd_fail.GetBinError(14, 4)) / 2.) # REMOVE HIGH WEIGHT EVENT BIN if useQCD: qcd_pass = f.Get('qcd_pass').Clone() qcd_pass.Scale(1. / scale) @@ -904,7 +1067,8 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ qcd_fail_integral = 0 for i in range(1, qcd_pass_real.GetNbinsX() + 1): for j in range(1, qcd_pass_real.GetNbinsY() + 1): - if qcd_pass_real.GetXaxis().GetBinCenter(i) > mass_range[0] and qcd_pass_real.GetXaxis().GetBinCenter( + if qcd_pass_real.GetXaxis().GetBinCenter(i) > mass_range[ + 0] and qcd_pass_real.GetXaxis().GetBinCenter( i) < mass_range[1]: qcd_pass_real_integral += qcd_pass_real.GetBinContent(i, j) qcd_fail_integral += qcd_fail.GetBinContent(i, j) @@ -913,7 +1077,7 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ fail_hists_bkg["qcd"] = qcd_fail print 'qcd pass integral', qcd_pass.Integral() print 'qcd fail integral', qcd_fail.Integral() - elif (fLoose is not None) and (bkg=='wqq' or bkg=='zqq'): + elif (fLoose is not None) and (bkg == 'wqq' or bkg == 'zqq'): hpass_tmp = fLoose.Get(bkg + '_pass').Clone() hfail_tmp = f.Get(bkg + '_fail').Clone() hpass_tmp.Scale(1. / scale) @@ -921,7 +1085,7 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ hpass_tmp.Scale(GetSF(bkg, 'pass', f, fLoose)) hfail_tmp.Scale(GetSF(bkg, 'fail', f)) pass_hists_bkg[bkg] = hpass_tmp - fail_hists_bkg[bkg] = hfail_tmp + fail_hists_bkg[bkg] = hfail_tmp else: hpass_tmp = f.Get(bkg + '_pass').Clone() hfail_tmp = f.Get(bkg + '_fail').Clone() @@ -936,9 +1100,9 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ pass_hists_sig = {} fail_hists_sig = {} # for Pbb - #masses = [50, 75, 125, 100, 150, 250, 300] - #sigs = ['Pbb_'] - #signal_names = [] + # masses = [50, 75, 125, 100, 150, 250, 300] + # sigs = ['Pbb_'] + # signal_names = [] # for Hbb masses = [125] # 50,75,125,100,150,200,250,300] sigs = ["hqq", "zhqq", "whqq", "vbfhqq", "tthqq"] @@ -961,50 +1125,53 @@ def LoadHistograms(f, pseudo, blind, useQCD, scale, r_signal, mass_range, blind_ fail_hists_sig[sig + str(mass)] = failhist signal_names.append(sig + str(mass)) - if pseudo: + if pseudo: for i, bkg in enumerate(background_names): - if i==0: + if i == 0: pass_hists["data_obs"] = pass_hists_bkg[bkg].Clone('data_obs_pass') fail_hists["data_obs"] = fail_hists_bkg[bkg].Clone('data_obs_fail') - else: + else: pass_hists["data_obs"].Add(pass_hists_bkg[bkg]) fail_hists["data_obs"].Add(fail_hists_bkg[bkg]) for i, signal in enumerate(signal_names): - pass_hists["data_obs"].Add(pass_hists_sig[signal],r_signal) - fail_hists["data_obs"].Add(fail_hists_sig[signal],r_signal) + pass_hists["data_obs"].Add(pass_hists_sig[signal], r_signal) + fail_hists["data_obs"].Add(fail_hists_sig[signal], r_signal) else: pass_hists["data_obs"] = f.Get('data_obs_pass') fail_hists["data_obs"] = f.Get('data_obs_fail') - pass_hists.update(pass_hists_bkg) pass_hists.update(pass_hists_sig) fail_hists.update(fail_hists_bkg) fail_hists.update(fail_hists_sig) - + for histogram in (pass_hists.values() + fail_hists.values()): - for i in range(1,histogram.GetNbinsX()+1): - for j in range(1,histogram.GetNbinsY()+1): + for i in range(1, histogram.GetNbinsX() + 1): + for j in range(1, histogram.GetNbinsY() + 1): massVal = histogram.GetXaxis().GetBinCenter(i) ptVal = histogram.GetYaxis().GetBinLowEdge(j) + histogram.GetYaxis().GetBinWidth(j) * 0.3 rhoVal = r.TMath.Log(massVal * massVal / ptVal / ptVal) - if blind and histogram.GetXaxis().GetBinCenter(i) > blind_range[0] and histogram.GetXaxis().GetBinCenter(i) < blind_range[1]: - print "blinding signal region for %s, mass bin [%i,%i] "%(histogram.GetName(),histogram.GetXaxis().GetBinLowEdge(i),histogram.GetXaxis().GetBinUpEdge(i)) - histogram.SetBinContent(i,j,0.) + if blind and histogram.GetXaxis().GetBinCenter(i) > blind_range[ + 0] and histogram.GetXaxis().GetBinCenter(i) < blind_range[1]: + print "blinding signal region for %s, mass bin [%i,%i] " % ( + histogram.GetName(), histogram.GetXaxis().GetBinLowEdge(i), histogram.GetXaxis().GetBinUpEdge(i)) + histogram.SetBinContent(i, j, 0.) if rhoVal < rho_range[0] or rhoVal > rho_range[1]: print "removing rho = %.2f for %s, pt bin [%i, %i], mass bin [%i,%i]" % ( - rhoVal, histogram.GetName(), histogram.GetYaxis().GetBinLowEdge(j), histogram.GetYaxis().GetBinUpEdge(j), - histogram.GetXaxis().GetBinLowEdge(i), histogram.GetXaxis().GetBinUpEdge(i)) + rhoVal, histogram.GetName(), histogram.GetYaxis().GetBinLowEdge(j), + histogram.GetYaxis().GetBinUpEdge(j), + histogram.GetXaxis().GetBinLowEdge(i), histogram.GetXaxis().GetBinUpEdge(i)) histogram.SetBinContent(i, j, 0.) - histogram.SetDirectory(0) + histogram.SetDirectory(0) - # print "lengths = ", len(pass_hists), len(fail_hists) + # print "lengths = ", len(pass_hists), len(fail_hists) # print pass_hists; # print fail_hists; - return (pass_hists,fail_hists) + return (pass_hists, fail_hists) + -def GetSF(process, cat, f, fLoose=None, removeUnmatched=False, iPt=-1): +def GetSF(process, cat, f, fLoose=None, removeUnmatched=False, iPt=-1): SF = 1 print process, cat if 'hqq' in process or 'zqq' in process or 'Pbb' in process: @@ -1034,9 +1201,9 @@ def GetSF(process, cat, f, fLoose=None, removeUnmatched=False, iPt=-1): else: passInt = f.Get(process + '_pass' + matchingString).Integral() passIntLoose = fLoose.Get(process + '_pass' + matchingString).Integral() - SF *= passInt/passIntLoose + SF *= passInt / passIntLoose if 'zqq' in process: - print passInt/passIntLoose + print passInt / passIntLoose # remove cross section from MH=125 signal templates (template normalized to luminosity*efficiency*acceptance) ## if process=='hqq125': ## SF *= 1./48.85*5.824E-01 @@ -1048,17 +1215,18 @@ def GetSF(process, cat, f, fLoose=None, removeUnmatched=False, iPt=-1): ## SF *= 1./(3.782*5.824E-01) ## elif process=='tthqq': ## SF *= 1./(5.071E-01*5.824E-01) - - #if 'zqq' in process: + + # if 'zqq' in process: # print SF # sys.exit() return SF -def reset(w,fr,exclude=None): + +def reset(w, fr, exclude=None): for p in RootIterator(fr.floatParsFinal()): if exclude is not None and exclude in p.GetName(): continue if w.var(p.GetName()): - print 'setting %s = %e +/- %e from %s'%(p.GetName(), p.getVal(), p.getError(),fr.GetName()) + print 'setting %s = %e +/- %e from %s' % (p.GetName(), p.getVal(), p.getError(), fr.GetName()) w.var(p.GetName()).setVal(p.getVal()) w.var(p.GetName()).setError(p.getError()) return True