def __init__(self, name, snames, variable): self.name = name self.plotter = ROOT.MultiDraw() for sname in snames: if lowpt: self.plotter.addInputPath(utils.getSkimPath(sname, 'ph75')) else: self.plotter.addInputPath(utils.getSkimPath(sname, 'emjet')) self.variable = variable self.categories = [] # [(name, title, sel)]
oname = omname[0] mname = omname[1] print oname, mname snames, region, basesel, colname = measurements[(oname, mname)] outputFile = ROOT.TFile.Open( outDir + '/trigger_efficiency_%s_%s.root' % (oname, mname), 'recreate') # fill the histograms plotter = ROOT.MultiDraw() plotter.setWeightBranch('') for sample in allsamples.getmany(snames): plotter.addInputPath(utils.getSkimPath(sample.name, region)) plotter.setBaseSelection(basesel) # make an empty histogram for each (trigger, variable) combination histograms = [] for tname, (passdef, commonsel, title, variables) in confs[oname].items(): if len(omname) > 2 and tname != omname[2]: continue trigDir = outputFile.mkdir(tname) passdef = passdef.format(col=colname) commonsel = commonsel.format(col=colname)
# templates setup egPlotter = ROOT.MultiDraw() mgPlotter = ROOT.MultiDraw() # egPlotter.setPrintLevel(2) # mgPlotter.setPrintLevel(2) if dataType == 'data': egPlotter.setWeightBranch('') mgPlotter.setWeightBranch('') # target samples if dataSource == 'smu': for sname in skimConfig['mudata'][0]: egPlotter.addInputPath(utils.getSkimPath(sname, 'tp2m')) mgPlotter.addInputPath(utils.getSkimPath(sname, 'tp2m')) egPlotter.setBaseSelection('tags.pt_ > 50. && probes.loose') mgPlotter.setBaseSelection('tags.pt_ > 50.') else: if dataSource == 'sph': egSamp = 'phdata' mgSamp = 'phdata' elif dataSource == 'sel': egSamp = 'eldata' mgSamp = 'mudata' for sname in skimConfig[egSamp][0]: egPlotter.addInputPath(utils.getSkimPath(sname, 'tpeg'))
nomSels['chIso'] = nomSels['chIso'].replace('chIso', 'chIsoMax') tightSels['chIso'] = tightSels['chIso'].replace('chIso', 'chIsoMax') looseSels['chIso'] = looseSels['chIso'].replace('chIso', 'chIsoMax') # selections concatenated with chVeto configurations = [('Nom', nomSels), ('Tight', tightSels), ('Loose', looseSels)] ####################### # Plot all histograms # ####################### plotter = ROOT.MultiDraw() plotter.setPrintLevel(1) for sample in allsamples.getmany(snames): if selections.lowpt: plotter.addInputPath(utils.getSkimPath(sample.name, 'ph75')) else: plotter.addInputPath(utils.getSkimPath(sample.name, 'emjet')) plotter.setBaseSelection(' && '.join(baseSels.values())) template = ROOT.TH1D('template', ';p_{T} (GeV)', len(binning) - 1, binning) template.Sumw2() histograms = {} gname = 'gpt' gpt = template.Clone(gname) histograms[gname] = gpt plotter.addPlot(gpt, 'photons.scRawPt[0]', ' && '.join(goodSels.values()))
#sname = 'sph' #sample = ('sph-16*-m', 'monoph') #boson = 'Photon' #sname = 'smu' #sample = ('smu-16*-m', 'zmumu') #boson = 'Z' #sname = 'znng' #sample = ('znng-130-o', 'monoph') #boson = 'Photon' sname = 'wnlg' sample = ('wnlg-130-o', 'monoph') boson = 'Photon' ROOT.gSystem.Load('libPandaTreeObjects.so') e = ROOT.panda.Event ROOT.gROOT.LoadMacro('jetbalance.cc+') print utils.getSkimPath(*sample) tree = ROOT.TChain('events') tree.Add(utils.getSkimPath(*sample)) outputFile = ROOT.TFile.Open( '/data/t3home000/yiiyama/monophoton/jetbalance_' + sname + '_' + boson + '.root', 'recreate') ROOT.jetbalance(tree, outputFile, getattr(ROOT, 'b' + boson)) outputFile.Close()
import os import sys import shutil thisdir = os.path.dirname(os.path.realpath(__file__)) basedir = os.path.dirname(thisdir) sys.path.append(basedir) import config import utils from datasets import allsamples import ROOT for sample in allsamples.getmany('sph-16*'): source = ROOT.TFile.Open(utils.getSkimPath(sample.name, 'offtime')) tree = source.Get('events') tmpname = '/tmp/' + os.environ[ 'USER'] + '/' + sample.name + '_offtimeIso.root' outputFile = ROOT.TFile.Open(tmpname, 'recreate') newtree = tree.CopyTree( 'TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 175 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 40.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026 && t1Met.pt > 170. && t1Met.photonDPhi > 0.5 && t1Met.minJetDPhi > 0.5' ) newtree.Write() source.Close() outputFile.Close() shutil.copy(tmpname, config.skimDir + '/' + sample.name + '_offtimeIso.root') os.remove(tmpname)
from datasets import allsamples import ROOT arun = array.array('I', [0]) alumi = array.array('I', [0]) aevent = array.array('I', [0]) aeta = array.array('f', [0.] * 10) aphi = array.array('f', [0.] * 10) positions = {} #for sname in ['sph-16b-m', 'sph-16c-m', 'sph-16d-m', 'sph-16e-m', 'sph-16f-m', 'sph-16g-m', 'sph-16h-m']: for sname in ['sph-16b-m', 'sph-16c-m', 'sph-16d-m']: positions[sname] = {} source = ROOT.TFile.Open(utils.getSkimPath(sname, 'monoph')) tree = source.Get('events') tree.Draw( '>>elist', 'photons.scRawPt[0] > 175. && t1Met.pt > 170. && t1Met.photonDPhi > 0.5 && t1Met.minJetDPhi > 0.5', 'entrylist') elist = ROOT.gDirectory.Get('elist') tree.SetEntryList(elist) tree.SetBranchAddress('runNumber', arun) tree.SetBranchAddress('lumiNumber', alumi) tree.SetBranchAddress('eventNumber', aevent) tree.SetBranchAddress('photons.eta_', aeta) tree.SetBranchAddress('photons.phi_', aphi) ientry = 0
# garbage collection histograms = [] template = ROOT.TH1D('template', ';#sigma_{i#etai#eta}', 44, 0.004, 0.015) ratioTemplate = ROOT.TH1D( 'ratio', ';I_{CH} (GeV)', 3, array.array('d', [0., getCut('chIsoCuts'), 3.5, 5.])) ptTotal = ROOT.TH1D('ptTotal', '', 1, 0., 1.) outputFile = ROOT.TFile.Open(basedir + '/hist/hadron_fake/direct_vbf.root', 'recreate') # target and hadron templates dataPlotter = ROOT.MultiDraw() lumi = 0. for sample in allsamples.getmany('sph-16*'): dataPlotter.addInputPath(utils.getSkimPath(sample.name, 'vbfem')) lumi += sample.lumi dataPlotter.setBaseSelection('t1Met.pt < 100.') mcPlotter = ROOT.MultiDraw() for sample in allsamples.getmany('gj-*'): mcPlotter.addInputPath(utils.getSkimPath(sample.name, 'vbfem')) mcPlotter.setBaseSelection('t1Met.pt < 100.') mcPlotter.setConstantWeight(lumi) for ipt in range(len(ptBinning) - 1): ptlow = ptBinning[ipt] pthigh = ptBinning[ipt + 1]
def plotHist(hist): canvas.addHistogram(hist) canvas.xtitle = '#phi\'' canvas.printWeb('monophoton/halo', hist.GetName(), logy=False) canvas.Clear() outputFile = ROOT.TFile.Open(config.histDir + '/halo/phifit.root', 'recreate') templates = {} trees = {} haloPlotter = ROOT.MultiDraw() mcPlotter = ROOT.MultiDraw() for sample in targs: haloPlotter.addInputPath(utils.getSkimPath(sample.name, 'halo')) mcPlotter.addInputPath(utils.getSkimPath('znng-130-o', 'monoph')) mcPlotter.setConstantWeight(dataLumi) haloPlotter.setBaseSelection( 'photons.scRawPt[0] > 175. && t1Met.pt > 170. && t1Met.minJetDPhi > 0.5 && t1Met.photonDPhi > 0.5' ) mcPlotter.setBaseSelection( 'photons.scRawPt[0] > 175. && t1Met.pt > 170. && t1Met.minJetDPhi > 0.5 && t1Met.photonDPhi > 0.5' ) foldedPhi = 'TMath::Abs(TVector2::Phi_mpi_pi(TVector2::Phi_mpi_pi(photons.phi_[0] + 0.005) - {halfpi})) - {halfpi}'.format( halfpi=math.pi * 0.5) empty = ROOT.TH1D('empty', ';#phi\'', 40, -0.5 * math.pi, 0.5 * math.pi)
import sys import math thisdir = os.path.dirname(os.path.realpath(__file__)) basedir = os.path.dirname(thisdir) sys.path.append(basedir) import config import utils from datasets import allsamples import ROOT offtime = ROOT.TChain('events') for sample in allsamples.getmany('sph-16*'): # offtime.Add(utils.getSkimPath(sample.name, 'offtime')) offtime.Add(utils.getSkimPath(sample.name, 'offtimealt')) # singlemu cannot be an alternative to sph because sph has severe trigger bias #offtime = ROOT.TChain('events') #for sample in allsamples.getmany('smu-16b-m'): # offtime.Add(utils.getSkimPath(sample.name, 'offtime')) trivial = ROOT.TChain('events') for sample in allsamples.getmany('sph-16*'): trivial.Add(utils.getSkimPath(sample.name, 'trivialShower')) #offsel = 'TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 175 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 5.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026 && t1Met.pt > 170. && t1Met.photonDPhi > 0.5 && t1Met.minJetDPhi > 0.5' #offsel = 'TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 175 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 5.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026' #offsel = 'HLT_Photon135_PFMET100 && TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 140 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 5.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026' offsel = 'HLT_Photon120_R9Id90_HE10_IsoM && TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 130 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 5.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026' #offsel = 'TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 50. && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 5.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026'
cuts.append('(genPhoton.pt > 170. && genMet.pt > 130.)') genSel = ' && '.join(cuts) weight = '(weight * ' + str(lumi) + ')' genSelString = weight + ' * ' + genSel recoSelString = weight + ' * ' + recoSel expr = ptdef.expr + ':genPhoton.pt' print expr print genSelString print recoSelString for sample in samples: sourceName = utils.getSkimPath(sample.name, region, config.skimDir, '') dname = sample.name + '_' + region print ' ', dname, '(%s)' % sourceName if not os.path.exists(sourceName): sys.stderr.write('File ' + sourceName + ' does not exist.\n') raise RuntimeError('InvalidSource') source = ROOT.TFile.Open(sourceName) events = source.Get('events') hist = ROOT.TH2D(dname, dname, len(xbins)-1, xbins, len(ybins)-1, ybins) events.Draw(expr + '>>' + dname, genSelString, 'colz') outFile.cd()
def plotiso(loc, pid, pt, met, tune): inputKey = tune + '_' + loc + '_' + pid + '_PhotonPt' + pt + '_Met' + met try: ptSel = s.PhotonPtSels['PhotonPt' + pt] except KeyError: print 'Inputted pt range', pt, 'not found!' print 'Not applying any pt selection!' ptSel = '(1)' try: metSel = s.MetSels['Met' + met] except KeyError: print 'Inputted met range', met, 'not found!' print 'Not applying any met selection!' metSel = '(1)' var = s.getVariable('chiso', tune, loc) versDir = s.versionDir WEBDIR = os.environ['HOME'] + '/public_html/cmsplots' plotDir = os.path.join(WEBDIR, 'purity', s.Version, inputKey, 'chiso') histDir = os.path.join(versDir, inputKey) if not os.path.exists(plotDir): os.makedirs(plotDir) if not os.path.exists(histDir): os.makedirs(histDir) pids = pid.split('-') pid = pids[0] extras = pids[1:] selections = s.getSelections(tune, loc, pid) itune = s.Tunes.index(tune) ### Plot I_{CH} from sph data and gjets MC # selection on H/E & INH & IPh baseSel = ' && '.join([ ptSel, metSel, selections['fiducial'], selections['hovere'], selections['nhiso'], selections['phiso'] ]) if 'pixel' in extras: baseSel = baseSel + ' && ' + s.Cuts['pixelVeto'] if 'monoph' in extras: baseSel = baseSel + ' && ' + s.Cuts['monophId'] if 'max' in extras: baseSel = baseSel.replace('chIso', 'chIsoMax') var = s.Variable('TMath::Max(0., photons.chIsoMaxX[0][%d])' % itune, *var[1:]) truthSel = '(photons.matchedGenId == -22)' # output file outName = 'chiso' # + inputKey print 'plotiso writing to', histDir + '/' + outName + '.root' outFile = ROOT.TFile(histDir + '/' + outName + '.root', 'RECREATE') # don't use var.binning for binning binning = [0., var.cuts[pid]] + [0.1 * x for x in range(20, 111, 5)] # make the data iso distribution for reference extractor = s.HistExtractor('sphData', s.Samples['sphData'], var) print 'setBaseSelection(' + baseSel + ')' extractor.plotter.setBaseSelection(baseSel) extractor.categories.append( ('data', 'I_{CH} Distribution from SinglePhoton Data', '')) hist = extractor.extract(binning)[0] hist.Scale(1. / hist.GetSumOfWeights()) formatHist(hist, 'Events') printHist([hist], 'HIST', outName + '_data', plotDir, logy=True) extractor = s.HistExtractor('gjetsMc', s.Samples['gjetsMc'], var) print 'setBaseSelection(' + baseSel + ' && ' + truthSel + ')' extractor.plotter.setBaseSelection(baseSel + ' && ' + truthSel) extractor.categories.append( ('rawmc', 'I_{CH} Distribution from #gamma+jets MC', '')) raw = extractor.extract(binning)[0] raw.Scale(1. / raw.GetSumOfWeights()) formatHist(raw, 'Events') ### Plot I_{CH} from sph data and dy MC Zee samples eSelScratch = ' && '.join([ 'tp.mass > 81 && tp.mass < 101', metSel, selections['fiducial'], selections['hovere'], selections['nhiso'], selections['phiso'], selections['sieie'] ]) eSel = 'weight * (' + eSelScratch.replace("photons", "probes") + ')' eExpr = var.expression.replace('photons', 'probes') print 'Extracting electron MC distributions' mcTree = ROOT.TChain('events') for sample in allsamples.getmany('dy-50-*'): mcTree.Add(utils.getSkimPath(sample.name, 'tpeg')) print 'Draw(' + eExpr + ', ' + eSel + ')' mcHist = raw.Clone("emc") mcHist.Reset() mcTree.Draw(eExpr + ">>emc", eSel, 'goff') mcHist.Scale(1. / mcHist.GetSumOfWeights()) formatHist(mcHist, 'Events') print 'Extracting electron data distributions' dataTree = ROOT.TChain('events') for sample in allsamples.getmany('sph-16*'): dataTree.Add(utils.getSkimPath(sample.name, 'tpeg')) print 'Draw(' + eExpr + ', ' + eSel + ')' dataHist = raw.Clone("edata") dataHist.Reset() dataTree.Draw(eExpr + ">>edata", eSel, 'goff') dataHist.Scale(1. / dataHist.GetSumOfWeights()) formatHist(dataHist, 'Events') printHist([mcHist, dataHist], 'HIST', outName + '_electrons', plotDir, logy=True) scaled = raw.Clone("scaledmc") scaleHist = raw.Clone("escale") scaleHist.SetTitle("Data/MC Scale Factors from Electrons") scaleHist.Reset() for iBin in range(1, scaleHist.GetNbinsX() + 1): dataValue = dataHist.GetBinContent(iBin) dataError = dataHist.GetBinError(iBin) mcValue = mcHist.GetBinContent(iBin) mcError = mcHist.GetBinError(iBin) if mcValue == 0 or dataValue == 0: ratio = 1 error = 0.05 else: ratio = dataValue / mcValue error = ratio * ((dataError / dataValue)**2 + (mcError / mcValue)**2)**(0.5) scaleHist.SetBinContent(iBin, ratio) scaled.SetBinContent(iBin, ratio * scaled.GetBinContent(iBin)) scaleHist.SetBinError(iBin, error) scaled.Scale(1. / scaled.GetSumOfWeights()) formatHist(scaled, 'Events') formatHist(scaleHist, 'Scale Factor', lstyle=ROOT.kSolid) printHist([scaleHist], '', outName + '_scale', plotDir, logy=False) printHist([raw, scaled], 'HIST', outName + '_photons', plotDir, logy=True) outFile.Close()
ntotal = 0 sampleNames = [] tree = ROOT.TChain('cutflow') for sample in allsamples.getmany(args.snames): sampleNames.append(sample.name) if sample.data: data = True if args.skimDir == config.skimDir: # default skim directory -> assume nevents in DB is accurate ntotal += sample.nevents filePath = utils.getSkimPath(sample.name, args.region) else: # otherwise open the original files for fname in sample.files(): source = ROOT.TFile.Open(fname) counter = source.Get('counter') if not counter: source.Close() continue ntotal += counter.GetBinContent(1) source.Close() filePath = args.skimDir + '/' + sample.name + '_' + args.region + '.root'