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 makePlot(mtype, vtype, quantity, which): hkey = '{}_{}_{}'.format(mtype, vtype, quantity) if which == 'Signal': HISTS = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', hkey) h = HISTS[hkey] elif which == 'Data': HISTS, PConfig = HG.getDataHistograms(FILES['Data'], hkey, addFlows=False) h = HISTS[hkey]['data'] p = Plotter.Plot(h, '', '', 'hist') c = Plotter.Canvas() c.addMainPlot(p) p.setColor(R.kBlue) if hkey == 'Prox_PD_deltaR' or hkey == 'Prox_PP_deltaR': s = 0 print hkey, which for ibin in xrange(1, p.GetNbinsX() + 1): s += p.GetBinContent(ibin) print p.GetXaxis().GetBinLowEdge(ibin), p.GetBinContent(ibin), s s = c.makeStatsBox(p, R.kBlue) c.cleanup(hkey + '_' + which + '.pdf')
def fillData(fs, sp, quantity, factor): # get histograms s = HG.getHistogram(FILES['Signal'], (fs, sp), '{}_{}'.format(quantity, factor)).Clone() DHists, DPConfig = HG.getDataHistograms(FILES['Data'], '{}_1'.format(quantity), addFlows=False) b = DHists['{}_1'.format(quantity)]['data'] if SignalInfo[sp]['sigmaBLimit'] == 0.: return s.Scale(ScaleFactor(sp, factor, 1.e-2)) # get cumulatives sCum = s.GetCumulative(CONFIG[quantity]['forward']) bCum = b.GetCumulative(CONFIG[quantity]['forward']) # fill f.o.m. histogram, and keep track of max f.o.m. and cut value nBins = sCum.GetNbinsX() xAxis = sCum.GetXaxis() fom_max = 0. opt_cut = 0. opt_s = 0. opt_b = 0. for ibin in range(1,nBins+1): S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward']) if FOMs[FIGURE_OF_MERIT] > fom_max: fom_max = FOMs[FIGURE_OF_MERIT] opt_cut = cutVal opt_s = S opt_b = B # for each (mH, mX) pair, store the xvalue: cTau (mm) / 10 -> cm, divided by factor # this will run for each sample point, meaning afterwards, the (mH, mX) x and y lists # will have len(factors) * 2 (maybe 3 if we put the small lifetimes in) points masses = (sp[0], sp[1]) cTau = sp[-1] DATA[masses][quantity]['x'].append(cTau/10./factor) DATA[masses][quantity]['y'].append(opt_cut)
def fillData(fs, sp, quantity, hkey): # get histograms s = HG.getHistogram(FILES['Signal'], (fs, sp), hkey) DHists, DPConfig = HG.getDataHistograms(FILES['Data'], hkey, addFlows=False) b = DHists[hkey]['data'] if SignalInfo[sp]['sigmaBLimit'] == 0.: return s.Scale(ScaleFactor(sp, sigmaB=1.e-2)) # get cumulatives sCum = s.GetCumulative(CONFIG[quantity]['forward']) bCum = b.GetCumulative(CONFIG[quantity]['forward']) # fill f.o.m. histogram, and keep track of max f.o.m. and cut value nBins = sCum.GetNbinsX() xAxis = sCum.GetXaxis() data = [] for ibin in range(1, nBins + 1): S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward']) for gridPoint in CONFIG[quantity]['VALS']: if abs(cutVal - gridPoint) < .01: data.append({ 'cut': cutVal, 'ZBi': FOMs['ZBi'], 'ZPL': FOMs['ZPL'], 's': S, 'b': B }) break DATA[hkey] = data
'hMoreLxySig', 'hLessDeltaPhi', 'hMoreDeltaPhi', ], 'Full': ['LxySig_IDPHI', 'LxySig_DPHI'], } DHists = {'Prompt': {}, 'Full': {}} for which in keyList: if which == 'Prompt': for key in keyList[which]: DHists[which][key] = HG.getHistogram(FILES[which], 'Data', key).Clone() else: D, P = HG.getDataHistograms(FILES[which], keyList[which], addFlows=False) DHists[which] = {key: D[key]['data'] for key in D} #### Correction factors from "inverted PAT" CR and SR #### # these are 0.5 bins #DHists['Prompt']['hLessLxySig'].GetXaxis().SetRange(1, 12) #DHists['Prompt']['hMoreLxySig'].GetXaxis().SetRange(1, 12) # now they're 1 bins DHists['Prompt']['hLessLxySig'].Rebin(2) DHists['Prompt']['hMoreLxySig'].Rebin(2) # up to 6
} SCALED = {sp: HISTS[sp].Clone() for sp in SIGNALPOINTS} for sp in SIGNALPOINTS: integral = SCALED[sp].Integral(0, SCALED[sp].GetNbinsX() + 1) SCALED[sp].Scale(1. / (integral if integral != 0. else 1.)) CUM = {sp: SCALED[sp].GetCumulative() for sp in SIGNALPOINTS} DISTS = { sp: Plotter.Plot(HISTS[sp], 'm_{{X}} = {} GeV'.format(sp[1]), 'l', 'hist') for sp in SIGNALPOINTS } PLOTS = { sp: Plotter.Plot(CUM[sp], 'm_{{X}} = {} GeV'.format(sp[1]), 'l', 'hist') for sp in SIGNALPOINTS } HISTS['data'] = HG.getDataHistograms(DFILE, 'mass')[0]['mass']['data'] SCALED['data'] = HISTS['data'].Clone() SCALED['data'].Scale( 1. / SCALED['data'].Integral(0, SCALED['data'].GetNbinsX() + 1)) CUM['data'] = SCALED['data'].GetCumulative() DISTS['data'] = Plotter.Plot(HISTS['data'], 'Data', 'l', 'hist p') PLOTS['data'] = Plotter.Plot(CUM['data'], 'Data', 'l', 'hist p') cols = [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163)] cols = [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195)] rcols = { 7000 + i: R.TColor(7000 + i, *(c / 255. for c in cols[i])) for i in xrange(4) } COLORS = {20: 7000, 50: 7001, 150: 7002, 350: 7003}
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 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 optimizeCut(fs, sp, quantity): # get histograms s = HG.getHistogram(FILES['Signal'], (fs, sp), quantity) DHists, DPConfig = HG.getDataHistograms(FILES['Data'], quantity) b = DHists[quantity]['data'] n = s.Integral(0, s.GetNbinsX()+1) s.Scale(ScaleFactor(sp, sigmaB=1.e-2)) # get cumulatives sCum = s.GetCumulative(CONFIG[quantity]['forward']) bCum = b.GetCumulative(CONFIG[quantity]['forward']) fom = sCum.Clone() print '**** Data (|DeltaPhi| > Pi/2) vs. HTo2XTo{} ({} GeV, {} GeV, {} mm) (|DeltaPhi| < Pi/2)'.format(fs, *sp) print '**** Quantity = {:s} ::: Passing (N-1) = {:.0f} ::: N_gen = {:.0f} ::: Sigma*B = {:.3f} pb ::: 2016 ILumi = 35922 /pb'.format( CONFIG[quantity]['pretty'], n, SignalInfo[sp]['sumWeights'][1], SignalInfo[sp]['sigmaBLimit']) print '{:>8s} {:>7s} {:>7s} {:>7s} {:>6s} {:>6s}'.format('CutVal', 'S', 'B=nOff', 'S+B=nOn', 'ZBi', 'ZPL') # fill f.o.m. histogram, and keep track of max f.o.m. and cut value nBins = sCum.GetNbinsX() xAxis = sCum.GetXaxis() fom_max = 0. opt_cut = 0. opt_s = 0. opt_b = 0. for ibin in range(1,nBins+1): S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward']) print '{:8.3f} {:7.3f} {:7.3f} {:7.3f} {:6.3f} {:6.3f}'.format(cutVal, S, B, S+B, FOMs['ZBi'], FOMs['ZPL']) if FOMs[FIGURE_OF_MERIT] > fom_max: fom_max = FOMs[FIGURE_OF_MERIT] opt_cut = cutVal opt_s = S opt_b = B fom.SetBinContent(ibin, FOMs[FIGURE_OF_MERIT]) # make plots p = {} p['sig'] = Plotter.Plot(sCum, 'signal' , 'l', 'hist') p['bg' ] = Plotter.Plot(bCum, 'data' , 'l', 'hist') p['fom'] = Plotter.Plot(fom , PRETTY_LEG , 'l', 'hist') # make canvas, colors, maximum canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp)) canvas.addMainPlot(p['sig']) canvas.addMainPlot(p['bg' ]) canvas.addMainPlot(p['fom']) p['sig'].SetLineColor(R.kBlue ) p['bg' ].SetLineColor(R.kRed ) p['fom'].SetLineColor(R.kGreen) canvas.setMaximum() canvas.firstPlot.SetMinimum(0.) # scale f.o.m. and make new axis fom.Scale(canvas.firstPlot.GetMaximum()/fom_max/1.05) axis = R.TGaxis(xAxis.GetXmax(), 0., xAxis.GetXmax(), canvas.firstPlot.GetMaximum(), 0., fom_max*1.05, 510, '+L') for attr in ('LabelFont', 'LabelOffset', 'TitleFont', 'TitleOffset', 'TitleSize'): getattr(axis, 'Set'+attr)(getattr(xAxis, 'Get'+attr)()) axis.SetTitle('Figure of Merit') axis.CenterTitle() axis.Draw() canvas.scaleMargins(1.1, edges='R') # make the legend after canvas.makeLegend(lWidth=.2, pos='br') canvas.legend.resizeHeight() canvas.legend.moveLegend(X=-.2, Y=.1) # draw optimum text and line x, y = canvas.legend.GetX1(), canvas.legend.GetY2() canvas.drawText(text='#color[{:d}]{{opt. cut = {:.2f}}}'.format(R.kBlack, opt_cut), pos=(x, y+0.05), align='bl') line = R.TLine(opt_cut, 0., opt_cut, canvas.firstPlot.GetMaximum()) line.SetLineStyle(2) line.Draw() # save canvas.cleanup('pdfs/OPT_{}_{}_HTo2XTo{}_{}.pdf'.format(quantity, FIGURE_OF_MERIT, fs, SPStr(sp)))
def makeDataPlot(key): h, pconfig = HG.getDataHistograms(FILES['Data'], key) h = h[key]['data'] p = Plotter.Plot(h, '', '', 'pe') RT.addBinWidth(p) c = Plotter.Canvas(lumi='Data 2016, 36.3 fb^{{-1}} (13 TeV), {}'.format( CUTS[key]['lumi']), cWidth=600 if key != 'deltaPhi' else 800, logy=CUTS[key]['logy']) c.addMainPlot(p) c.firstPlot.setColor(R.kBlack) 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_Data_{}.pdf'.format(key), mode='LUMI')
import ROOT as R import DisplacedDimuons.Analysis.HistogramGetter as HG import DisplacedDimuons.Analysis.Plotter as Plotter # the input histogram here is just two histograms with LxySig < 6 and DeltaPhi < pi/4 and > 3pi/4 separately # the script to make it is validateBackground which is in oldscripts now # this script makes a little less sense now, also it is superseded by smallLxySigConsistency, # but I'm leaving it here in case you want to see how to to the KS probability f = R.TFile.Open('roots/ValidationPlots_DATA.root') D, P = HG.getDataHistograms(f, ('LxySig_DPHI', 'LxySig_IDPHI'), addFlows=False) h = {k: D[k]['data'] for k in D} c = {k: h[k].GetCumulative(False) for k in h} cumRatio = c['LxySig_IDPHI'].Clone() cumRatio.Divide(c['LxySig_DPHI']) for k in h: h[k].Rebin(5) distRatio = h['LxySig_IDPHI'].Clone() distRatio.Divide(h['LxySig_DPHI']) pDist = { k: Plotter.Plot(h[k], '#Delta#Phi {} #pi/2'.format('<' if '_DPHI' in k else '>'), 'lp', 'hist e') for k in h
def makeIntegratedSEQMC(hkey='SEQ'): if DODATA: HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey, extraScale=DATASCALE) DATAHISTS, DataPConfig = HG.getDataHistograms(FILES['Data'], hkey) else: HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey) HISTS = HISTS[hkey] PConfig = PConfig[hkey] if DODATA: DATAHISTS = DATAHISTS[hkey] PConfig['data'] = DataPConfig[hkey]['data'] PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) if DODATA: PLOTS['data'] = Plotter.Plot(DATAHISTS['data'], *PConfig['data']) canvas = Plotter.Canvas( lumi='MC' if not DODATA else 'MC + Data', logy=True, cWidth=1600, ) # ratioFactor=0. if not DODATA else 1./3., fontscale=1. if not DODATA else 1.+1./3.) for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) if DODATA: canvas.addMainPlot(PLOTS['data']) setBinLabels(canvas) canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8) # if not DODATA else 1.) if DODATA: canvas.addLegendEntry(PLOTS['data']) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() canvas.legend.moveLegend(X=.1) canvas.firstPlot.setTitles(X='Cut', Y='Normalized Counts') canvas.firstPlot.SetMaximum(2.e7) canvas.firstPlot.SetMinimum(1.e4 if 'DSA' not in hkey else 1.e-1) canvas.scaleMargins(.5, 'L') canvas.firstPlot.scaleTitleOffsets(.5, 'Y') R.TGaxis.SetExponentOffset(0., 0.02, "y") # if DODATA: # canvas.makeRatioPlot(PLOTS['data'].plot, PLOTS['stack'].plot.GetStack().Last()) # canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y') # canvas.rat .scaleTitleOffsets(0.8, axes='Y') # canvas.rat.setTitles(X='', copy=canvas.firstPlot.plot) # setBinLabels(canvas, '') #canvas.cleanup('pdfs/NM1_{}_MC.pdf'.format(hkey)) #canvas.finishCanvas(extrascale=1. if not DODATA else 1.+1./3.) #canvas.save('pdfs/NM1_{}{}_MC.pdf'.format(hkey, BUMPSTRING)) #canvas.deleteCanvas() canvas.cleanup('pdfs/NM1_{}{}{}_MC.pdf'.format(hkey, BUMPSTRING, IDPHISTRING))
def makeIntegratedNM1MC(hkey='NM1'): ### modified version of getBackgroundHistograms FILE = FILES['MC'] keylist = [hkey] stack = True addFlows = False rebin = None rebinVeto = None HISTS = {} PConfig = {} for key in keylist: HISTS[key] = {} PConfig[key] = {'stack': ('', '', 'hist')} if stack: HISTS[key]['stack'] = R.THStack('hStack', '') for ref in HG.BGORDER: HISTS[key][ref] = HG.getHistogram(FILE, ref, key).Clone() #if addFlows: # RT.addFlows(HISTS[key][ref]) HISTS[key][ref].Scale(HG.PLOTCONFIG[ref]['WEIGHT']) if DODATA: HISTS[key][ref].Scale(DATASCALE) #if rebin is not None and (rebinVeto is None or (rebinVeto is not None and not rebinVeto(key))): # is2D = 'TH2' in str(HISTS[key][ref].__class__) # if is2D: # if not hasattr(rebin, '__iter__'): # print '[HISTOGRAMGETTER ERROR]: For 2D plots, "rebin" must be a list of 2 rebin values' # exit() # HISTS[key][ref].Rebin2D(*rebin) # else: # HISTS[key][ref].Rebin(rebin) PConfig[key][ref] = (HG.PLOTCONFIG[ref]['LATEX'], 'f', 'hist') #if not stack and ref == BGORDER[0]: # HISTS[key]['stack'] = HISTS[key][ref].Clone() # continue ### modification totalBin1 = sum( [HISTS[key][ref].GetBinContent(1) for ref in HG.BGORDER]) for ibin in range(1, len(CUTS) + 2): totalBin = sum( [HISTS[key][ref].GetBinContent(ibin) for ref in HG.BGORDER]) scaleFactor = totalBin1 / totalBin for ref in HG.BGORDER: HISTS[key][ref].SetBinContent( ibin, HISTS[key][ref].GetBinContent(ibin) / totalBin * scaleFactor) ### end modification # NOW add to the stack for ref in HG.BGORDER: HISTS[key]['stack'].Add(HISTS[key][ref]) ### end modified version of getBackgroundHistograms HISTS = HISTS[hkey] PConfig = PConfig[hkey] if DODATA: DATAHISTS, DataPConfig = HG.getDataHistograms(FILES['Data'], hkey) DATAHISTS = DATAHISTS[hkey] PConfig['data'] = DataPConfig[hkey]['data'] #PConfig['data'] = ('DoubleMuon2016', 'pe', 'pe') totalBin1 = DATAHISTS['data'].GetBinContent(1) for ibin in range(1, len(CUTS) + 2): totalBin = DATAHISTS['data'].GetBinContent(ibin) scaleFactor = totalBin1 / totalBin DATAHISTS['data'].SetBinContent( ibin, DATAHISTS['data'].GetBinContent(ibin) / totalBin * scaleFactor) for ibin in range(1, len(CUTS) + 2): DATAHISTS['data'].SetBinError(ibin, 1.e-7) PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) if DODATA: PLOTS['data'] = Plotter.Plot(DATAHISTS['data'], *PConfig['data']) canvas = Plotter.Canvas( lumi='MC' if not DODATA else 'MC + Data', logy=True, cWidth=1600, ) # ratioFactor=0. if not DODATA else 1./3., fontscale=1. if not DODATA else 1.+1./3.) for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) if DODATA: canvas.addMainPlot(PLOTS['data']) setBinLabels(canvas) canvas.makeLegend(lWidth=.27, pos='bl', autoOrder=False, fontscale=0.8) # if not DODATA else 1.) if DODATA: canvas.addLegendEntry(PLOTS['data']) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() canvas.firstPlot.setTitles(X='Cut', Y='n#minus1 Eff.') canvas.firstPlot.SetMaximum(1.e0) canvas.firstPlot.SetMinimum(1.e-3 if 'DSA' not in hkey else 1.e-6) # if DODATA: # canvas.makeRatioPlot(PLOTS['data'].plot, PLOTS['stack'].plot.GetStack().Last()) # canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y') # canvas.rat .scaleTitleOffsets(0.8, axes='Y') # canvas.rat.setTitles(X='', copy=canvas.firstPlot.plot) # setBinLabels(canvas, '') # for ibin in range(1, len(CUTS)+2): # canvas.rat.SetBinError(ibin, 1.e-7) canvas.scaleMargins(.5, 'L') canvas.firstPlot.scaleTitleOffsets(.5, 'Y') #canvas.cleanup('pdfs/NM1_{}_MC.pdf'.format(hkey)) #canvas.finishCanvas(extrascale=1. if not DODATA else 1.+1./3.) #canvas.save('pdfs/NM1_{}{}_MC.pdf'.format(hkey, BUMPSTRING)) #canvas.deleteCanvas() canvas.cleanup('pdfs/NM1_{}{}{}_MC.pdf'.format(hkey, BUMPSTRING, IDPHISTRING))
def makeMCPlots(): quantities = { 'DSA': [], 'PAT': [], 'HYB': [], 'HYB-DSA': [], 'HYB-PAT': [] } dimQuantities = [ 'Lxy', 'LxySig', 'LxyErr', 'vtxChi2', 'mind0Sig', 'mass', 'deltaPhi', 'deltaR', 'cosAlpha', 'cosAlpha-O', 'DCA', 'pTOverM', 'minNHits', 'qsum' ] for recoType in quantities: if 'HYB-' in recoType: continue quantities[recoType].extend(dimQuantities) quantities['HYB-DSA'].extend( ['pT', 'eta', 'phi', 'd0', 'FPTE', 'd0Sig', 'trkChi2', 'nStations']) quantities['HYB-PAT'].extend( ['pT', 'eta', 'phi', 'd0', 'relTrkIso', 'd0Sig', 'trkChi2']) for recoType in ('DSA', 'PAT'): quantities[recoType].extend(quantities['HYB-' + recoType]) quantities['REF-DSA'] = ['FPTE'] quantities[''] = ['nDimuon', 'nDSA', 'nDSA12', 'nDSA12-pT', 'nDSA-DT'] # consider making deltaPhi not log scale. If so, then uncomment the maximum commands at the bottom def rebinVeto(key): if 'Lxy' in key and 'Sig' not in key and 'Err' not in key and 'DSA' not in key: return True if 'deltaPhi' in key or 'phi' in key: return True if 'mass' in key and MASSZOOMED: return True if 'nStations' in key: return True if 'cosAlpha' in key: return True if 'LxySig' in key and 'DSA' in key: return True if 'mind0Sig' in key and 'DSA' in key: return True if 'd0' in key and 'Sig' not in key and 'DSA' in key: return True if 'trkChi2' in key: return True if 'nDimuon' in key: return True if 'nDSA' in key: return True if 'REF-DSA-FPTE' in key: return True if 'minNHits' in key: return True if 'qsum' in key: return True return False for recoType in quantities: for quantity in quantities[recoType]: hkey = recoType + '-' + quantity if hkey[0] == '-' or recoType == 'DSAPlus': hkey = quantity recoType = 'DSAPlus' DODATA = recoType == 'DSA' or recoType == 'REF-DSA' or ( recoType == 'DSAPlus' and 'nDSA' in quantity) if DODATA: HISTS, PConfig = HG.getBackgroundHistograms( FILES['MC'], hkey, addFlows=True, rebin=10, rebinVeto=rebinVeto, extraScale=DATASCALE) DATAHISTS, DataPConfig = HG.getDataHistograms( FILES['Data'], hkey, addFlows=True, rebin=10, rebinVeto=rebinVeto) else: HISTS, PConfig = HG.getBackgroundHistograms( FILES['MC'], hkey, addFlows=True, rebin=10, rebinVeto=rebinVeto) HISTS = HISTS[hkey] PConfig = PConfig[hkey] if DODATA: DATAHISTS = DATAHISTS[hkey] PConfig['data'] = DataPConfig[hkey]['data'] PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) if DODATA: PLOTS['data'] = Plotter.Plot(DATAHISTS['data'], *PConfig['data']) canvas = Plotter.Canvas( lumi=('MC' if not DODATA else 'MC + Data') + lumiExtra.get(CUTSTRING) + ' ({})'.format(recoType), logy=True, ratioFactor=0. if not DODATA else 1. / 3., fontscale=1. if not DODATA else 1. + 1. / 3.) if hkey == 'REF-DSA-FPTE': canvas.mainPad.SetLogx() for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) if DODATA: canvas.addMainPlot(PLOTS['data']) # this has to be here because it has to be drawn first if 'vtxChi2' in hkey: canvas.firstPlot.GetXaxis().SetRangeUser(0., 50.) if 'mass' in hkey: if MASSZOOMED: canvas.firstPlot.GetXaxis().SetRangeUser(0., 100.) if 'mind0Sig' in hkey and 'DSA' in hkey: pass #canvas.firstPlot.GetXaxis().SetRangeUser(0., 5.) canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]]) canvas.firstPlot.setTitles(Y='Normalized Counts') canvas.makeLegend(lWidth=.27, pos='tr' if hkey != 'REF-DSA-FPTE' else 'tl', autoOrder=False, fontscale=0.8 if not DODATA else 1.) if DODATA: canvas.addLegendEntry(PLOTS['data']) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) HISTS['sum'] = HISTS['stack'].GetStack().Last() nBins = HISTS['sum'].GetNbinsX() val = None if 'LxySig' in hkey: val = 100. if 'vtxChi2' in hkey: val = 50. if 'LxyErr' in hkey: val = 10. if 'mind0Sig' in hkey: val = 3. if 'Lxy' == quantity: val = 100. if val is not None: print '{} Mean : {}'.format(hkey, HISTS['sum'].GetMean()) print '{} Overflow % : {}'.format( hkey, HISTS['sum'].GetBinContent(nBins) / HISTS['sum'].Integral(1, nBins) * 100.) print '{} > {:<8.0f} % : {}'.format( hkey, val, HISTS['sum'].Integral(HISTS['sum'].FindBin(val), nBins) / HISTS['sum'].Integral(1, nBins) * 100.) if hkey == 'PAT-LxySig': h = HG.getHistogram(FILES['MC'], 'DY50toInf', hkey).Clone() print '{} DY50toInf : {}'.format( hkey, h.Integral(h.FindBin(100.), h.GetNbinsX())) if DODATA: canvas.makeRatioPlot(PLOTS['data'].plot, PLOTS['stack'].plot.GetStack().Last()) canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y') canvas.rat.scaleTitleOffsets(0.8, axes='Y') if 'mass' in hkey: if MASSZOOMED: canvas.rat.GetXaxis().SetRangeUser(0., 100.) if 'REF-DSA-FPTE' in hkey: canvas.ratPad.SetLogx() doNotMaximize = True canvas.firstPlot.SetMaximum({ 'DSA': 1000., 'PAT': 10.**7., 'HYB': 2. * 10.**5., 'HYB-DSA': 2. * 10.**5., 'HYB-PAT': 2. * 10.**5., 'REF-DSA': 1000., 'DSAPlus': 1000. }[recoType]) if recoType == 'DSA' and quantity in [ 'pT', 'eta', 'phi', 'FPTE', 'd0Sig', 'trkChi2', 'nStations' ]: canvas.firstPlot.SetMaximum(10.**5.) #if recoType == 'PAT' and 'deltaPhi' in quantity: # canvas.firstPlot.SetMaximum(11.**5.) if not doNotMaximize: canvas.firstPlot.SetMaximum(HISTS['sum'].GetMaximum() * 1.05) canvas.firstPlot.SetMinimum(1.) #canvas.cleanup('pdfs/ZEP_{}_{}_{}_MC.pdf'.format(quantity, recoType, CUTSTRING)) canvas.finishCanvas(extrascale=1. if not DODATA else 1. + 1. / 3.) canvas.save('pdfs/ZEP_{}_{}_{}_MC.pdf'.format( quantity + ('Zoomed' if 'mass' in quantity and MASSZOOMED else ''), recoType, CUTSTRING)) canvas.deleteCanvas()
def makeMCPlot(hkey, DODATA=False, TENP=False): if DODATA: if not TENP: HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC_I'], hkey) DATAHISTS, DataPConfig = HG.getDataHistograms( FILES['Data_I'], hkey) lumi = 'MC + Data, |#Delta#Phi| > #pi/2' else: HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey, extraScale=DATASCALE) DATAHISTS, DataPConfig = HG.getDataHistograms(FILES['Data'], hkey) lumi = 'MC + 10% Data' else: HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey) lumi = 'MC' HISTS = HISTS[hkey] PConfig = PConfig[hkey] if DODATA: DATAHISTS = DATAHISTS[hkey] PConfig['data'] = DataPConfig[hkey]['data'] PLOTS = {} for key in HG.BGORDER + ('stack', ): PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key]) if DODATA: PLOTS['data'] = Plotter.Plot(DATAHISTS['data'], *PConfig['data']) canvas = Plotter.Canvas( lumi=lumi, logy=True if hkey != 'nDTHits' else False #ratioFactor=0. if not DODATA else 1./3., fontscale=1. if not DODATA else 1.+1./3.) ) for key in HG.BGORDER: PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF') canvas.addMainPlot(PLOTS['stack']) if DODATA: canvas.addMainPlot(PLOTS['data']) canvas.firstPlot.setTitles(X='', copy=HISTS[HG.BGORDER[0]]) canvas.firstPlot.setTitles(Y='Normalized Counts') canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8) # if not DODATA else 1.) if DODATA: canvas.addLegendEntry(PLOTS['data']) for ref in reversed(HG.BGORDER): canvas.addLegendEntry(PLOTS[ref]) canvas.legend.resizeHeight() RT.addBinWidth(canvas.firstPlot) if canvas.logy: canvas.firstPlot.SetMinimum(1.) canvas.firstPlot.SetMaximum(500.) else: canvas.firstPlot.SetMinimum(0.) canvas.firstPlot.SetMaximum(10.) #if DODATA: # canvas.makeRatioPlot(PLOTS['data'].plot, PLOTS['stack'].plot.GetStack().Last()) # canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y') # canvas.rat .scaleTitleOffsets(0.8, axes='Y') # canvas.rat.setTitles(X='', copy=canvas.firstPlot.plot) if canvas.logy: line = R.TLine(CONFIG[hkey]['val'], 0.45, CONFIG[hkey]['val'], 10.**(R.TMath.Log10(500.) * 1.06)) else: line = R.TLine(CONFIG[hkey]['val'], 0., CONFIG[hkey]['val'], 10. * 1.05) line.Draw() line.SetLineStyle(2) if DODATA: if not TENP: DATAHISTS_NO, DataPConfig_NO = HG.getDataHistograms( FILES['Data_I'], hkey, addFlows=False) else: DATAHISTS_NO, DataPConfig_NO = HG.getDataHistograms(FILES['Data'], hkey, addFlows=False) print '\033[32m{:6s} {:8s} {:5.0f} {:5.0f} {:7.2%}\033[m'.format( 'Data' + ('' if not TENP else '10'), hkey, *fractionCut(hkey, DATAHISTS_NO[hkey]['data'])) canvas.cleanup('pdfs/NM1D_{}_MC{}{}.pdf'.format( hkey, '' if not DODATA else 'Data', '' if not TENP else '-10'))