Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WZ at 5 TeV #5

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
396 changes: 396 additions & 0 deletions FidRyTotR.py

Large diffs are not rendered by default.

40 changes: 34 additions & 6 deletions framework/AnalysisCreator.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,23 @@ def AddSelection(self, selection):
for l in lines:
self.selection += '%s%s\n'%(' '*addNSpaces, l)

def AddLoopCode(self, code):
code = code.replace('\t', ' ')
lines = code.split('\n')
for l in lines:
ltemp = "%s"%l
lorig = "%s"%l
ltemp = ltemp.replace(' ', '')
if ltemp != '': break
nspaces = 0
while len(lorig) >0 and lorig[0] == ' ':
nspaces += 1
lorig = lorig[1:]
addNSpaces = 6-nspaces
self.loopcode = ''
for l in lines:
self.loopcode += '%s%s\n'%(' '*addNSpaces, l)

def AddSyst(self, syst):
if isinstance(syst, list): self.syst += syst
elif syst == '': return
Expand All @@ -30,6 +47,10 @@ def AddSyst(self, syst):
def AddHeader(self, h):
self.header += h

def AddSampleOptions(self, h):
self.sampleOptions += h
if not self.sampleOptions.endswith('\n'): self.sampleOptions += '\n'

def AddInit(self, t):
self.init += t

Expand Down Expand Up @@ -61,13 +82,14 @@ def AddHisto(self, var, hname, nbins, b0 = 0, bN = 0, bins = [], weight = '', sy
if write: self.fillLine.append(fillLine)
else : return fillLine

def AddExpr(self, ename, var, expr):
def AddExpr(self, ename, var, expr, goAfter = False):
if not isinstance(var, list): var = [var]
for v in var:
if v == '': continue
st = 'fun.GetValue(t, "%s", syst)'%v
expr = re.sub(r'\b%s\b'%v, st, expr)
self.expr[ename] = expr
self.exprorder[ename] = goAfter

def CraftCut(self, cut):
return cut
Expand Down Expand Up @@ -118,9 +140,10 @@ def GetAnalysisTemplate(self):
body += 'import os,sys\nsys.path.append(os.path.abspath(__file__).rsplit("/xuAnalysis/",1)[0]+"/xuAnalysis/")\n'
body += 'from framework.analysis import analysis\nimport framework.functions as fun\nfrom ROOT import TLorentzVector\n\n'
body += self.header
body += '\nsystematics = ' + str(self.syst) + '\n'
body += '%s'%self.sampleOptions
body += 'class %s(analysis):\n'%self.analysisName
body += ' def init(self):\n'
body += ' self.systematics = ' + str(self.syst) + '\n'
body += self.init
body +=' # Create your histograms here\n'
#if len(self.syst) > 0: body +=' for syst in systematics:\n'
Expand All @@ -133,17 +156,19 @@ def GetAnalysisTemplate(self):

if len(self.cuts) > 0 and len(self.syst) == 0:
body += '\n # Requirements\n'
for cut in self.cuts: body += ' if not %s: return\n'%cut
for cut in self.cuts: body += ' if not (%s): return\n'%cut


hnames = self.vars.keys()
if len(hnames) > 0:
body += '\n # Filling the histograms\n'
if len(self.syst) > 0:
body += '\n for syst in systematics:\n'
body += '\n for syst in self.systematics:\n'
body += '\n # Requirements\n'
for cut in self.cuts: body += ' if not %s: return\n'%cut
for expr in self.expr.keys(): body += ' %s = %s\n'%(expr, self.expr[expr])
for cut in self.cuts: body += ' if not (%s): continue\n'%cut
for expr in self.expr.keys(): body += ' %s = %s\n'%(expr, self.expr[expr]) if not self.exprorder[expr] else ''
if self.loopcode != '': body += self.loopcode
for expr in self.expr.keys(): body += ' %s = %s\n'%(expr, self.expr[expr]) if self.exprorder[expr] else ''
# for h in hnames:
# var = self.vars[h]
# cut = ' ' if self.histocuts[h] == '' else ' if %s:'%self.histocuts[h]
Expand Down Expand Up @@ -218,6 +243,7 @@ def __init__(self, analysisName, cfgname = 'testcfg', path = '', weight = '', ou
self.header = ''
self.init = ''
self.selection = ''
self.loopcode = ''
self.cuts = []
self.histos = []
self.fillLine = []
Expand All @@ -226,7 +252,9 @@ def __init__(self, analysisName, cfgname = 'testcfg', path = '', weight = '', ou
self.weights = {}
self.histocuts = {}
self.syst = ['']
self.sampleOptions = ''
self.expr = {}
self.exprorder = {}


def main():
Expand Down
14 changes: 8 additions & 6 deletions framework/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,14 @@ def __init__(self, pvec = TLorentzVector(), charge = 0, pdgid = -1):
#################################################################################
class lepton(object):

def __init__(self, pvec = TLorentzVector(), charge = 0, pdgid = -1, mcmatch=-1, passTightID = True):
def __init__(self, pvec = TLorentzVector(), charge = 0, pdgid = -1, mcmatch=-1, passTightID = True, passbtag = True):
self.SetP(pvec)
self.SetCharge(charge)
self.SetFlav(pdgid)
self.resetValues()
self.mcmatch = mcmatch
self.passTightID = passTightID
self.passbtag = passbtag
###############################
### Set methods

Expand Down Expand Up @@ -258,6 +259,12 @@ def CheckZpair(lep1, lep2):
if not lep1.charge*lep2.charge < 0: return 0
return InvMass(lep1,lep2)

def CheckSign(lep1, lep2):
''' Returns: 1 if Same Sign, 0 otherwise '''
if not lep1.charge*lep2.charge > 0: return 0
return 1


def GetNBtags(listOfJets):
''' Returns the number of btag jets in the list of jets '''
nbtags = 0
Expand Down Expand Up @@ -348,8 +355,3 @@ def GetValue(tree, var, syst = '', index = -1):
else:
print 'ERROR: var %s not in tree!!'%var
return 0

def replaceWords(string, word, newstring):
import re
return re.sub(r'\b%s\b'%word, newstring, string)

46 changes: 37 additions & 9 deletions framework/looper.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,25 @@

from framework.AnalysisCreator import AnalysisCreator
from run import main as run
from ROOT import TFile

class looper(AnalysisCreator):

def AddRunFolder(self, fname):
sys.path.append(fname)

def Run(self):
self.CreateAnalysis()
#cfgpath = '%s/%s.cfg'%(self.outpath, self.cfgname)
cfgpath = self.cfgname
print 'Executing analysis \'%s\' using cfg file \'%s\' in \'%s/%s/\'...'%(self.analysisName, cfgpath, mypath+self.outpath, self.analysisName)
return run('%s/%s/%s'%(mypath+self.outpath,self.analysisName,cfgpath))
odir = {}
if len(self.samples.keys()) != 0:
self.CreateAnalysis()
#cfgpath = '%s/%s.cfg'%(self.outpath, self.cfgname)
cfgpath = self.cfgname
print 'Executing analysis \'%s\' using cfg file \'%s\' in \'%s/%s/\'...'%(self.analysisName, cfgpath, mypath+self.basepath, self.analysisName)
odir = run('%s/%s/%s'%(mypath+self.basepath,self.analysisName,cfgpath))
if self.readOutput and self.loadDic != {}:
for ksamp in self.loadDic.keys():
odir[ksamp] = self.loadDic[ksamp]
return odir

def AutoRemove(self):
command = 'rm -r %s/%s'%(self.outpath, self.analysisName)
Expand All @@ -36,33 +43,54 @@ def AddToOutput(self, sampleName, histodic):
def GetAnalysisName(self):
return 'analysis_%i'%(int(time.time()*1e6)%1e12)

def __init__(self, path = '', nSlots = 1, cut = '', weight = '', nEvents = 0, year = 0, verbose = 0, options = 'merge', treeName = 'Events', processdic = {}):
def AddSample(self, sampleName, sampleList):
if self.readOutput:
if os.path.isfile('%s/%s.root'%(self.outpath, sampleName)):
if not sampleName in self.loadDic.keys(): self.loadDic[sampleName] = {}
print 'Reading %s from %s...'%(sampleName, self.outpath)
f = TFile.Open('%s/%s.root'%(self.outpath, sampleName))
hlist = f.GetListOfKeys()
for l in hlist:
hname = l.GetName()
histo = getattr(f, hname)
histo.SetDirectory(0)
self.loadDic[sampleName][hname] = histo
else: self.samples[sampleName] = sampleList
else:
self.samples[sampleName] = sampleList

def __init__(self, path = '', nSlots = 1, cut = '', weight = '', nEvents = 0, year = 0, verbose = 0, options = 'merge', treeName = 'Events', processdic = {}, outpath='./.looper/', readOutput=False, basepath = './looper/'):
self.analysisName = self.GetAnalysisName()
self.SetTreeName(treeName)
self.SetCfgname('testcfg')
self.SetOutpath('./.looper/')
self.SetBasePath('./.looper/')
self.AddRunFolder('.looper')
self.SetOutpath(outpath)
self.SetBasePath(basepath)
self.AddRunFolder(outpath)
self.SetPath(path)
self.SetNEvents(nEvents)
self.SetYear(year)
self.SetVerbose(verbose)
self.SetOptions(options)
self.SetNSlots(nSlots)
self.SetWeight(weight)
self.readOutput = readOutput
self.header = ''
self.init = ''
self.selection = ''
self.loopcode = ''
self.cuts = []
self.histos = []
self.samples = {}
self.vars = {}
self.out = {}
self.loadDic = {}
self.fillLine = []
self.weights = {}
self.histocuts = {}
self.syst = ['']
self.expr = {}
self.exprorder = {}
self.sampleOptions = ''
if cut != '': self.AddCut(cut)
if processdic != {}:
for pr in processdic:
Expand Down
29 changes: 29 additions & 0 deletions getScaleUnc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import ROOT
from numpy import sort

file = ROOT.TFile("/pool/ciencias/nanoAODv4/5TeV/nanoAODnoSkim/postProc/WWTo2L2Nu_1.root","READ")
tree = file.Get("Events")

#Nominal is 4, 2 and 6 are unphysical
tree.Draw("1>>hNominal(1,0.5,1.5)","LHEScaleWeight[4]")
tree.Draw("1>>h0(1,0.5,1.5)","LHEScaleWeight[0]")
tree.Draw("1>>h1(1,0.5,1.5)","LHEScaleWeight[1]")
tree.Draw("1>>h3(1,0.5,1.5)","LHEScaleWeight[3]")
tree.Draw("1>>h5(1,0.5,1.5)","LHEScaleWeight[5]")
tree.Draw("1>>h7(1,0.5,1.5)","LHEScaleWeight[7]")
tree.Draw("1>>h8(1,0.5,1.5)","LHEScaleWeight[8]")


hn = ROOT.gDirectory.Get("hNominal")
h0 = ROOT.gDirectory.Get("h0")
h1 = ROOT.gDirectory.Get("h1")
h3 = ROOT.gDirectory.Get("h3")
h5 = ROOT.gDirectory.Get("h5")
h7 = ROOT.gDirectory.Get("h7")
h8 = ROOT.gDirectory.Get("h8")

scalevariations = [h0.GetBinContent(1), h1.GetBinContent(1),h3.GetBinContent(1),h5.GetBinContent(1),h7.GetBinContent(1),h8.GetBinContent(1)]
print "Nominal: ", hn.GetBinContent(1)
print "Scale Vars: ", [h0.GetBinContent(1), h1.GetBinContent(1),h3.GetBinContent(1),h5.GetBinContent(1),h7.GetBinContent(1),h8.GetBinContent(1)]
sortedscalevariations = sort(scalevariations)
print "Envelope (percent): - %1.3f + %1.3f "%((sortedscalevariations[0]- hn.GetBinContent(1))/hn.GetBinContent(1), (sortedscalevariations[-1]- hn.GetBinContent(1))/hn.GetBinContent(1))
90 changes: 3 additions & 87 deletions plotter/Plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,12 +363,11 @@ class HistoComp(Plot):
cp.Draw()
'''

def AddHisto(self, h, drawOpt = 'hist', drawErr = 0, addToLeng = 0, color = '', lineStyle = 1):
def AddHisto(self, h, drawOpt = 'hist', drawErr = 0, addToLeng = 0, color = ''):
if self.doNorm: h.Scale(1/h.Integral())
h.SetStats(0); h.SetLineWidth(2); h.SetTitle('')
if isinstance(color, int):
h.SetLineColor(color)
h.SetLineStyle(lineStyle)
#h.SetFillColor(color)
self.histos.append([h, drawOpt, drawErr, addToLeng])

Expand Down Expand Up @@ -398,7 +397,7 @@ def Draw(self, doSetLogy = False):
self.SetAxisPlot(self.histos[0][0])
dmax = max(dmax)
dmin = min(dmin)
if self.legend.GetNRows() > 0: self.legend.Draw()
self.legend.Draw()

# Set maximum and minimum
if isinstance(self.PlotMaximum, float): self.histos[0][0].SetMaximum(self.PlotMaximum)
Expand Down Expand Up @@ -426,10 +425,7 @@ def Draw(self, doSetLogy = False):
self.ratioh[0][0].SetMinimum(self.PlotRatioMin)
for h in self.ratioh:
h[0].Draw(h[1] + ',same')
if h[2] != 0 and h[2] != '':
hrat = h[0].Clone()
hrat.SetFillStyle(3244)
hrat.Draw('same,'+h[2])
if h[2] != 0 and h[2] != '': h[0].Draw('same,'+h[2])

# Save
gPad.SetTickx();
Expand Down Expand Up @@ -634,83 +630,3 @@ def __init__(self, outpath = './', outname = 'temp', doRatio = True, HM='', colo
self.overlapHistos = []
self.extraRatio = []
if HM!= '': self.SetHistosFromMH(HM)



class HistoUnc(HistoComp):
''' Example:
cp = HistoUnc('./temp/', doRatio = True, doNorm = True)
cp.AddHisto(hdata, 'pe', 'e2', 'Data')
cp.AddHisto(hMC, 'hist', '', 'MC')
cp.autoRatio = True
cp.Draw()
'''

def AddHistoNom(self, h):
self.hNo = h
self.AddHisto(h, 'hist', 'e2' if self.DrawStatUnc else 0, 0, 1, 1)
self.rnom = self.hNo.Clone('rnom')
for b in range(0, self.rnom.GetNbinsX()+2):
bc = self.rnom.GetBinContent(b)
berr = self.rnom.GetBinError(b) / bc if bc != 0 else 0
self.rnom.SetBinError(b, berr)
self.rnom.SetBinContent(b, 1.)
#print 'berr: ', berr
self.rnom.SetLineStyle(2)
self.rnom.SetLineWidth(2)
self.rnom.SetLineColor(kGray+1)
self.rnom.SetFillColor(kTeal-9)
self.rnom.SetFillStyle(1)
self.AddRatioHisto(self.rnom, 'hist', 'e2')

def AddHistoUp(self, h):
self.hUp = h
self.hUp.SetLineWidth(2); self.hUp.SetTitle('');
self.hUp.SetStats(0); self.hUp.SetLineColor(kAzure+2)
self.AddHisto(self.hUp, 'hist', 0, 0, kAzure+2, 2)
self.rUp = self.hUp.Clone('hUp')
#self.rUp.Divide(self.hNo)
for b in range(0, self.rUp.GetNbinsX()+1):
bc = self.rUp.GetBinContent(b)
d = self.hNo.GetBinContent(b)
self.rUp.SetBinContent(b, 1 if (bc==0 or d==0) else bc/d)
self.AddRatioHisto(self.rUp, 'hist', 0)
if self.rUp.GetMinimum()*0.80 < self.PlotRatioMin: self.SetRatioMin(self.rUp.GetMinimum()*0.80)
if self.rUp.GetMaximum()*1.20 > self.PlotRatioMax: self.SetRatioMax(self.rUp.GetMaximum()*1.2)
self.rUp.SetLineStyle(1)

def AddHistoDown(self, h):
self.hDo = h
self.hDo.SetLineWidth(2); self.hDo.SetTitle('');
self.hDo.SetStats(0); self.hDo.SetLineColor(kRed+1)
self.AddHisto(self.hDo, 'hist', 0, 0, kRed+1, 2)
self.rDo = self.hDo.Clone('hDo')
#self.rDo.Divide(self.hNo)
for b in range(0, self.rDo.GetNbinsX()+1):
bc = self.rDo.GetBinContent(b)
d = self.hNo.GetBinContent(b)
self.rDo.SetBinContent(b, 1 if (bc==0 or d==0) else bc/d)
self.rDo.SetLineStyle(1)
if self.rDo.GetMinimum()*0.80 < self.PlotRatioMin: self.SetRatioMin(self.rDo.GetMinimum()*0.80)
if self.rDo.GetMaximum()*1.20 > self.PlotRatioMax: self.SetRatioMax(self.rDo.GetMaximum()*1.2)
self.AddRatioHisto(self.rDo, 'hist', 0)

def __init__(self, outpath = './', outname = 'temp', tag = '', doNorm = False, drawStatErr = True, xtit = '', ytit = 'Events'):
self.Initialize(outpath, outname, True)
self.doNorm = doNorm
self.DrawStatUnc = drawStatErr
self.autoRatio = False
self.histos = []
self.ratioh = []
self.SetPlotMaxScale(1.3)
self.AddTex(tag, 0.65, 0.88, 0.05)
self.SetHistoPad(x0 = 0.0, y0 = 0.47, x1 = 1, y1 = 1)
self.SetRatioPad(x0 = 0.0, y0 = 0.00, x1 = 1, y1 = 0.52)
self.SetHistoPadMargins(top = 0.14, bottom = 0.10, right = 0.03, left = 0.10)
self.SetRatioPadMargins(top = 0.08, bottom = 0.25, right = 0.03, left = 0.10)
self.SetYratioTitle('Unc./Nom.', 0.10, 0.4, labSize = 0.08)
self.SetXtitle(xtit, 0.12, 0.8, labSize = 0.09)
self.SetYtitle(ytit, 0.12, 0.35, labSize = 0.08)
self.SetTextLumi(texlumi = '%2.1f fb^{-1} (13 TeV)' if not doNorm else '', texlumiX = 0.67, texlumiY = 0.97, texlumiS = 0.05)
self.SetRatioMin(0.95); self.SetRatioMax(1.05)

Loading