def makeOverlaidPlot(): REFLIST = (('2Mu2J', (1000, 20, 2)), ('2Mu2J', (200, 50, 200))) key = 'Dim_deltaPhi_Matched' h = { REFLIST[0]: HISTS[REFLIST[0]][key].Clone(), REFLIST[1]: HISTS[REFLIST[1]][key].Clone(), } p = {} for ref in h: RT.addFlows(h[ref]) if h[ref].GetNbinsX() > 100: h[ref].Rebin(10) p[ref] = Plotter.Plot(h[ref], '2#mu2j ({}, {}, {})'.format(*ref[1]), 'l', 'hist') fname = 'pdfs/{}{}_Overlaid.pdf'.format(key, CUTSTRING) canvas = Plotter.Canvas() canvas.addMainPlot(p[REFLIST[1]]) canvas.addMainPlot(p[REFLIST[0]]) canvas.makeLegend(lWidth=.25, pos='tl') #canvas.legend.moveLegend(Y=-.3) canvas.legend.resizeHeight() p[REFLIST[1]].SetLineColor(R.kBlue) p[REFLIST[0]].SetLineColor(R.kRed) RT.addBinWidth(canvas.firstPlot) pave1 = canvas.makeStatsBox(p[REFLIST[1]], color=R.kBlue) pave2 = canvas.makeStatsBox(p[REFLIST[0]], color=R.kRed) Plotter.MOVE_OBJECT(pave2, Y=-.22, NDC=False) canvas.cleanup(fname)
def makeSignalPlot(hkey): HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', hkey) h = HISTS[hkey] p = Plotter.Plot(h, '', '', 'hist') canvas = Plotter.Canvas(lumi='Signal: H#rightarrow2X#rightarrow2#mu + *', logy=True if hkey != 'nDTHits' else False) canvas.addMainPlot(p) p.SetLineColor(R.kBlue) canvas.firstPlot.SetMinimum(0.9) pave = canvas.makeStatsBox(p, color=R.kBlue) if hkey in ('nHits', 'LxySig'): Plotter.MOVE_OBJECT(pave, Y=-.3) canvas.mainPad.Update() if canvas.logy: line = R.TLine( CONFIG[hkey]['val'], canvas.firstPlot.GetMinimum(), CONFIG[hkey]['val'], 10.**(R.TMath.Log10(canvas.firstPlot.GetMaximum()) * 1.06)) else: line = R.TLine(CONFIG[hkey]['val'], canvas.firstPlot.GetMinimum(), CONFIG[hkey]['val'], canvas.firstPlot.GetMaximum() * 1.05) line.Draw() line.SetLineStyle(2) print '\033[31m{:6s} {:8s} {:5.0f} {:5.0f} {:7.2%}\033[m'.format( 'Signal', hkey, *fractionCut(hkey, canvas.firstPlot.plot)) RT.addBinWidth(canvas.firstPlot) canvas.cleanup('pdfs/NM1D_{}_2Mu2J.pdf'.format(hkey))
def makeBinnedResPlot(MUON, fs, sp, quantity, q2): h = HistogramGetter.getHistogram(f, (fs, sp), '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)).Clone() fname = 'pdfs/SRR_{}_{}_{}-Binned_{}HTo2XTo{}_{}.pdf'.format(MUON, quantity+'Res', q2, 'Trig-' if TRIGGER else '', fs, SPStr(sp)) pretty, binranges, values, colors, colors2, legName = getBinningValues(q2) projections = {key:h.ProjectionY('_'+str(i), key[0], key[1]) for i,key in enumerate(binranges)} plots = {key:Plotter.Plot(projections[key], legName.format(Q2=pretty, V1=values[key][0], V2=values[key][1]), 'l', 'hist') for key in binranges} canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp)) for key in binranges: RT.addFlows(plots[key]) plots[key].Rebin(10) if plots[key].Integral() != 0: plots[key].Scale(1./plots[key].Integral()) canvas.addMainPlot(plots[key]) canvas.makeLegend(lWidth=.25, pos='tr') canvas.legend.moveLegend(X=-.08) canvas.legend.resizeHeight() canvas.setMaximum(recompute=True) for i, key in enumerate(binranges): plots[key].SetLineColor(colors[key]) plots[key].setTitles(X=plots[key].GetXaxis().GetTitle(), Y='Normalized Counts') canvas.drawText('#color[{}]{{'.format(colors2[key]) + 'RMS = {:.4f}'.format(plots[key].GetStdDev()) + '}', (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-(i*0.04)-.04) ) RT.addBinWidth(canvas.firstPlot) canvas.cleanup(fname)
def makeRepEffectPlots(hkey): HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey) HISTS = HISTS[hkey] PConfig = PConfig[hkey] PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) canvas = Plotter.Canvas(lumi='MC, {} replacement'.format( hkey.replace('LxySig-', '').replace('Lxy-', '')), logy=True) for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]]) canvas.firstPlot.setTitles(Y='Normalized Counts') canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) canvas.firstPlot.SetMaximum(10.**7.) canvas.firstPlot.SetMinimum(10.**0.) canvas.cleanup('RepEffect_MC_{}.pdf'.format(hkey))
def makeTestPlot(): hkey = 'DSA-deltaPhi' HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', ('deltaPhi', )) DATAHISTS, DataPConfig = HG.getDataHistograms(FILES['Data'], hkey) HISTS[hkey] = HISTS['deltaPhi'] pS = Plotter.Plot(HISTS[hkey], 'H#rightarrow2X#rightarrow2#mu signal', 'l', 'hist') pD = Plotter.Plot(DATAHISTS[hkey]['data'], *DataPConfig[hkey]['data']) canvas = Plotter.Canvas(lumi='2#mu signal + 10% of 2016 data', logy=True) canvas.addMainPlot(pS) canvas.addMainPlot(pD) pS.setColor(R.kBlue, which='L') canvas.makeLegend(lWidth=.25) canvas.legend.resizeHeight() canvas.legend.moveLegend(X=-.1) canvas.firstPlot.SetMinimum(0.5) canvas.firstPlot.SetMaximum(50000.) canvas.firstPlot.setTitles(Y='Long-Lived Candidates') line = R.TLine(R.TMath.Pi() / 2., 0.5, R.TMath.Pi() / 2., 50000.) line.Draw() line.SetLineStyle(2) RT.addBinWidth(canvas.firstPlot) canvas.cleanup('deltaPhi.pdf')
def makeMCPlots(): f = R.TFile.Open('roots/PATMuonStudyPlots_Combined_BS8_MC.root') #f = R.TFile.Open('roots/PATMuonStudyPlots_Combined_BS8_MC_OldPATMatch.root') BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'QCD20toInf-ME', 'DY10to50', 'DY50toInf') PC = HG.PLOTCONFIG for hkey in ('PAT-LxySig', 'DSA-LxySig', 'PAT-vtxChi2', 'DSA-vtxChi2'): HISTS = {} HISTS['stack'] = R.THStack('hStack', '') PConfig = {'stack':('', '', 'hist')} for ref in BGORDER: HISTS[ref] = HG.getHistogram(f, ref, hkey).Clone() #RT.addFlows(HISTS[ref]) HISTS[ref].Scale(PC[ref]['WEIGHT']) HISTS[ref].Rebin(10) HISTS['stack'].Add(HISTS[ref]) PConfig[ref] = (PC[ref]['LATEX'], 'f', 'hist') PLOTS = {} for key in BGORDER + ('stack',): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) canvas = Plotter.Canvas(logy=True) for key in BGORDER: PLOTS[key].setColor(PC[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) # this has to be here because it has to be drawn first if 'LxySig' in hkey: canvas.firstPlot.GetXaxis().SetRangeUser(0., 1000.) pass if 'vtxChi2' in hkey: #canvas.firstPlot.GetXaxis().SetRangeUser(0., 200.) pass canvas.firstPlot.setTitles(X='', copy=PLOTS[BGORDER[0]]) canvas.firstPlot.setTitles(Y='Normalized Counts') canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8) for ref in reversed(BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) HISTS['sum'] = HISTS['stack'].GetStack().Last() nBins = HISTS['sum'].GetNbinsX() if 'LxySig' in hkey: val = 100. if 'vtxChi2' in hkey: val = 50. print '{} Mean : {}'.format(hkey, HISTS['sum'].GetMean()) print '{} Overflow % : {}'.format(hkey, HISTS['sum'].GetBinContent( nBins+1)/HISTS['sum'].Integral(0, nBins+1)*100.) print '{} > {:<8.0f} % : {}'.format(hkey, val, HISTS['sum'].Integral (HISTS['sum'].FindBin(val), nBins+1)/HISTS['sum'].Integral(0, nBins+1)*100.) if hkey == 'PAT-LxySig': h = HG.getHistogram(f, 'DY50toInf', hkey).Clone() print '{} DY50toInf : {}'.format(hkey, h.Integral(h.FindBin(100.), h.GetNbinsX()+1)) canvas.firstPlot.SetMaximum(HISTS['sum'].GetMaximum()*1.05) canvas.firstPlot.SetMinimum(1.) canvas.cleanup('pdfs/MC_'+hkey+'.pdf')
def makeLessMorePlot(fs, sp, quantity): h = { 'Less': HG.getHistogram(FILES[fs], (fs, sp), '{}-Less'.format(quantity)).Clone(), 'More': HG.getHistogram(FILES[fs], (fs, sp), '{}-More'.format(quantity)).Clone(), } for key in h: try: h[key].Scale(1. / h[key].Integral()) except: return pretty = { 'Less': { 'leg': 'L_{xy} < 320 cm', 'col': R.kBlue }, 'More': { 'leg': 'L_{xy} > 320 cm', 'col': R.kRed }, } p = { key: Plotter.Plot(h[key], pretty[key]['leg'], 'l', 'hist') for key in h } prettyFS = '2#mu' if '2Mu' in fs else '4#mu' c = Plotter.Canvas( lumi='H#rightarrow2X#rightarrow{} ({} GeV, {} GeV, {} mm)'.format( prettyFS, *sp), cWidth=600 if ARGS.SQUARE else 800) for key in p: c.addMainPlot(p[key]) p[key].setColor(pretty[key]['col'], which='LM') RT.addBinWidth(c.firstPlot) c.makeLegend(lWidth=0.125, pos='tr') c.legend.resizeHeight() c.legend.moveLegend(X=-.4) c.setMaximum() if ARGS.SQUARE: c.firstPlot.scaleTitleOffsets(1.1, 'X') c.cleanup('pdfs/LESSMORE_{}_{}_{}_{}_{}.pdf'.format(quantity, fs, *sp), mode='LUMI')
def makePerSignalPlots(fs): for sp in SIGNALPOINTS: for key in HISTS[(fs, sp)]: h = HISTS[(fs, sp)][key] RT.addFlows(h) p = Plotter.Plot(h, '', 'p', 'hist') canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp)) canvas.addMainPlot(p) p.SetLineColor(R.kBlue) RT.addBinWidth(p) pave = canvas.makeStatsBox(p, color=R.kBlue) canvas.cleanup('pdfs/Gen_{}_{}HTo2XTo{}_{}.pdf'.format( key, 'Trig-' if TRIGGER else '', fs, SPStr(sp)))
def makeGenRecoPlots(): for ref in HISTS: if not type(ref) == tuple: continue if ref[0] == '4Mu': name = 'HTo2XTo4Mu_' latexFS = '4#mu' elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_' latexFS = '2#mu2j' if TRIGGER: name = 'Trig-' + name name += SPStr(ref[1]) lumi = SPLumiStr(ref[0], *ref[1]) colors = {'Matched': R.kRed, 'Closest': R.kBlue} KEYS = ('Matched', 'Closest') for MUON in ('DSA', 'REF'): h, p = {}, {} for key in KEYS: h[key] = HISTS[ref]['{}_{}_{}'.format(MUON, 'deltaRGR', key)].Clone() RT.addFlows(h[key]) if h[key].GetNbinsX() > 100: h.Rebin(10) p[key] = Plotter.Plot(h[key], key, 'l', 'hist') fname = 'pdfs/{}{}_{}_{}_{}.pdf'.format(MUON, CUTSTRING, 'deltaRGR', 'Matched', name) canvas = Plotter.Canvas(lumi=lumi) for key in KEYS: canvas.addMainPlot(p[key]) p[key].SetLineColor(colors[key]) canvas.makeLegend(lWidth=.25, pos='tr') canvas.legend.resizeHeight() canvas.setMaximum() RT.addBinWidth(canvas.firstPlot) LPOS = (canvas.legend.GetX1NDC() + .01, canvas.legend.GetY1NDC() - .04) for i, key in enumerate(KEYS): canvas.drawText(text='#color[{}]{{n = {:d}}}'.format( colors[key], int(p[key].GetEntries())), pos=(LPOS[0], LPOS[1] - i * 0.04)) canvas.cleanup(fname)
def makeEffPlots(quantity, fs, SP=None): HKeys = { 'Eff': '{}Eff', 'Den': '{}Den', } for key in HKeys: HKeys[key] = HKeys[key].format(quantity) h = {} p = {} g = {} if SP is None: for i, sp in enumerate(SIGNALPOINTS): if i == 0: for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) else: for key in HKeys: h[key].Add(HISTS[(fs, sp)][HKeys[key]]) else: sp = SP for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) for key in HKeys: RT.addFlows(h[key]) h[key].Rebin(10) g['Eff'] = R.TGraphAsymmErrors(h['Eff'], h['Den'], 'cp') g['Eff'].SetNameTitle( 'g_Eff', ';' + h['Eff'].GetXaxis().GetTitle() + ';Vertex Fit Efficiency') p['Eff'] = Plotter.Plot(g['Eff'], '', 'elp', 'pe') canvas = Plotter.Canvas(lumi=fs if SP is None else SPLumiStr(fs, *SP)) canvas.addMainPlot(p['Eff']) p['Eff'].setColor(R.kBlue) RT.addBinWidth(canvas.firstPlot) canvas.firstPlot.SetMinimum(0.) canvas.firstPlot.SetMaximum(1.) canvas.cleanup('pdfs/SVFE_{}Eff{}_{}HTo2XTo{}_{}.pdf'.format( quantity, CUTSTRING, 'Trig-' if TRIGGER else '', fs, 'Global' if SP is None else SPStr(SP)))
def makeResPlot(fs, sp): if sp is None: h = HG.getAddedSignalHistograms(FILES[fs], fs, ['pTRes-' + MUON for MUON in MUONS]) prettyFS = '2#mu' if '2Mu' in fs else '4#mu' lumi = 'H#rightarrow2X#rightarrow{}, all samples combined{}'.format( prettyFS, ' + trigger' if ARGS.TRIGGER else '') else: h = {} for MUON in MUONS: h['pTRes-' + MUON] = HG.getHistogram(FILES[fs], (fs, sp), 'pTRes-' + MUON).Clone() prettyFS = '2#mu' if '2Mu' in fs else '4#mu' lumi = 'H#rightarrow2X#rightarrow{} ({} GeV, {} GeV, {} mm){}'.format( prettyFS, sp[0], sp[1], sp[2], ' + trigger' if ARGS.TRIGGER else '') c = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800) pretty = {'DSA': {'col': R.kBlue}, 'RSA': {'col': R.kRed}} p = {} for MUON in MUONS: h['pTRes-' + MUON].Scale( 1. / h['pTRes-' + MUON].Integral(0, h['pTRes-' + MUON].GetNbinsX() + 1)) #h['pTRes-'+MUON].Rebin(10) p[MUON] = Plotter.Plot(h['pTRes-' + MUON], MUON, 'l', 'hist') c.addMainPlot(p[MUON]) p[MUON].setColor(pretty[MUON]['col'], which='LM') c.makeLegend(lWidth=0.125, pos='tr') c.legend.resizeHeight() c.setMaximum() c.firstPlot.setTitles(X='', Y='', copy=h['pTRes-DSA']) RT.addBinWidth(c.firstPlot) if ARGS.SQUARE: c.firstPlot.scaleTitleOffsets(1.1, 'X') c.firstPlot.scaleTitleOffsets(1.3, 'Y') c.cleanup('pdfs/PTRES{}_{}_{}.pdf'.format( '_Trig' if ARGS.TRIGGER else '', fs, 'Global' if sp is None else SPStr(sp)), mode='LUMI')
def makePerSamplePlots(): for ref in HISTS: if not type(ref) == tuple: continue for key in HISTS[ref]: if 'deltaRGR' in key: continue if 'VS' in key: continue if type(ref) == tuple: if ref[0] == '4Mu': name = 'HTo2XTo4Mu_' latexFS = '4#mu' elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_' latexFS = '2#mu2j' if TRIGGER: name = 'Trig-' + name name += SPStr(ref[1]) lumi = SPLumiStr(ref[0], *ref[1]) legName = HistogramGetter.PLOTCONFIG['HTo2XTo' + ref[0]]['LATEX'] else: if '_Matched' in key: continue name = ref lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX'] legName = HistogramGetter.PLOTCONFIG[ref]['LATEX'] h = HISTS[ref][key].Clone() RT.addFlows(h) if h.GetNbinsX() > 100: h.Rebin(10) p = Plotter.Plot(h, legName, 'l', 'hist') fname = 'pdfs/{}{}_{}.pdf'.format(key, CUTSTRING, name) canvas = Plotter.Canvas(lumi=lumi) canvas.addMainPlot(p) canvas.makeLegend(lWidth=.25, pos='tr') canvas.legend.moveLegend(Y=-.3) canvas.legend.resizeHeight() p.SetLineColor(R.kBlue) RT.addBinWidth(p) pave = canvas.makeStatsBox(p, color=R.kBlue) canvas.cleanup(fname)
def makePerSamplePlots(): for ref in HISTS: for key in HISTS[ref]: if type(ref) == tuple: if ref[0] == '4Mu': name = 'HTo2XTo4Mu_' elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_' name += SPStr(ref[1]) if TRIGGER: name = 'Trig-' + name lumi = SPLumiStr(ref[0], *ref[1]) legName = HistogramGetter.PLOTCONFIG['HTo2XTo' + ref[0]]['LATEX'] else: name = ref lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX'] legName = HistogramGetter.PLOTCONFIG[ref]['LATEX'] h = HISTS[ref][key].Clone() RT.addFlows(h) p = Plotter.Plot(h, legName, 'l', 'hist') fname = 'pdfs/NM1_{}_{}.pdf'.format(key, name) canvas = Plotter.Canvas(lumi=lumi) canvas.lumi += ' : |#Delta#Phi| ' + ('<' if '_Less' in key else '>') + ' #pi/2' canvas.addMainPlot(p) canvas.makeLegend(lWidth=.25, pos='tr') canvas.legend.moveLegend(Y=-.3) canvas.legend.resizeHeight() p.SetLineColor(R.kBlue) RT.addBinWidth(p) cutKey = key.replace('_Less', '').replace('_More', '') cutVal = Selections.CUTS[cutKey].val l = R.TLine(cutVal, p.GetMinimum(), cutVal, p.GetMaximum() * 1.05) l.SetLineStyle(2) l.SetLineWidth(2) l.Draw() canvas.cleanup(fname)
def makeBinnedResPlotBinwise(MUONS, outputTag, quantity, q2, fs, sp): defaultColorOrder = (R.kRed, R.kBlue, R.kGreen, R.kMagenta) h = {} for MUON in MUONS: h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)).Clone() # leaving space for the bin number fname = 'pdfs/SRR_{}_{}_{}-Binned-Bin-{{}}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', q2, 'Trig-' if TRIGGER else '', fs, SPStr(sp)) pretty, binranges, values, colors, colors2, legName = getBinningValues(q2) for i, key in enumerate(binranges): canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp)) projections, plots = {}, {} for j, MUON in enumerate(MUONS): projections[MUON] = h[MUON].ProjectionY('_'+str(i)+'_'+str(j), key[0], key[1]) plots[MUON] = Plotter.Plot(projections[MUON], MUON, 'l', 'hist') RT.addFlows(plots[MUON]) plots[MUON].Rebin(10) if plots[MUON].Integral() != 0: plots[MUON].Scale(1./plots[MUON].Integral()) plots[MUON].SetLineColor(defaultColorOrder[j]) canvas.addMainPlot(plots[MUON]) canvas.makeLegend(lWidth=.25, pos='tr') canvas.legend.resizeHeight() canvas.setMaximum(recompute=True) canvas.drawText(legName.format(Q2=pretty, V1=values[key][0], V2=values[key][1]), (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-.04)) for j, MUON in enumerate(MUONS): plots[MUON].SetLineColor(defaultColorOrder[j]) plots[MUON].setTitles(X=plots[MUON].GetXaxis().GetTitle(), Y='Normalized Counts') canvas.drawText('#color[{}]{{'.format(defaultColorOrder[j]) + 'RMS = {:.4f}'.format(plots[MUON].GetStdDev()) + '}', (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-(j*0.04)-.08) ) RT.addBinWidth(canvas.firstPlot) canvas.cleanup(fname.format(i+1))
def makeRatioPlots(quantity, LxyRange): legDict = {'Less': '< #pi/4', 'More': '> 3#pi/4'} hkeys = { key: 'h{}{}{}'.format(key, quantity, LxyRange) for key in ('Less', 'More') } a = HISTS[hkeys['Less']]['stack'].GetStack().Last().Clone() den = HISTS[hkeys['More']]['stack'].GetStack().Last().Clone() a.Rebin(2), den.Rebin(2) a.Divide(den) d = DHists[hkeys['Less']].Clone() den = DHists[hkeys['More']].Clone() d.Rebin(2), den.Rebin(2) d.Divide(den) PLOTS = {'': Plotter.Plot(a, ' MC SR/CR', 'lp', 'hist p')} DPLOTS = {'': Plotter.Plot(d, 'Data SR/CR', 'lp', 'hist p')} canvas = Plotter.Canvas(lumi='36.3 fb^{-1} (13 TeV)', logy=False) colors = {'': R.kBlue} canvas.addMainPlot(PLOTS['']) canvas.addMainPlot(DPLOTS['']) PLOTS[''].setColor(R.kBlue) DPLOTS[''].setColor(R.kBlack) canvas.firstPlot.setTitles(X='', copy=DHists[hkeys['Less']]) canvas.firstPlot.setTitles(Y='Event Yield') canvas.makeLegend(lWidth=.3, pos='tr') canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) canvas.firstPlot.SetMaximum(2.) canvas.firstPlot.SetMinimum(-1.) canvas.cleanup('pdfs/Ratio_{}_{}.pdf'.format( keyList[hkeys['Less']], 'Lin' if not canvas.logy else 'Log'))
def makeRepEffectPlots(hkey): HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey) HISTS = HISTS[hkey] PConfig = PConfig[hkey] PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) canvas = Plotter.Canvas( lumi='MC Background, {} PAT association (36.3 fb^{{-1}})'.format( hkey.replace('LxySig-', '').replace('Lxy-', '')), logy=True, cWidth=600 if ARGS.SQUARE else 800) for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]]) canvas.firstPlot.setTitles(Y='Event Yield') canvas.makeLegend(lWidth=.3, pos='tr', autoOrder=False, fontscale=0.8) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) canvas.firstPlot.SetMaximum(10.**7.) canvas.firstPlot.SetMinimum(10.**0.) if ARGS.SQUARE: canvas.firstPlot.scaleTitleOffsets(1.1, 'X') z = PLOTS['stack'].plot.GetStack().Last() print 'MC', hkey, z.Integral(0, z.GetNbinsX() + 1) canvas.cleanup('pdfs/REPEFF_MC_{}.pdf'.format(hkey), mode='LUMI')
def makeStackPlots(DataMC=False, logy=False): BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'QCD20toInf-ME', 'DY10to50', 'DY50toInf') for hkey in HISTS['DY50toInf']: if 'Matched' in hkey: continue if 'VS' in hkey: continue h = {} if not MCONLY: h['Data'] = HISTS['DoubleMuonRun2016B-07Aug17-v2'][hkey].Clone() if True: # h ['Signal'] = HISTS[('4Mu', (125, 20, 13)) ][hkey].Clone() h['BG'] = R.THStack('hBG', '') PConfig = {} if not MCONLY: PConfig['Data'] = ('DoubleMuon2016', 'pe', 'pe') if True: # PConfig['Signal'] = ('H#rightarrow2X#rightarrow4#mu', 'l' , 'hist') PConfig['BG'] = ('', '', 'hist') PC = HistogramGetter.PLOTCONFIG for key in BGORDER: h[key] = HISTS[key][hkey].Clone() RT.addFlows(h[key]) if h[key].GetNbinsX() > 100: h[key].Rebin(10) h[key].Scale(PC[key]['WEIGHT']) PConfig[key] = (PC[key]['LATEX'], 'f', 'hist') h['BG'].Add(h[key]) if not MCONLY: for era in ('C', 'D', 'E', 'F', 'G', 'H'): h['Data'].Add( HISTS['DoubleMuonRun2016{}-07Aug17'.format(era)][hkey]) RT.addFlows(h['Data']) if h['Data'].GetNbinsX() > 100: h['Data'].Rebin(10) p = {} for key in h: p[key] = Plotter.Plot(h[key], *PConfig[key]) fname = 'pdfs/{}{}_Stack{}{}{}.pdf'.format(hkey, CUTSTRING, 'MC' if MCONLY else '', '-Log' if logy else '', '-Rat' if DataMC else '') for key in BGORDER: p[key].setColor(PC[key]['COLOR'], which='LF') canvas = Plotter.Canvas(ratioFactor=0. if not DataMC else 1. / 3., logy=logy, fontscale=1. if not DataMC else 1. + 1. / 3.) if True: canvas.addMainPlot(p['BG']) if not MCONLY: canvas.addMainPlot(p['Data']) # canvas.addMainPlot(p['Signal']) canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8 if not DataMC else 1.) if not MCONLY: canvas.addLegendEntry(p['Data']) for key in reversed(BGORDER): canvas.addLegendEntry(p[key]) # canvas.addLegendEntry(p['Signal']) canvas.legend.resizeHeight() p['BG'].setTitles(X=p['WJets'].GetXaxis().GetTitle(), Y='Normalized Counts') RT.addBinWidth(p['BG']) canvas.firstPlot.SetMaximum(h['BG'].GetStack().Last().GetMaximum() * 1.05) #canvas.firstPlot.SetMaximum(1.e-4) if logy: canvas.firstPlot.SetMinimum(1.) if DataMC: canvas.makeRatioPlot(p['Data'].plot, p['BG'].plot.GetStack().Last()) canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y') canvas.rat.scaleTitleOffsets(0.8, axes='Y') # p['Signal' ].SetLineStyle(2) # p['Signal' ].SetLineColor(R.kRed) canvas.finishCanvas(extrascale=1. if not DataMC else 1. + 1. / 3.) canvas.save(fname) canvas.deleteCanvas()
def makeEffPlots(quantity, fs, SP=None): HKeys = { 'DSA_Num': 'DSADim_Num_{}', 'DSA_Den': 'DSADim_Den_{}', } for key in HKeys: HKeys[key] = HKeys[key].format(quantity, 'HTo2XTo' + fs) h = {} pg = {} pnum = {} pden = {} prn = {} prd = {} g = {} rn = {} rd = {} if SP is None: for i, sp in enumerate(SIGNALPOINTS): if i == 0: for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) else: for key in HKeys: h[key].Add(HISTS[(fs, sp)][HKeys[key]]) displacement_str = None displacement_color = None else: sp = SP if isinstance(sp, tuple): for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) h[key].GetXaxis().SetLimits(limit_low, limit_high) h[key].GetXaxis().SetRangeUser(limit_low, limit_high) RT.addFlows(h[key]) h[key].Rebin(10) h[key].Sumw2() elif isinstance(sp, list): h[key] = {} for key in HKeys: for spl in sp: h[key][spl] = HISTS[(fs, spl)][HKeys[key]].Clone() h[key][spl].SetDirectory(0) h[key][spl].GetXaxis().SetLimits(limit_low, limit_high) RT.addFlows(h[key][spl]) h[key][spl].Rebin(10) h[key][spl].Sumw2() dxy_fraction = round(FRACTIONS[fs]['{}_{}_{}'.format(*SP)][1], 1) for key in DISPLACEMENT_CATEGORIES: if key[0] <= dxy_fraction < key[1]: displacement_str = DISPLACEMENT_CATEGORIES[key]['label'] displacement_color = DISPLACEMENT_CATEGORIES[key]['color'] break else: # we must have dxy_fractions == 100.0 key = DISPLACEMENT_CATEGORIES.keys()[-1] displacement_str = DISPLACEMENT_CATEGORIES[key]['label'] displacement_color = DISPLACEMENT_CATEGORIES[key]['color'] # for key in HKeys: # RT.addFlows(h[key]) # h[key].Rebin(10) # # area = h[key].Integral() # h[key].Sumw2() # # if area != 0: h[key].Scale(1./area) NumDens = ( ('DSA_Num', 'DSA_Den', 'GEN', R.kBlue), ('DSA_Num', 'DSA_Den', ('untriggered', 'triggered'), (R.kBlue, R.kRed)), ) num, den, leg, col = NumDens[0] g[num] = R.TGraphAsymmErrors(h[num], h[den], 'cp') g[num].GetXaxis().SetLimits(limit_low, limit_high) g[num].SetNameTitle( 'g_' + num, ';' + h[num].GetXaxis().GetTitle() + '; Trigger Efficiency') pg[num] = Plotter.Plot(g[num], leg, 'elp', 'pe') num, den, leg, col = NumDens[1] pnum[num] = Plotter.Plot(deepcopy(h[num]), leg[1], 'elp', 'pe') pden[num] = Plotter.Plot(deepcopy(h[den]), leg[0], 'elp', 'pe') pnum[num].SetNameTitle('pnum_' + num, ';' + h[num].GetXaxis().GetTitle() + '; yield') rn[num] = deepcopy(h[num]) rn[num].Scale(1. / (h[num].Integral())) rn[num].SetNameTitle('rn_' + num, ';' + h[num].GetXaxis().GetTitle() + '; norm. yield') # rn[num].GetXaxis().SetRangeUser(0, 100) prn[num] = Plotter.Plot(rn[num], leg[1], 'elp', 'pe') rd[num] = deepcopy(h[den]) rd[num].Scale(1. / (h[den].Integral())) rd[num].SetNameTitle('rd_' + num, ';' + h[num].GetXaxis().GetTitle() + '; norm. yield') prd[num] = Plotter.Plot(rd[num], leg[0], 'elp', 'pe') FIRST = (0, 1) SECOND = (1, 2) fraction_str = '' if SP is None else '[{}%, #color[{}]{{{}%}}]'.format( round(FRACTIONS[fs]['{}_{}_{}'.format(*SP)][0], 1), displacement_color, round(FRACTIONS[fs]['{}_{}_{}'.format(*SP)][1], 1)) accepted_error_max = 0.1 accepted_error_halfmax = 0.2 for SECTION in (FIRST, ): canvas_eff = Plotter.Canvas( lumi=fs if SP is None else '{} ({} GeV, {} GeV, {} mm) #scale[0.7]{{{fraction_str}}}'. format(fs, *SP, fraction_str=fraction_str)) for i in range(SECTION[0], SECTION[1]): key = NumDens[i][0] col = NumDens[i][3] # pg[key].GetXaxis().SetLimits(0., 3.5) canvas_eff.addMainPlot(pg[key]) pg[key].SetMarkerColor(col) pg[key].SetLineColor(col) ymax = -1. ymaxErrorYlow = 0. ymaxErrorYhigh = 0. ymax_pos = None for b in range(pg[key].GetN(), 0, -1): xtemp = R.Double(-1.) ytemp = R.Double(-1.) pg[key].GetPoint(b, xtemp, ytemp) ytempErrorYlow = pg[key].GetErrorYlow(b) ytempErrorYhigh = pg[key].GetErrorYhigh(b) # if ytemp > ymax and max(pg[key].GetErrorYlow(b), # pg[key].GetErrorYhigh(b)) < accepted_error_max: # ymax = ytemp # ymax_pos = xtemp # if point has a lower value than the one one the right, but it # is compatible with the fluctuations of the plot on the right # (i.e., its errors are contained in the errors of the other # plot), then call the (left) point the new maximum nevertheless if ytemp < ymax and max(ytempErrorYlow, ytempErrorYhigh) < accepted_error_max and \ ytemp-ytempErrorYlow > ymax-ymaxErrorYlow and \ ytemp+ytempErrorYhigh < ymax+ymaxErrorYhigh: ymax = ytemp ymaxErrorYlow = ytempErrorYlow ymaxErrorYhigh = ytempErrorYhigh ymax_pos = xtemp elif ytemp > ymax and max( ytempErrorYlow, ytempErrorYhigh) < accepted_error_max: ymax = ytemp ymaxErrorYlow = ytempErrorYlow ymaxErrorYhigh = ytempErrorYhigh ymax_pos = xtemp if ymax_pos is not None: maxarrow = R.TArrow(ymax_pos, -0.065, ymax_pos, 0.) R.SetOwnership(maxarrow, 0) maxarrow.SetLineColor(col) maxarrow.SetLineWidth(3) maxarrow.SetArrowSize(0.02) maxarrow.Draw() else: print('WARNING: No maximum found. Maybe the accepted errors ' 'are too small?') ymax_pos = None yhalfmax_pos = None if ymax_pos is not None: yhalfmax = 0.5 * ymax yhalfmax_pos = None for b in range(pg[key].GetN()): xtemp = R.Double(-1.) ytemp = R.Double(-1.) pg[key].GetPoint(b, xtemp, ytemp) if ytemp > yhalfmax and max( pg[key].GetErrorYlow(b), pg[key].GetErrorYhigh(b)) < accepted_error_halfmax: x2 = xtemp y2 = ytemp xtemp_prev = R.Double(0.) ytemp_prev = R.Double(0.) for bprev in range(1, b + 1): if b - bprev >= 0 and max( pg[key].GetErrorYlow(b - bprev), pg[key].GetErrorYhigh( b - bprev)) < accepted_error_halfmax: pg[key].GetPoint(b - bprev, xtemp_prev, ytemp_prev) x1 = xtemp_prev y1 = ytemp_prev # linear interpolation: yhalfmax_pos = (yhalfmax * (x1 - x2) + (y1 * x2 - y2 * x1)) / (y1 - y2) break else: yhalfmax_pos = x2 * 0.5 halfmaxarrow = R.TArrow(yhalfmax_pos, -0.06, yhalfmax_pos, 0.) R.SetOwnership(halfmaxarrow, 0) halfmaxarrow.SetLineColor(col) halfmaxarrow.SetLineWidth(2) halfmaxarrow.SetArrowSize(0.02) halfmaxarrow.Draw() break if ymax_pos is not None and yhalfmax_pos is not None: pg[key].legName = pg[key].legName + \ ' #scale[0.7]{{(#Delta R_{{max}} = {}, #Delta R_{{max/2}} = {}, #frac{{#Delta R_{{max/2}}}}{{#Delta R_{{max}}}} = {})}}'.format( round(ymax_pos,3), round(yhalfmax_pos,3), round(yhalfmax_pos/ymax_pos, 3)) run1_line = R.TLine(0.2, 0., 0.2, 1.) R.SetOwnership(run1_line, 0) run1_line.SetLineColor(R.kGray) run1_line.Draw() canvas_eff.makeLegend(lWidth=0.65, pos='tr') # canvas_eff.legend.moveLegend(X=0.08) canvas_eff.legend.resizeHeight() # canvas_eff.firstPlot.GetXaxis().SetLimits(0., 3.5) canvas_eff.firstPlot.SetMinimum(0.) canvas_eff.firstPlot.SetMaximum(1.) RT.addBinWidth(canvas_eff.firstPlot) canvas_eff.cleanup('pdfs/DimSTE_{}{}Eff_HTo2XTo{}_{}_{}.pdf'.format( output_tag, quantity, fs, 'Global' if SP is None else SPStr(SP), (displacement_str if displacement_str is not None else ''))) for SECTION in (SECOND, ): canvas_ratioplot = Plotter.Canvas( ratioFactor=1 / 3., lumi=fs if SP is None else '{} ({} GeV, {} GeV, {} mm) #scale[0.7]{{{fraction_str}}}'.format( fs, *SP, fraction_str=fraction_str)) for i in range(SECTION[0], SECTION[1]): key = NumDens[i][0] col = NumDens[i][3] # prn[key].GetXaxis().SetLimits(0., 3.5) # prd[key].GetXaxis().SetLimits(0., 3.5) canvas_ratioplot.makeLegend(lWidth=.35, pos='tr') canvas_ratioplot.addLegendEntry(prn[key]) canvas_ratioplot.addLegendEntry(prd[key]) canvas_ratioplot.legend.resizeHeight() canvas_ratioplot.addMainPlot(prn[key]) canvas_ratioplot.addMainPlot(prd[key]) canvas_ratioplot.makeRatioPlot(prn[key], prd[key], ytit='triggered / untriggered') canvas_ratioplot.firstPlot.scaleTitleOffsets(0.8, axes='Y') canvas_ratioplot.rat.scaleTitleOffsets(0.8, axes='Y') vline = R.TLine(2.5, 0.5, 2.5, 1.5) R.SetOwnership(vline, 0) vline.SetLineColor(15) vline.Draw() prn[key].SetMarkerColor(col[0]) prn[key].SetLineColor(col[0]) prd[key].SetMarkerColor(col[1]) prd[key].SetLineColor(col[1]) # canvas_ratioplot.makeLegend(pos='tr') # canvas_ratioplot.legend.moveLegend(X=0.08) # canvas_ratioplot.legend.resizeHeight() # canvas_ratioplot.firstPlot.SetMinimum(0.) # canvas_ratioplot.firstPlot.SetMaximum(1.) # vline = R.TLine(0., 1., 5., 1.) # R.SetOwnership(vline, 0) # vline.SetLineColor(15) # vline.Draw() # RT.addBinWidth(canvas_ratioplot.firstPlot) # canvas_ratioplot.finishCanvas(extrascale=1.+1/3.) canvas_ratioplot.cleanup( 'pdfs/DimSTE_{}{}NormRatio_HTo2XTo{}_{}_{}.pdf'.format( output_tag, quantity, fs, 'Global' if SP is None else SPStr(SP), (displacement_str if displacement_str is not None else ''))) canvas_overlay = Plotter.Canvas( lumi=fs if SP is None else '{} ({} GeV, {} GeV, {} mm) #scale[0.7]{{{fraction_str}}}'. format(fs, *SP, fraction_str=fraction_str)) for i in range(SECTION[0], SECTION[1]): key = NumDens[i][0] col = NumDens[i][3] canvas_overlay.addMainPlot(pden[num]) canvas_overlay.addMainPlot(pnum[num]) canvas_overlay.makeLegend(pos='tr', lWidth=.2) canvas_overlay.legend.resizeHeight() # canvas_overlay.firstPlot.GetXaxis().SetLimits(0., 3.5) pnum[num].SetMarkerColor(col[0]) pden[num].SetMarkerColor(col[1]) pnum[num].SetLineColor(col[0]) pden[num].SetLineColor(col[1]) canvas_overlay.cleanup('pdfs/DimSTE_{}Overlay{}_{}_{}.pdf'.format( quantity, fs, 'Global' if SP is None else SPStr(SP), (displacement_str if displacement_str is not None else '')))
def makeOverlaidResPlot(MUONS, fs, sp, quantity, outputTag=None): # whether the plot is dif or res makes a difference wrt binning, fit range, and stats box positions # only pT is a res type; the others are all dif types ISDIF = quantity != 'pT' # what to name the plot. if MUONS is length 1, no sense to pass it twice, so get it automatically if outputTag is None: outputTag = MUONS[0] # colors, in order of MUONS, and also hashed defaultColorOrder = (R.kBlue, R.kRed, R.kGreen) colorDict = dict(zip(MUONS, defaultColorOrder)) # get histograms and define plots h = {} for MUON in MUONS: h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), MUON+'_'+quantity+'Res').Clone() p = {} for MUON in MUONS: RT.addFlows(h[MUON]) if not ISDIF: h[MUON].Rebin(5) else: h[MUON].Rebin(10) p[MUON] = Plotter.Plot(h[MUON], 'Signal MC ({})'.format(MUON[:3]), 'l', 'hist') # define and fit gaussians to everything. Set FITRANGE to be something useful. funcs = {} fplots = {} for MUON in MUONS: if quantity == 'pT': FITRANGE = (-0.4, 0.3) elif quantity == 'eta': FITRANGE = (-0.1, 0.1) else: FITRANGE = (-20., 20.) funcs[MUON] = R.TF1('f'+MUON, 'gaus', *FITRANGE) h[MUON].Fit('f'+MUON, 'R') fplots[MUON] = Plotter.Plot(funcs[MUON], 'Gaussian fit ({})'.format(MUON[:3]), 'l', '') # define canvas, add plots. addS is so that statsbox will be drawn later. # these all should be pretty obvious until... canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp)) for i, MUON in enumerate(MUONS): canvas.addMainPlot(p[MUON], addS=True if i!=0 else False) canvas.addMainPlot(fplots[MUON]) if len(MUONS) > 1: canvas.firstPlot.setTitles(X=canvas.firstPlot.GetXaxis().GetTitle().replace(MUONS[0],'Reco')) canvas.makeLegend(lWidth=.25, pos='tl') canvas.legend.resizeHeight() for MUON in MUONS: p [MUON].SetLineColor(colorDict[MUON] ) fplots[MUON].SetLineColor(colorDict[MUON]+1) RT.addBinWidth(canvas.firstPlot) # dif type: fit boxes go down the left side # res type: fit boxes go down the middle # stats boxes are on the right paves = [] for i, MUON in enumerate(MUONS): paves.append(canvas.makeStatsBox(p[MUON], color=colorDict[MUON])) Plotter.MOVE_OBJECT(paves[-1], Y=-.2*i) if not ISDIF: canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tr') else: canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tl') sbox = p[MUON].FindObject('stats') sbox.SetTextColor(colorDict[MUON]+1) if not ISDIF: Plotter.MOVE_OBJECT(sbox, Y=-.15*i, X=-.18, NDC=True) else: Plotter.MOVE_OBJECT(sbox, Y=-.15*i-0.04*4.1, NDC=True) fname = 'pdfs/SRR_{}_{}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', 'Trig-' if TRIGGER else '', fs, SPStr(sp)) canvas.cleanup(fname)
def makeKinkDistPlot(quantity, masses): points = sorted( [sp for sp in SignalInfo if sp[0] == masses[0] and sp[1] == masses[1]], key=lambda x: x[2]) s = { points[0]: HG.getHistogram(FILES['Signal'], (fs, points[0]), '{}_1'.format(quantity)).Clone(), points[1]: HG.getHistogram(FILES['Signal'], (fs, points[1]), '{}_10'.format(quantity)).Clone(), } s[points[0]].Scale(1. / s[points[0]].Integral(0, s[points[0]].GetNbinsX() + 1)) s[points[1]].Scale(1. / s[points[1]].Integral(0, s[points[1]].GetNbinsX() + 1)) #RT.addFlows(s[points[0]]) #RT.addFlows(s[points[1]]) s[points[0]].Rebin(2) s[points[1]].Rebin(2) pl = { points[0]: Plotter.Plot(s[points[0]], 'c#tau = {} mm, nominal'.format(points[0][2]), 'l', 'hist'), points[1]: Plotter.Plot(s[points[1]], 'c#tau = {} mm, reweighted'.format(points[0][2]), 'l', 'hist'), } colors = { points[0]: R.kBlue, points[1]: R.kRed, } c = Plotter.Canvas(lumi='({} GeV, {} GeV)'.format(*masses)) c.addMainPlot(pl[points[0]]) c.addMainPlot(pl[points[1]]) for p in points: pl[p].setColor(colors[p], which='LM') c.makeLegend(lWidth=0.3, pos='tr') c.legend.SetMargin(0.1) c.legend.resizeHeight() c.drawText(text='lol', pos=(c.legend.GetX1(), c.legend.GetY1() + .4), NDC=False) c.setMaximum() RT.addBinWidth(c.firstPlot) c.cleanup('pdfs/KINK_Dist_{}_{}_{}_{}.pdf'.format(quantity, masses[0], masses[1], FIGURE_OF_MERIT))
def makeSignalPlot(key): h = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', key) h = h[key] p = Plotter.Plot(h, '', '', 'hist') RT.addBinWidth(p) c = Plotter.Canvas(lumi='H#rightarrow2X#rightarrow2#mu, {}'.format( CUTS[key]['lumi']), cWidth=600 if key != 'deltaPhi' else 800, logy=CUTS[key]['logy']) c.addMainPlot(p) c.firstPlot.setColor(R.kBlue) c.firstPlot.scaleTitleOffsets(1.1, 'Y') if key == 'deltaPhi': axis = c.firstPlot.GetXaxis() labeldict = { 1: '0', 25: '#pi/4', 50: '#pi/2', 75: '3#pi/4', 100: '#pi' } for i in xrange(1, 101): val = labeldict.get(i) if val is None: val = '' axis.SetBinLabel(i, val) axis.SetNdivisions(216, False) axis.SetLabelSize(.06) axis.SetTickLength(0.03) axis.SetTickSize(0.03) axis.LabelsOption('h') c.mainPad.Update() ymin = c.mainPad.GetUymin() ymax = c.mainPad.GetUymax() if c.logy: ymax = 10.**ymax xB = R.TGaxis(0., ymin, R.TMath.Pi() - .07, ymin, 0., R.TMath.Pi(), 216, "+B", .03) xB.SetLabelSize(0) xB.Draw('same') xT = R.TGaxis(0., ymax, R.TMath.Pi() - .07, ymax, 0., R.TMath.Pi(), 216, "-B", .03) xT.SetLabelSize(0) xT.Draw('same') if key == 'pT': c.firstPlot.GetXaxis().SetRangeUser(0., 600.) eff = getEff(p, key) c.drawText('{:.1%} efficient'.format(eff), align='tr', pos=(1. - c.margins['r'] - .03, 1. - c.margins['t'] - .03)) c.mainPad.Update() ymax = c.mainPad.GetUymax() line = R.TLine(CUTS[key]['val'], 0., CUTS[key]['val'], ymax if not c.logy else 10.**ymax) line.SetLineStyle(2) line.Draw() if key == 'trkChi2': c.firstPlot.GetXaxis().SetTitle('trk. #chi^{2}/dof') c.cleanup('pdfs/NM1_2Mu2J_{}.pdf'.format(key), mode='LUMI')
def makeSimplePlots(PLOT_SPECS, DISTRIBUTION_SPECS, output_filename, output_folder="pdfs/", logy=False, normalize=False, make_legend=True): importHistograms(DISTRIBUTION_SPECS) canvas = Plotter.Canvas(logy=logy, lumi=PLOT_SPECS["lumi_str"]) Xrange_min = None Xrange_max = None Yrange_min = None Yrange_max = None for el in DISTRIBUTION_SPECS: hist = el.getAttribute("histogram") leg = el.getAttribute("legend") if leg is None: leg = '' if normalize: leg += ' (normalized)' linecolor = el.getAttribute("linecolor") linestyle = el.getAttribute("linestyle") markercolor = el.getAttribute("markercolor") markerstyle = el.getAttribute("markerstyle") Xrange = el.getAttribute("Xrange") Yrange = el.getAttribute("Yrange") rebin = el.getAttribute("rebin") if Xrange is not None: # find the most inclusive x-axis ranges if Xrange_min is not None: Xrange_min = Xrange[0] if Xrange[0] < Xrange_min else Xrange_min else: Xrange_min = Xrange[0] if Xrange_max is not None: Xrange_max = Xrange[1] if Xrange[1] > Xrange_max else Xrange_max else: Xrange_max = Xrange[1] if Yrange is not None: # find the most inclusive y-axis ranges if Yrange_min is not None: Yrange_min = Yrange[0] if Yrange[0] < Yrange_min else Yrange_min else: Yrange_min = Yrange[0] if Yrange_max is not None: Yrange_max = Yrange[1] if Yrange[1] > Yrange_max else Yrange_max else: Yrange_max = Yrange[1] # rebin histograms, if applicable if rebin: hist.Rebin(rebin) # normalize histograms, if applicable if normalize and hist.Integral() != 0: hist.Scale(1. / hist.Integral()) plot = Plotter.Plot(hist, leg, "l", "hist") canvas.addMainPlot(plot) if linecolor: plot.SetLineColor(linecolor) if linestyle: plot.SetLineStyle(linestyle) if markercolor: plot.SetMarkerColor(markercolor) if markerstyle: plot.SetMarkerStyle(markerstyle) RT.addBinWidth(plot) # set custom axis ranges if specified in DISTRIBUTION_SPECS if logy and Yrange_min <= 0.0: Yrange_min = 1e-3 if Xrange: print('setting x ranges: {}, {}'.format(Xrange_min, Xrange_max)) canvas.firstPlot.GetXaxis().SetRangeUser(Xrange_min, Xrange_max) if Yrange: canvas.firstPlot.GetYaxis().SetRangeUser(Yrange_min, Yrange_max) if make_legend: canvas.makeLegend(pos="tl", fontscale=0.77) canvas.legend.resizeHeight() fname = output_folder + "/" + output_filename if logy: fname += "_logy" if normalize: fname += "_norm" canvas.finishCanvas() canvas.save(fname, extList=[".pdf", ".root"]) canvas.deleteCanvas()
def compareFOMPlot(quantity, sp, sigmaBMode='GLOBAL'): keys = FACTORS for FACTOR in FACTORS: s = HG.getHistogram(FILES['Signal'], (fs, sp), '{}_{}'.format(quantity, FACTOR)).Clone() if sigmaBMode == 'GLOBAL': s.Scale(ScaleFactor(sp, 1, 1.e-2)) extra = 'GLOBAL' DHists, DPConfig = HG.getDataHistograms(FILES['Data'], '{}_1'.format(quantity), addFlows=False) b = DHists['{}_1'.format(quantity)]['data'] # get cumulatives bCum = b.GetCumulative(CONFIG[quantity]['forward']) sCum = s.GetCumulative(CONFIG[quantity]['forward']) fom = {z: sCum.Clone() for z in ('ZBi', 'ZPL')} nBins = sCum.GetNbinsX() xAxis = sCum.GetXaxis() # dictionaries instead of numbers because we have 2 sets of ZBi curves fom_max = {z: 0. for z in ('ZBi', 'ZPL')} opt_cut = {z: 0. for z in ('ZBi', 'ZPL')} opt_s = {z: 0. for z in ('ZBi', 'ZPL')} opt_b = {z: 0. for z in ('ZBi', 'ZPL')} for ibin in range(1, nBins + 1): S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward']) for z in ('ZBi', 'ZPL'): if FOMs[z] > fom_max[z]: fom_max[z] = FOMs[z] opt_cut[z] = cutVal opt_s[z] = S opt_b[z] = B fom[z].SetBinContent(ibin, FOMs[z]) p = { z: Plotter.Plot(fom[z], PRETTY_LEG[z], 'l', 'hist p') for z in fom } colors = {'ZBi': R.kRed, 'ZPL': R.kBlue} c = Plotter.Canvas(lumi='({} GeV, {} GeV, {} mm){}'.format( sp[0], sp[1], sp[2], '' if FACTOR == 1 else ' #rightarrow {} mm'.format(sp[2] / FACTOR))) for z in fom: c.addMainPlot(p[z]) p[z].setColor(colors[z], which='LM') c.makeLegend(lWidth=0.1, pos='tr') #c.legend.SetMargin(0.1) c.legend.resizeHeight() lines = { z: R.TLine(opt_cut[z], 0., opt_cut[z], max(fom_max.values()) * 1.1) for z in fom } for z in fom: lines[z].SetLineStyle(2) lines[z].SetLineColor(colors[z]) lines[z].Draw() for i, z in enumerate(fom.keys()): c.drawText(text='#color[{:d}]{{opt = {:.1f}}}'.format( colors[z], opt_cut[z]), pos=(c.legend.GetX2(), c.legend.GetY1() - .04 - i * .04), align='br') c.firstPlot.SetMinimum(0.) c.firstPlot.SetMaximum(max(fom_max.values()) * 1.1) c.firstPlot.setTitles(Y='Figure of Merit') RT.addBinWidth(c.firstPlot) c.cleanup('pdfs/COMPARE_FOM-{}_{}_{}_{}_{}_{}.pdf'.format( extra, quantity, sp[0], sp[1], sp[2], FACTOR))
def makePerSamplePlots(selection=None): rebinning_exceptions = ("pTdiff", "nCSCDTHits") h = {} p = {} for dataset in HISTS: if selection is not None: selected_hists_names = getHistNames(dataset, *selection) else: selected_hists_names = HISTS[dataset] for key in selected_hists_names: # do not plot empty histograms in the interest of plotting time if HISTS[dataset][key].GetEntries() == 0: continue if key not in h: h[key] = HISTS[dataset][key].Clone() else: h[key].Add(HISTS[dataset][key]) for key in h: RT.addFlows(h[key]) if h[key].GetNbinsX() >= 1000: if any(["__" + var + "VAR" in key for var in rebinning_exceptions]): print ("Do not rebin {}".format(key)) pass else: if "__L1pTresVAR" in key or "__L2pTresVAR" in key: h[key].Rebin(2) else: h[key].Rebin(15) elif h[key].GetNbinsX() >= 100: if any(["__" + var + "VAR" in key for var in rebinning_exceptions]): print ("Do not rebin {}".format(key)) pass else: h[key].Rebin(5) else: pass if "lowerHemisphere" in key: hs_req = "lower hemisphere" elif "upperHemisphere" in key: hs_req = "upper hemisphere" else: hs_req = None if "oppositeCharges" in key: pair_charge_req = "oppositely charged pairs" elif "equalCharges" in key: pair_charge_req = "equally charged pairs" else: pair_charge_req = None if "posCharge" in key: charge_req = "positive muon tracks" elif "negCharge" in key: charge_req = "negative muon tracks" else: charge_req = None legName = "" for req in (hs_req, pair_charge_req, charge_req): if req is not None: if legName != "": legName += ", " legName += req p = Plotter.Plot(h[key], legName, "l", "hist") for is_logy in (True, False): fname = "pdfs/{}{}{}.pdf".format( key, dataset_fname, ("_logy" if is_logy else "") ) canvas = Plotter.Canvas(logy=is_logy, lumi=lumi) canvas.addMainPlot(p) if legName != "": canvas.makeLegend(lWidth=0.25, pos="tl", fontscale=0.65) canvas.legend.resizeHeight() for var in RANGES: if "__{}VAR".format(var) in key: canvas.firstPlot.GetXaxis().SetRangeUser( RANGES[var][0], RANGES[var][1] ) p.SetLineColor(R.kBlue) RT.addBinWidth(p) # Gauss fit for L2 resolution plots if any( ["__{}VAR".format(var) in key for var in L1RESOLUTIONVARIABLES] ) or any(["__{}VAR".format(var) in key for var in L2RESOLUTIONVARIABLES]): # Trigger information for canvas pave_triggerinfo = R.TPaveText(0.56, 0.38, 0.88, 0.51, "NDCNB") pave_triggerinfo.SetTextAlign(13) pave_triggerinfo.SetTextFont(42) # pave_triggerinfo.SetTextSize(self.fontsize*.9) pave_triggerinfo.SetMargin(0) pave_triggerinfo.SetFillStyle(0) pave_triggerinfo.SetFillColor(0) pave_triggerinfo.SetLineStyle(0) pave_triggerinfo.SetLineColor(0) pave_triggerinfo.SetBorderSize(0) pave_triggerinfo.AddText(0.0, 1.0, HLT_info) pave_triggerinfo.AddText(0.0, 0.5, L1T_info) pave_triggerinfo.Draw() fit_xmin, fit_xmax = findFitRange(h[key]) func = R.TF1("f" + key, "gaus", fit_xmin, fit_xmax) func.SetParameters(10.0, -0.1, 0.5) func.SetLineStyle(2) func.SetLineColor(R.kBlue + 2) R.SetOwnership(func, 0) h[key].Fit("f" + key, "RQN") func.Draw("same") pave_gaus = R.TPaveText(0.56, 0.63, 0.88, 0.83, "NDCNB") pave_gaus.SetTextAlign(13) pave_gaus.SetTextFont(42) # pave_gaus.SetTextSize(self.fontsize*.9) pave_gaus.SetMargin(0) pave_gaus.SetFillStyle(0) pave_gaus.SetFillColor(0) pave_gaus.SetLineStyle(0) pave_gaus.SetLineColor(0) pave_gaus.SetBorderSize(0) pave_gaus.AddText(0.0, 1.0, "Gaussian fit around maximum:") pave_gaus.AddText( 0.06, 0.65, "Mean = {:2.3f}".format(func.GetParameter(1)) ) pave_gaus.AddText( 0.06, 0.45, "Sigma = {:2.3f}".format(func.GetParameter(2)) ) pave_gaus.AddText( 0.06, 0.25, "#chi^{{2}} = {:2.3f}".format(func.GetChisquare()) ) # count the histogram contents to the right of the upper # fit limit (to get an estimate for the content in the tail) h_content = 0 h_content_tail = 0 fit_xmax_bin = h[key].FindBin(fit_xmax) for b in range(1, h[key].GetNbinsX() + 1): h_content += h[key].GetBinContent(b) if b > fit_xmax_bin: h_content_tail += h[key].GetBinContent(b) pave_gaus.AddText( 0.06, 0.05, "Entries above {:2.2f} (max. fit range): {:2.1f}%".format( fit_xmax, 100.0 * h_content_tail / h_content ), ) pave_gaus.Draw() try: canvas.legend.moveLegend(X=0.393, Y=-0.01) except: # continue if there is no legend pass else: # Trigger information for canvas pave_triggerinfo = R.TPaveText(0.4, 0.75, 0.72, 0.88, "NDCNB") pave_triggerinfo.SetTextAlign(13) pave_triggerinfo.SetTextFont(42) # pave_triggerinfo.SetTextSize(self.fontsize*.9) pave_triggerinfo.SetMargin(0) pave_triggerinfo.SetFillStyle(0) pave_triggerinfo.SetFillColor(0) pave_triggerinfo.SetLineStyle(0) pave_triggerinfo.SetLineColor(0) pave_triggerinfo.SetBorderSize(0) pave_triggerinfo.AddText(0.0, 1.0, HLT_info) pave_triggerinfo.AddText(0.0, 0.5, L1T_info) pave_triggerinfo.Draw() pave = canvas.makeStatsBox(p, color=R.kBlue) pave_triggerinfo.Draw() # find the corresponding d0 distribution in the given d0 bin # and display its mean try: current_var = re.findall(r"__(.+)VAR", key) if len(current_var) == 1: current_var = current_var[0].split("_")[-1] if current_var != "d0" and all( [c in key for c in ("__d0GT", "__d0LT")] ): d0_hist = key.replace("__{}VAR".format(current_var), "__d0VAR") for idataset, dataset in enumerate(HISTS): if idataset == 0: h_d0 = HISTS[dataset][d0_hist].Clone() else: h_d0.Add(HISTS[dataset][d0_hist]) d0_mean = h_d0.GetMean() # d0_mean = HISTS[dataset][d0_hist].GetMean() d0_min = re.findall(r"__d0GT(\d+)p(\d+)", d0_hist) if len(d0_min) > 0: d0_min = float("{}.{}".format(d0_min[0][0], d0_min[0][1])) else: d0_min = float(re.findall(r"__d0GT(\d+)", d0_hist)[0]) d0_max = re.findall(r"__d0LT(\d+)p(\d+)", d0_hist) if len(d0_max) > 0: d0_max = float("{}.{}".format(d0_max[0][0], d0_max[0][1])) else: d0_max = float(re.findall(r"__d0LT(\d+)", d0_hist)[0]) pave_d0info = R.TPaveText(0.56, 0.53, 0.88, 0.61, "NDCNB") pave_d0info.SetTextAlign(13) pave_d0info.SetTextFont(42) pave_d0info.SetMargin(0) pave_d0info.SetFillStyle(0) pave_d0info.SetFillColor(0) pave_d0info.SetLineStyle(0) pave_d0info.SetLineColor(0) pave_d0info.SetBorderSize(0) pave_d0info.AddText( 0.0, 1.0, "{} cm < d_{{0}} < {} cm".format(d0_min, d0_max) ) pave_d0info.AddText( 0.0, 0.0, "#LTd_{{0}}#GT = {:4.3f} cm".format(d0_mean) ) pave_d0info.Draw() except KeyError: # not all of the histograms have d0 equivalents (e.g., # 'oppositeCharges' pair histos,...) print ( "[PLOTTER WARNING] Error processing d0 information " "for {}; will not be printed on canvas".format(key) ) canvas.cleanup(fname) return
def makeKinkFOMPlot(quantity, masses, sigmaBMode='DEFAULT'): points = sorted( [sp for sp in SignalInfo if sp[0] == masses[0] and sp[1] == masses[1]], key=lambda x: x[2]) s = { points[0]: HG.getHistogram(FILES['Signal'], (fs, points[0]), '{}_1'.format(quantity)).Clone(), points[1]: HG.getHistogram(FILES['Signal'], (fs, points[1]), '{}_10'.format(quantity)).Clone(), } if sigmaBMode == 'DEFAULT': s[points[0]].Scale(ScaleFactor(points[0], 1)) s[points[1]].Scale(ScaleFactor(points[1], 10)) extra = '' elif sigmaBMode == 'SAME': s[points[0]].Scale(ScaleFactor(points[0], 1)) s[points[1]].Scale(ScaleFactor(points[0], 1)) extra = '_SAME' elif sigmaBMode == 'GLOBAL': s[points[0]].Scale(ScaleFactor(points[0], 1, 1.e-2)) s[points[1]].Scale(ScaleFactor(points[1], 1, 1.e-2)) extra = '_GLOBAL' DHists, DPConfig = HG.getDataHistograms(FILES['Data'], '{}_1'.format(quantity), addFlows=False) b = DHists['{}_1'.format(quantity)]['data'] # get cumulatives bCum = b.GetCumulative(CONFIG[quantity]['forward']) sCum = {p: s[p].GetCumulative(CONFIG[quantity]['forward']) for p in points} fom = {p: sCum[p].Clone() for p in points} nBins = sCum[points[0]].GetNbinsX() xAxis = sCum[points[0]].GetXaxis() # dictionaries instead of numbers because we have 2 sets of ZBi curves fom_max = {p: 0. for p in points} opt_cut = {p: 0. for p in points} opt_s = {p: 0. for p in points} opt_b = {p: 0. for p in points} for ibin in range(1, nBins + 1): for p in points: S, B, cutVal, FOMs = calculateFOM(s[p], b, sCum[p], bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward']) if FOMs[FIGURE_OF_MERIT] > fom_max[p]: fom_max[p] = FOMs[FIGURE_OF_MERIT] opt_cut[p] = cutVal opt_s[p] = S opt_b[p] = B fom[p].SetBinContent(ibin, FOMs[FIGURE_OF_MERIT]) pl = { points[0]: Plotter.Plot(fom[points[0]], 'c#tau = {} mm, nominal'.format(points[0][2]), 'l', 'hist p'), points[1]: Plotter.Plot(fom[points[1]], 'c#tau = {} mm, reweighted'.format(points[0][2]), 'l', 'hist p'), } colors = { points[0]: R.kBlue, points[1]: R.kRed, } c = Plotter.Canvas(lumi='({} GeV, {} GeV)'.format(*masses)) c.addMainPlot(pl[points[0]]) c.addMainPlot(pl[points[1]]) for p in points: pl[p].setColor(colors[p], which='LM') c.makeLegend(lWidth=0.3, pos='tr') c.legend.SetMargin(0.1) c.legend.resizeHeight() lines = { p: R.TLine(opt_cut[p], 0., opt_cut[p], max(fom_max.values()) * 1.1) for p in points } for p in points: lines[p].SetLineStyle(2) lines[p].SetLineColor(colors[p]) lines[p].Draw() for i, p in enumerate(points): c.drawText(text='#color[{:d}]{{opt = {:.1f}}}'.format( colors[p], opt_cut[p]), pos=(c.legend.GetX2(), c.legend.GetY1() - .04 - i * .04), align='br') c.firstPlot.SetMinimum(0.) c.firstPlot.SetMaximum(max(fom_max.values()) * 1.1) c.firstPlot.setTitles(Y=PRETTY_LEG) RT.addBinWidth(c.firstPlot) c.cleanup('pdfs/KINK_FOM{}_{}_{}_{}_{}.pdf'.format(extra, quantity, masses[0], masses[1], FIGURE_OF_MERIT))
def makeResPlots(metric, quantity, sp=None): PRETTY = { 'pTRes_hits_less': { 'mnice': 'p_{T} res.', 'qnice': 'N(hits)', 'leg': 'N(hits) #leq 12', 'col': R.kRed }, 'pTRes_hits_more': { 'mnice': 'p_{T} res.', 'qnice': 'N(hits)', 'leg': 'N(hits) > 12', 'col': R.kBlue }, 'pTRes_fpte_less': { 'mnice': 'p_{T} res.', 'qnice': '#sigma_{p_{T}}/p_{T}', 'leg': '#sigma_{p_{T}}/p_{T} < 1', 'col': R.kBlue }, 'pTRes_fpte_more': { 'mnice': 'p_{T} res.', 'qnice': '#sigma_{p_{T}}/p_{T}', 'leg': '#sigma_{p_{T}}/p_{T} #geq 1', 'col': R.kRed }, 'qdiff_hits_less': { 'mnice': 'charge diff.', 'qnice': 'N(hits)', 'leg': 'N(hits) #leq 12', 'col': R.kRed }, 'qdiff_hits_more': { 'mnice': 'charge diff.', 'qnice': 'N(hits)', 'leg': 'N(hits) > 12', 'col': R.kBlue }, 'qdiff_fpte_less': { 'mnice': 'charge diff.', 'qnice': '#sigma_{p_{T}}/p_{T}', 'leg': '#sigma_{p_{T}}/p_{T} < 1', 'col': R.kBlue }, 'qdiff_fpte_more': { 'mnice': 'charge diff.', 'qnice': '#sigma_{p_{T}}/p_{T}', 'leg': '#sigma_{p_{T}}/p_{T} #geq 1', 'col': R.kRed }, } witches = ('less', 'more') if quantity == 'fpte' else ('more', 'less') hkeys = ['{}_{}_{}'.format(metric, quantity, which) for which in witches] if sp is None: HISTS = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', hkeys) else: HISTS = {} for key in hkeys: HISTS[key] = HG.getHistogram(FILES['Signal'], ('2Mu2J', sp), key).Clone() PLOTS = {} for key in hkeys: HISTS[key].Scale(1. / HISTS[key].Integral(0, HISTS[key].GetNbinsX() + 1)) #RT.addFlows(HISTS[key]) PLOTS[key] = Plotter.Plot(HISTS[key], PRETTY[key]['leg'], 'l', 'hist') #canvas = Plotter.Canvas(lumi='{} by {}'.format(PRETTY[hkeys[0]]['mnice'], PRETTY[hkeys[0]]['qnice'])) lumi = 'H#rightarrow2X#rightarrow2#mu' if sp is None: lumi += ', all samples combined' else: lumi += ' ({} GeV, {} GeV, {} mm)'.format(*sp) canvas = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800) for key in hkeys: canvas.addMainPlot(PLOTS[key]) PLOTS[key].setColor(PRETTY[key]['col'], which='L') canvas.firstPlot.SetMinimum(0.) canvas.setMaximum() if metric == 'qdiff': canvas.firstPlot.SetMaximum(1.) canvas.firstPlot.setTitles(Y='Density') if 'qdiff' in hkeys[0]: canvas.firstPlot.SetNdivisions(3) canvas.makeLegend(lWidth=0.27, pos='tr') canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) if ARGS.SQUARE: canvas.firstPlot.scaleTitleOffsets(1.1, 'X') if metric == 'pTRes': canvas.firstPlot.scaleTitleOffsets(1.3, 'Y') canvas.cleanup('pdfs/QCUTRES_Sig_{}_{}_{}.pdf'.format( metric, quantity, 'Global' if sp is None else SPStr(sp)), mode='LUMI')
def makeEffPlots(quantity, fs, SP=None): range_limits = { 'pT': [0., 300.], 'eta': None, 'phi': None, 'd0': None, 'Lxy': [0., (500. if SP is None else \ SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['xmax'])], 'deltaR': None, 'mass': None, 'cosAlpha': None, 'dimuonPTOverM': [0, 10], 'XBeta': None, } HKeys = { 'GEN_Eff' : 'GEN_{}Num' , 'GEN_Den' : 'GEN_{}Den' , 'DSA_Eff' : 'DSA_{}Num' , 'DSA_Den' : 'DSA_{}Den' , 'RSA_Eff' : 'RSA_{}Num' , 'RSA_Den' : 'RSA_{}Den' , } for key in HKeys: HKeys[key] = HKeys[key].format(quantity, 'HTo2XTo'+fs) h = {} p = {} g = {} hm = {} if SP is None: for i, sp in enumerate(SIGNALPOINTS): if i == 0: for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) else: for key in HKeys: h[key].Add(HISTS[(fs, sp)][HKeys[key]]) else: sp = SP for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].SetDirectory(0) for key in HKeys: RT.addFlows(h[key]) nConcatBins = 20 if SP is None else \ SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['rebin'] h[key].Rebin(nConcatBins) # h[key].Rebin(30) NumDens = ( ('GEN_Eff' , 'GEN_Den' , 'GEN' , R.kGreen ), ('DSA_Eff' , 'DSA_Den' , 'DSA' , R.kBlue ), ('RSA_Eff' , 'RSA_Den' , 'RSA' , R.kRed ), ) for num, den, leg, col in NumDens: g[num] = R.TGraphAsymmErrors(h[num], h[den], 'cp') g[num].SetNameTitle('g_'+num, ';'+h[num].GetXaxis().GetTitle()+'; Trigger Efficiency') # g[num].GetXaxis().SetRangeUser(0., 30.) if range_limits[quantity] is not None: g[num].GetXaxis().SetLimits( range_limits[quantity][0], range_limits[quantity][1]) p[num] = Plotter.Plot(g[num], leg, 'elp', 'pe') h[num].Sumw2() h[den].Sumw2() ratio_hist = R.TEfficiency(h[num], h[den]) eff_sum_num = 0 eff_sum_den = 0 for binx in range(1,h[num].GetXaxis().GetNbins()+2): # if h[num].GetBinLowEdge(binx) > 250: continue glob_bin = ratio_hist.GetGlobalBin(binx) efferror = max(ratio_hist.GetEfficiencyErrorLow(glob_bin), ratio_hist.GetEfficiencyErrorUp(glob_bin)) if efferror != 0: eff_sum_num += ratio_hist.GetEfficiency(glob_bin) / \ (efferror*efferror) if ratio_hist.GetEfficiency(glob_bin) != 0: eff_sum_den += 1/(efferror*efferror) if eff_sum_den != 0: hm[num] = eff_sum_num / eff_sum_den FIRST = (0, 3) # SECOND = (3, 5) CHARGE = '' for SECTION in (FIRST,): fraction_str = '' if SP is None else '[{}%, {}%]'.format( round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][0], 1), round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][1], 1)) canvas = Plotter.Canvas(lumi = fs if SP is None else \ '{} ({} GeV, {} GeV, {} mm) ' \ '#scale[0.7]{{{fraction_str}}}'.format( fs, *SP, fraction_str=fraction_str)) for i in range(SECTION[0], SECTION[1]): key = NumDens[i][0] col = NumDens[i][3] canvas.addMainPlot(p[key]) p[key].SetMarkerColor(col) p[key].SetLineColor(col) # if quantity in ['Lxy','pT']: # axis_min = p[key].GetXaxis().GetBinLowEdge(1) # axis_max = p[key].GetXaxis().GetBinLowEdge(p[key].GetXaxis().GetNbins()+1) # hline = R.TLine(axis_min, hm[key], range_limits[quantity][1], hm[key]) # R.SetOwnership(hline, 0) # hline.SetLineColor(col) # hline.Draw() canvas.makeLegend(pos='tr') canvas.legend.moveLegend(X=-0.18) canvas.legend.resizeHeight() canvas.firstPlot.SetMinimum(0.) canvas.firstPlot.SetMaximum(1.) RT.addBinWidth(canvas.firstPlot) if quantity == 'pT': vline = R.TLine(28.,0.,28.,1.) # draw vertical line at 28 GeV R.SetOwnership(vline, 0) vline.SetLineColor(15) vline.Draw() canvas.cleanup(OUTPUT_PATH + FILENAME_OUT.format('STE', LXYMIN, LXYMAX, quantity, fs, 'Global' if SP is None else SPStr(SP)))
def makeCombinedPlots(categories, selection=None, exclude=None, logic="and"): rebinning_exceptions = ("nCSCDTHits",) h = {} p = {} # import all relevant histograms for dataset in HISTS: if selection and exclude: selected_hists_names = getHistNames( dataset, *selection, exclude=exclude, logic=logic ) elif selection and not exclude: selected_hists_names = getHistNames(dataset, *selection, logic=logic) elif not selection and exclude: selected_hists_names = getHistNames( dataset, "", exclude=exclude, logic=logic ) else: selected_hists_names = HISTS[dataset] for key in selected_hists_names: if not any([cat in key for cat, __ in categories]): continue search_res = re.search(r"__(.+)VAR", key) if search_res: variable = search_res.group(1) else: print ("Skipping {} (unidentifiable variable)...".format(key)) continue if variable not in h.keys(): h[variable] = {} for category, __ in categories: if not category in key: continue if category in h[variable]: h[variable][category].Add(HISTS[dataset][key]) else: h[variable][category] = HISTS[dataset][key].Clone() # prepare the histograms for variable in h: for category in h[variable]: RT.addFlows(h[variable][category]) if h[variable][category].GetNbinsX() >= 1000: if variable in rebinning_exceptions: print ("Do not rebin for variable {}".format(variable)) pass else: h[variable][category].Rebin(15) elif h[variable][category].GetNbinsX() >= 100: if variable in rebinning_exceptions: print ("Do not rebin for variable {}".format(variable)) pass else: h[variable][category].Rebin(5) else: pass # start creating plots for variable in h: p[variable] = {} # find the best vertical axes ranges realmin = float("inf") realmax = -float("inf") for category, category_name in categories: p[variable][category] = Plotter.Plot( h[variable][category], category_name, "l", "hist" ) key_fname = h[variable][category].GetName() key_fname = key_fname.replace(category, "") if len(HISTS.keys()) > 1: search_res = re.search(r"(_*?NoBPTXRun\d+[A-Z][_-]07Aug17)", key_fname) if search_res: key_fname = key_fname.replace(search_res.group(0), "") else: print ( "Could not identify datset. Dataset name will not be " "stripped from the output file names" ) if p[variable][category].GetMaximum() > realmax: realmax = p[variable][category].GetMaximum() if p[variable][category].GetMaximum() < realmin: realmin = p[variable][category].GetMinimum() for is_logy in (True, False): palette = Plotter.ColorPalette([867, 417, 600, 600, 801, 632]) fname = "pdfs/comb_{}{}.pdf".format(key_fname, ("_logy" if is_logy else "")) canvas = Plotter.Canvas(logy=is_logy, lumi="NoBPTXRun2016[D+E]-07Aug17") for category, category_name in categories: canvas.addMainPlot(p[variable][category]) p[variable][category].SetLineColor(palette.getNextColor()) if "goodQuality" in category: p[variable][category].SetLineStyle(2) RT.addBinWidth(p[variable][category]) if variable in RANGES: canvas.firstPlot.GetXaxis().SetRangeUser( RANGES[variable][0], RANGES[variable][1] ) canvas.makeLegend(lWidth=0.3, pos="tr", fontscale=0.65) canvas.legend.resizeHeight() canvas.legend.moveLegend(X=-0.2, Y=-0.13) # trigger information for canvas pave_triggerinfo = R.TPaveText(0.4, 0.75, 0.72, 0.88, "NDCNB") pave_triggerinfo.SetTextAlign(13) pave_triggerinfo.SetTextFont(42) # pave_triggerinfo.SetTextSize(self.fontsize*.9) pave_triggerinfo.SetMargin(0) pave_triggerinfo.SetFillStyle(0) pave_triggerinfo.SetFillColor(0) pave_triggerinfo.SetLineStyle(0) pave_triggerinfo.SetLineColor(0) pave_triggerinfo.SetBorderSize(0) pave_triggerinfo.AddText(0.0, 1.0, HLT_info) pave_triggerinfo.AddText(0.0, 0.5, L1T_info) pave_triggerinfo.Draw() if is_logy and realmin == 0: realmin = 0.5 canvas.firstPlot.GetYaxis().SetRangeUser(realmin * 0.8, realmax * 1.2) # canvas.cleanup(fname.replace('.pdf','.root')) canvas.cleanup(fname)
def makeStackPlots(DataMC=False, logy=False): BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'DY10to50', 'DY50toInf') for hkey in HISTS['DY50toInf']: h = { # 'Data' : HISTS['DoubleMuonRun2016D-07Aug17'][hkey].Clone(), # 'Signal' : HISTS[('4Mu', (125, 20, 13)) ][hkey].Clone(), 'BG': R.THStack('hBG', '') } PConfig = { # 'Data' : ('DoubleMuon2016D' , 'pe', 'pe' ), # 'Signal' : ('H#rightarrow2X#rightarrow4#mu', 'l' , 'hist'), 'BG': ('', '', 'hist'), } PC = HistogramGetter.PLOTCONFIG for key in BGORDER: h[key] = HISTS[key][hkey].Clone() RT.addFlows(h[key]) if h[key].GetNbinsX() > 100: h[key].Rebin(10) h[key].Scale(PC[key]['WEIGHT']) PConfig[key] = (PC[key]['LATEX'], 'f', 'hist') h['BG'].Add(h[key]) p = {} for key in h: p[key] = Plotter.Plot(h[key], *PConfig[key]) fname = 'pdfs/NM1_{}_Stack{}.pdf'.format(hkey, '-Log' if logy else '') for key in BGORDER: p[key].setColor(PC[key]['COLOR'], which='LF') canvas = Plotter.Canvas(ratioFactor=0. if not DataMC else 1. / 3., cHeight=600 if not DataMC else 800, logy=logy) canvas.addMainPlot(p['BG']) # canvas.addMainPlot(p['Data']) # canvas.addMainPlot(p['Signal']) canvas.lumi += ' : |#Delta#Phi| ' + ('<' if '_Less' in key else '>') + ' #pi/2' canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8) # canvas.addLegendEntry(p['Data' ]) for key in reversed(BGORDER): canvas.addLegendEntry(p[key]) # canvas.addLegendEntry(p['Signal']) canvas.legend.resizeHeight() p['BG'].setTitles(X=p['WJets'].GetXaxis().GetTitle(), Y='Normalized Counts') RT.addBinWidth(p['BG']) canvas.firstPlot.SetMaximum(h['BG'].GetStack().Last().GetMaximum() * 1.05) #canvas.firstPlot.SetMaximum(1.e-4) # if DataMC: # canvas.makeRatioPlot(p['Data'].plot, p['BG'].plot.GetStack().Last()) # p['Signal' ].SetLineStyle(2) # p['Signal' ].SetLineColor(R.kRed) canvas.cleanup(fname)
def makeSimplePlots(quantity, fs, SP=None, normalize=False): range_limits = { 'pT': [0., 300.], 'eta': None, 'phi': None, 'd0': None, 'Lxy': [0., (500. if SP is None else \ SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['xmax'])], 'deltaR': None, 'mass': None, 'cosAlpha': None, 'dimuonPTOverM': [0, 10], 'XBeta': None, } HKeys = { 'GEN_Den' : 'GEN_{}Den', 'DSA_Den' : 'DSA_{}Den', 'RSA_Den' : 'RSA_{}Den', } for key in HKeys: HKeys[key] = HKeys[key].format(quantity, 'HTo2XTo'+fs) h = {} p = {} if SP is None: for i, sp in enumerate(SIGNALPOINTS): if i == 0: for key in HKeys: h[key] = HISTS[(fs, sp)][HKeys[key]].Clone() h[key].Sumw2() h[key].SetDirectory(0) else: for key in HKeys: h[key].Sumw2() h[key].Add(HISTS[(fs, sp)][HKeys[key]]) else: for key in HKeys: h[key] = HISTS[(fs, SP)][HKeys[key]].Clone() h[key].Sumw2() if normalize is True and h[key].Integral() != 0: h[key].Scale(1/h[key].Integral()) h[key].SetDirectory(0) for key in HKeys: RT.addFlows(h[key]) nConcatBins = 20 if SP is None else \ SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['rebin'] h[key].Rebin(nConcatBins) if quantity == 'deltaR': ratio_cut = 0.5 hist_ratios = {} for key in HKeys: num_before_cut = 0 num_after_cut = 0 for i in range(h[key].GetNbinsX()+1): if h[key].GetXaxis().GetBinCenter(i) < ratio_cut: num_before_cut += h[key].GetBinContent(i) else: num_after_cut += h[key].GetBinContent(i) if num_before_cut+num_after_cut != 0: hist_ratios[key] = 1.0*num_before_cut/(num_before_cut+num_after_cut) else: hist_ratios[key] = -1 HistSpecs = ( ('GEN_Den', 'GEN', R.kGreen, 'Yield [a.u.]'), ('DSA_Den', 'DSA', R.kBlue, 'Yield [a.u.]'), ('RSA_Den', 'RSA', R.kRed, 'Yield [a.u.]'), ) for key, leg, col, yTitle in HistSpecs: if range_limits[quantity] is not None: h[key].GetXaxis().SetRangeUser( range_limits[quantity][0], range_limits[quantity][1]) h[key].SetNameTitle('h_'+key, ';'+h[key].GetXaxis().GetTitle() + '; ' + \ ('Normalized ' if normalize is True else '') + yTitle) # leg += (': yield(#Delta R<0.5) #times 100 / (total yield) = {}'.format( # round(hist_ratios[key]*100,2)) if quantity == 'deltaR' else '') p[key] = Plotter.Plot(h[key], leg, '', 'hist e1 x0') FIRST = (0, 3) CHARGE = '' for SECTION in (FIRST,): fraction_str = '' if SP is None else '[{}%, {}%]'.format( round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][0], 1), round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][1], 1)) canvas = Plotter.Canvas(lumi = fs if SP is None else \ '{} ({} GeV, {} GeV, {} mm) ' \ '#scale[0.7]{{{fraction_str}}}'.format( fs, *SP, fraction_str=fraction_str)) for i in range(SECTION[0], SECTION[1]): key = HistSpecs[i][0] col = HistSpecs[i][2] yTitle = HistSpecs[i][3] canvas.addMainPlot(p[key]) p[key].SetMarkerColor(col) p[key].SetLineColor(col) # p[key].firstPlot.SetYTitle(yTitle) canvas.makeLegend(pos='tl') canvas.legend.moveLegend(X=0.15) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) canvas.cleanup(OUTPUT_PATH + FILENAME_OUT.format('STD', LXYMIN, LXYMAX, quantity, fs, 'Global' if SP is None else SPStr(SP)))