def draw(self): ## Make auxiliary lists of indices and hitogram names indices = range(len(self.trees)) hnames = ['h_%s_%d' % (self.name, i) for i in indices] ## Make the histograms for t, hname in zip(self.trees, hnames): expr = '%s>>%s' % (self.expression, hname) sel = '&'.join(['(%s)' % c for c in self.cuts if c.strip()]) if self.binning: expr += '(%s)' % self.binning t.Draw(expr, sel, 'goff') else: ## No binning is specified. ## Take extra care to use the same binning for all. ## Use automatic binning fro the first tree and apply it ## to all others. if id(t) == id(self.trees[0]): ## This is the first tree, use auto-binning. t.Draw(expr, sel) else: ## This is no the first tree, use same binning as ## for the first one t.Draw(expr, sel, 'same') ## Retrieve the histograms in put them in a list self.histos = [ROOT.gDirectory.Get(hn) for hn in hnames] ## Customize histos for h, c, ms in zip(self.histos, self.colors, self.markerstyles): h.Sumw2() if self.normalize_to_unit_area: nbins = h.GetXaxis().GetNbins() area = h.GetBinWidth(1) * h.Integral(1, nbins) h.Scale(1./area) h.GetXaxis().SetTitle(self.xtitle) h.GetYaxis().SetTitle(self.ytitle) h.SetTitle(self.title) h.SetStats(0) h.SetLineColor(c) h.SetMarkerColor(c) h.SetMarkerStyle(ms) ## Find the histogram with greatest y range maxima = [h.GetMaximum() for h in self.histos] highest = max(maxima) imax = maxima.index(highest) ## Draw the "highest" histo first to guarantee nice the y-range. self.histos[imax].Draw(self.drawopts[imax]) ## Draw all histograms for h, opt in zip(self.histos, self.drawopts): h.Draw(opt + 'same') ## Add the legend legend = Legend(self.histos, self.ltitles, **self.legendkwargs) legend.draw() ## Add latex labels latex = Latex(self.labels, self.labels_layout) latex.draw()
def draw(self): ## Make auxiliary lists of indices and hitogram names indices = range(len(self.trees)) hnames = ['h_%s_%d' % (self.name, i) for i in indices] ## Make the histograms for t, hname in zip(self.trees, hnames): expr = '%s>>%s' % (self.expression, hname) sel = '&'.join(['(%s)' % c for c in self.cuts if c.strip()]) if self.binning: expr += '(%s)' % self.binning t.Draw(expr, sel, 'goff') else: ## No binning is specified. ## Take extra care to use the same binning for all. ## Use automatic binning fro the first tree and apply it ## to all others. if id(t) == id(self.trees[0]): ## This is the first tree, use auto-binning. t.Draw(expr, sel) else: ## This is no the first tree, use same binning as ## for the first one t.Draw(expr, sel, 'same') ## Retrieve the histograms in put them in a list self.histos = [ROOT.gDirectory.Get(hn) for hn in hnames] ## Customize histos for h, c, ms in zip(self.histos, self.colors, self.markerstyles): h.Sumw2() if self.normalize_to_unit_area: nbins = h.GetXaxis().GetNbins() area = h.GetBinWidth(1) * h.Integral(1, nbins) h.Scale(1. / area) h.GetXaxis().SetTitle(self.xtitle) h.GetYaxis().SetTitle(self.ytitle) h.SetTitle(self.title) h.SetStats(0) h.SetLineColor(c) h.SetMarkerColor(c) h.SetMarkerStyle(ms) ## Find the histogram with greatest y range maxima = [h.GetMaximum() for h in self.histos] highest = max(maxima) imax = maxima.index(highest) ## Draw the "highest" histo first to guarantee nice the y-range. self.histos[imax].Draw(self.drawopts[imax]) ## Draw all histograms for h, opt in zip(self.histos, self.drawopts): h.Draw(opt + 'same') ## Add the legend legend = Legend(self.histos, self.ltitles, **self.legendkwargs) legend.draw() ## Add latex labels latex = Latex(self.labels, self.labels_layout) latex.draw()
def decorate_canvas(self, canvas): ''' Decorate the new canvas with the results of the fit and other labels. ''' gpad_save = ROOT.gPad canvas.cd() phoScale = self.workspace.var('phoScale') phoRes = self.workspace.var('phoRes') ## Draw fit results: Latex([ 'Fit Parameters:', '#mu(E_{#gamma}) = %.2f #pm %.2f %%' % ( phoScale.getVal(), phoScale.getError() ), '#sigma(E_{#gamma}) = %.2f #pm %.2f %%' % ( phoRes.getVal(), phoRes.getError() ), ], position=(0.65, 0.8), textsize=22, rowheight=0.07 ).draw() ## CMS Preliminary: Latex(['CMS Preliminary 2011, #sqrt{s} = 7 TeV'], position=(0.17, 0.93), textsize=22).draw() labels = [] ## Data or MC if 'data' in self.name: labels.append('Data, L = 4.89 fb^{-1}') else: labels.append('Simulation') ## EB or EE if 'EB' in self.name: labels.append('ECAL Barrel') else: labels.append('ECAL Endcaps') if 'highR9' in self.name: labels.append('R_{9} > 0.94') Latex(labels, position=(0.22, 0.8), textsize=22, rowheight=0.07 ).draw() canvas.Modified() canvas.Update() gpad_save.cd()
def plot_training_phoeres_with_shape_and_fit(): """Plot the nominal MC photon energy smearing overlayed with the pdf shape and fit.""" canvases.next('TrainingPhoEResWithShapeAndFit') plot = phoERes.frame(roo.Range(-7.5, 5)) plot.SetTitle("Photon energy smearing overlayed with PDF shape (blue) " "and it's parametrized fit (dashed red)") data.plotOn(plot) ## Define model for the photon energy smearing function Ereco/Etrue - 1. phoEResPdf = ParametrizedKeysPdf('phoEResPdf', 'phoEResPdf', phoERes, phoScale, phoRes, data, ROOT.RooKeysPdf.NoMirror, 1.5) ## PDF shape phoEResPdf.shape.plotOn(plot) ## Parametrized fit of the PDF shape phoEResPdf.fitTo(data, roo.Range(-50, 50), roo.PrintLevel(-1)) phoEResPdf.plotOn(plot, roo.LineColor(ROOT.kRed), roo.LineStyle(ROOT.kDashed)) plot.Draw() Latex([ 's_{shape}: %.3f %%' % phoEResPdf.shapemode, 's_{fit}: %.3f #pm %.3f %%' % (phoScale.getVal(), phoScale.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f %%' % (phoScale.getVal() - phoEResPdf.shapemode, phoScale.getError()), 'r_{shape}: %.3f %%' % phoEResPdf.shapewidth, 'r_{fit}: %.3f #pm %.3f %%' % (phoRes.getVal(), phoRes.getError()), 'r_{fit} - r_{shape}: %.4f #pm %.4f %%' % (phoRes.getVal() - phoEResPdf.shapewidth, phoRes.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % (phoRes.getVal() / phoEResPdf.shapewidth, phoRes.getError() / phoEResPdf.shapewidth), ], position=(0.2, 0.8)).draw()
def draw_latex_for_fit_to_real_data(): ''' Draw latex results to the plot of the fit to real data. ''' global fsr_purity Latex([ 'E^{#gamma} Scale (%)', ' MC Truth: %.2f #pm %.2f' % (fit_calibrator.s.getVal(), fit_calibrator.s.getError()), ' Data Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f}' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} Resolution (%)', ' MC Truth: %.2f #pm %.2f' % (fit_calibrator.r.getVal(), fit_calibrator.r.getError()), ' Data Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f}' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), '', 'Signal Purity (%)', ' MC Truth: %.2f' % fsr_purity, ' Data Fit: %.2f #pm %.2f' % ( 100 * w.var('signal_f').getVal(), 100 * w.var('signal_f').getError() ) ], position=(0.2, 0.8) ).draw() print 'E^{#gamma} Scale (%)',' MC Truth: %.2f #pm %.2f' % (fit_calibrator.s.getVal(),fit_calibrator.s.getError()),' Data Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f}' % (phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(),phoScale.getErrorLo())
def plot_nominal_mmgmass_with_shape_and_fit(): """Plot the nominal MC mmg mass data overlayed with the pdf shape and fit.""" canvases.next('NominalMmgMassWithShapeAndFit') plot = mmgMass.frame(roo.Range(75, 105)) plot.SetTitle("m(#mu#mu#gamma) overlayed with PDF shape (blue) " "and it's parametrized fit (dashed red)") data.plotOn(plot) ## Define the mmg mass model. mmgMassPdf = ParametrizedKeysPdf('mmgMassPdf', 'mmgMassPdf', mmgMass, massPeak, massWidth, data, ROOT.RooKeysPdf.NoMirror, 1.5) ## PDF shape mmgMassPdf.shape.plotOn(plot) ## Parametrized fit of the PDF shape mmgMassPdf.fitTo(data, roo.Range(60, 120), roo.PrintLevel(-1)) mmgMassPdf.plotOn(plot, roo.LineColor(ROOT.kRed), roo.LineStyle(ROOT.kDashed)) plot.Draw() sshape = 100 * (mmgMassPdf.shapemode / mZ.getVal() - 1) rshape = 100 * mmgMassPdf.shapewidth / mmgMassPdf.shapemode Latex([ 's_{shape}: %.3f %%' % sshape, 's_{fit}: %.3f #pm %.3f %%' % (massScale.getVal(), massScale.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f %%' % (massScale.getVal() - sshape, massScale.getError()), 'r_{shape}: %.3f %%' % rshape, 'r_{fit}: %.3f #pm %.3f %%' % (massRes.getVal(), massRes.getError()), 'r_{fit} - r_{shape}: %.4f #pm %.4f %%' % (massRes.getVal() - rshape, massRes.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % (massRes.getVal() / rshape, massRes.getError() / rshape), ], position=(0.2, 0.8)).draw()
def decorate_plot(self): ## Draw the functional form Latex(['#frac{#sigma_{eff}}{E} = #frac{S}{#sqrt{E_{T}}} #oplus ' '#frac{N}{E_{T}} #oplus C'], position = (0.18, 0.8), textsize = 22).draw() ## Draw the fit result chi2 = self.fresult.minNll() npars = self.fresult.floatParsFinal().getSize() ndof = self.dxy.numEntries() - npars prob = ROOT.TMath.Prob(chi2, ndof) Latex([self.root_latex_for_realvar(self.S, 1), self.root_latex_for_realvar(self.N, 1), self.root_latex_for_realvar(self.C, 1), '#chi^{2} / N_{dof}: %.2g / %d' % (chi2, ndof), '#chi^{2} Prob.: %.3g %%' % (100 * prob)], position = (0.53, 0.8), textsize = 22).draw()
def plot_mmgmass_for_multiple_smearings(name, stargets, rtargets, colors, plotrange=(76, 106)): canvases.next(name).SetGrid() plot = mmgMass.frame(roo.Range(*plotrange)) plot.SetTitle("MC for multiple smearing scenarious") multilabels = [] ## Loop over the various smearings. for starget, rtarget, color in zip(stargets, rtargets, colors): mydata = calibrator.get_smeared_data(starget, rtarget) mydata.plotOn(plot, roo.LineColor(color), roo.MarkerColor(color)) multilabels.append(['s_{target}: %.1f %%' % starget, 'r_{target}: %.1f %%'% rtarget,]) ## End of loop over the various smearings. plot.Draw() for i, (labels, color) in enumerate(zip(multilabels, colors)): latex = Latex(labels, position=(0.2, 0.85 - i*0.11)) latex.SetTextColor(color) latex.draw()
def plot_nominal_and_smeared_mmgmass(): canvases.next('SmearedMMGMass').SetGrid() plot = mmgMass.frame(roo.Range(76, 106)) plot.SetTitle("Nominal (black) and smeared (red) mmg mass") data.plotOn(plot) datasmeared.plotOn(plot, roo.MarkerColor(ROOT.kRed), roo.LineColor(ROOT.kRed)) plot.Draw() Latex([ 's_{0}: %.2g %%, s: %.2g %%' % (phoScaleRef, targets), 'r_{0}: %.2g %%, r: %.2g %%' % (phoResRef, targetr) ], position=(0.2, 0.8)).draw()
def plot_smeared_phoeres_with_fit(): phoEResPdf.fitTo(datasmeared, roo.PrintLevel(-1), roo.SumW2Error(False)) canvases.next('SmearedSampleWithFit') plot = phoERes.frame(roo.Range(-30, 30)) plot.SetTitle("Smeared MC with paremetrized fit") datasmeared.plotOn(plot) phoEResPdf.plotOn(plot) phoEResPdf.paramOn(plot) plot.Draw() Latex([ 'target s: %.3g %%' % targets, 'target r: %.3g %%' % targetr, ], position=(0.2, 0.75)).draw()
def plot_mmgmass_with_fit_for_multiple_smearings(name, stargets, rtargets, colors, plotrange=(60, 105)): """Plot the smeared mmg mass for a number of different smearings.""" canvases.next(name).SetGrid() mmgMass.setRange('plot', *plotrange) plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle("") slabels = [] rlabels = [] ## Loop over the various smearings. for starget, rtarget, color in zip(stargets, rtargets, colors): mydata = calibrator.get_smeared_data(starget, rtarget) model = ParametrizedKeysPdf('model', 'model', mmgMass, mmgMassSmearPeak, mmgMassSmearWidth, mydata, ROOT.RooKeysPdf.NoMirror, 1.5) model.fitTo(mydata, roo.PrintLevel(-1), roo.Range(60, 120), roo.SumW2Error(False)) mydata.plotOn(plot, roo.LineColor(color), roo.MarkerColor(color)) model.plotOn(plot, roo.LineColor(color), roo.Range('plot'), roo.NormRange('plot')) slabels.append([ 's\' = % 3.f %%, ' % starget + '#Delta m_{#mu#mu#gamma} = %.2f #pm %.2f %%' % ( 100 * (mmgMassSmearPeak.getVal() / 91.2 - 1.), 100 * mmgMassSmearPeak.getError() / 91.2 ), ]) rlabels.append([ 'r\' = %.1f %%, ' % rtarget + '#sigma_{eff}/#mu(m_{\mu\mu\gamma}) = % .2f #pm %.2f %%' % ( 100 * mmgMassSmearWidth.getVal() / mmgMassSmearPeak.getVal(), 100 * mmgMassSmearWidth.getError() / mmgMassSmearPeak.getVal(), ), ]) ## End of loop over the various smearings. plot.Draw() for i, (labels, color) in enumerate(zip(slabels, colors)): latex = Latex(labels, position=(0.18, 0.85 - i*0.055)) latex.SetTextColor(color) latex.draw() for i, (labels, color) in enumerate(zip(rlabels, colors)): latex = Latex(labels, position=(0.18, 0.85 - (len(slabels)+1) * 0.055 - i*0.055)) latex.SetTextColor(color) latex.draw()
def plot_training_phoeres_with_shape_and_fit(): canvases.next('TrainingSampleWithShapeAndFit') plot = phoERes.frame(roo.Range(-7.5, 7.5)) plot.SetTitle( "MC overlayed with PDF shape (blue) and it's parametrized fit" "(dashed red)") data.plotOn(plot) phoEResPdf.shape.plotOn(plot) phoEResPdf.plotOn(plot, roo.LineColor(ROOT.kRed), roo.LineStyle(ROOT.kDashed)) plot.Draw() Latex([ 's_{shape}: %.3f %%' % phoEResPdf.shapemode, 's_{fit}: %.3f #pm %.3f %%' % (phoScale.getVal(), phoScale.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f' % (phoScale.getVal() - phoEResPdf.shapemode, phoScale.getError()), 'r_{shape}: %.3f %%' % phoEResPdf.shapewidth, 'r_{fit}: %.3f #pm %.3f %%' % (phoRes.getVal(), phoRes.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % (phoRes.getVal() / phoEResPdf.shapewidth, phoRes.getError() / phoEResPdf.shapewidth), ], position=(0.2, 0.75)).draw()
def plot_phoeres_with_fit_for_multiple_smearings(name, stargets, rtargets, colors, plotrange=(-30, 30)): """Plot the smeared photon energy response for a number of different smearings.""" canvases.next(name).SetGrid() phoERes.setRange('plot', *plotrange) plot = phoERes.frame(roo.Range('plot')) #plot.SetTitle("MC with paremetrized fit for multiple smearing scenarious") plot.SetTitle("") slabels = [] rlabels = [] ## Loop over the various smearings. for starget, rtarget, color in zip(stargets, rtargets, colors): mydata = calibrator.get_smeared_data(starget, rtarget) phoEResPdf.fitTo(mydata, roo.PrintLevel(-1), roo.SumW2Error(False)) mydata.plotOn(plot, roo.LineColor(color), roo.MarkerColor(color)) phoEResPdf.plotOn(plot, roo.LineColor(color), roo.Range('plot'), roo.NormRange('plot')) slabels.append([ 's\' = % 3.f %%, #Delta s_{fit} = % .2f #pm %.2f %%' % ( starget, phoScale.getVal() - starget, phoScale.getError() ), ]) rlabels.append([ 'r\' = %3.1f %%, #Delta r_{fit} = % .2f #pm %.2f %%' % ( rtarget, phoRes.getVal() - rtarget, phoRes.getError() ), ]) ## End of loop over the various smearings. plot.Draw() for i, (labels, color) in enumerate(zip(slabels, colors)): latex = Latex(labels, position=(0.18, 0.85 - i*0.055)) latex.SetTextColor(color) latex.draw() for i, (labels, color) in enumerate(zip(rlabels, colors)): latex = Latex(labels, position=(0.18, 0.85 - (len(slabels) + 1) * 0.055 - i * 0.055)) latex.SetTextColor(color) latex.draw()
## Plot fT1(t1) with training data. canvases.next('t1pdf').SetGrid() t.setRange(5, 10) t.SetTitle('log(m_{#mu#mu#gamma,E_{gen}^{#gamma}}^{2} - m_{#mu#mu}^{2})') plot = t.frame(roo.Range(6, 9)) t1data.plotOn(plot) t1pdf.shape.plotOn(plot) t1pdf.plotOn(plot, roo.LineColor(ROOT.kRed), roo.LineStyle(ROOT.kDashed)) plot.Draw() Latex([ 's_{shape}: %.3f' % t1pdf.shapemode, 's_{fit}: %.3f #pm %.3f' % (t1mode.getVal(), t1mode.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f' % (t1mode.getVal() - t1pdf.shapemode, t1mode.getError()), 'r_{shape}: %.3f' % t1pdf.shapewidth, 'r_{fit}: %.3f #pm %.3f' % (t1width.getVal(), t1width.getError()), 'r_{fit} - r_{shape}: %.4f #pm %.4f' % (t1width.getVal() - t1pdf.shapewidth, t1width.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % (t1width.getVal() / t1pdf.shapewidth, t1width.getError() / t1pdf.shapewidth), ], position=(0.2, 0.8)).draw() ## Plot fT2(t2|s,r) fitted to training data. canvases.next('t2pdf').SetGrid() t.setRange(-1, 1) t.setVal(0) t.SetTitle('log(E_{reco}^{#gamma}/E_{gen}^{#gamma})') phoScale.setVal(t2pdf.s0val) phoRes.setVal(t2pdf.r0val) t2pdf.fitTo(t2data, roo.Range(ROOT.TMath.Log(0.5), ROOT.TMath.Log(1.5)))
data, rho=1.5) ## Fit nominal data with ft2(t2|r,s) canvases.next('t2pdf').SetGrid() t2pdf.fitTo(data, roo.Range(ROOT.TMath.Log(0.5), ROOT.TMath.Log(2.0))) plot = t.frame(roo.Range(-0.15, 0.15)) data.plotOn(plot) t2pdf.plotOn(plot) plot.Draw() Latex([ 's_{shape}: %.3f %%' % t2pdf.s0val, 's_{sfit}: %.3f #pm %.3f %%' % (phoScale.getVal(), phoScale.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f %%' % (phoScale.getVal() - t2pdf.s0val, phoScale.getError()), 'r_{shape}: %.3f %%' % t2pdf.r0val, 'r_{fit}: %.3f #pm %.3f %%' % (phoRes.getVal(), phoRes.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % (phoRes.getVal() / t2pdf.r0val, phoRes.getError() / t2pdf.r0val), ], position=(0.2, 0.75)).draw() ## Fit scale s=-5 smeared data with ft2(t2|r,s) canvases.next('t2pdf_sm5').SetGrid() sdata = calibrator.get_smeared_data(-5, 'nominal') sdata.addColumn(tfunc) sdata.SetName('sdata_sm5') plot = t.frame(roo.Range(-0.15, 0.15)) sdata.plotOn(plot) t2pdf.fitTo(sdata, roo.Range(-0.7, 0.4)) t2pdf.plotOn(plot)
labels.append('Endcaps') labels = ['E_{T}^{#gamma} #in [%g,%g] GeV' % phoPtRange] for c in cuts: if 'phoR9' in c: labels.append(c.replace('phoR9', 'R_{9}')) break labels.append('Moduel 1') labels.append('True Resolution (#sigma_{eff}): %.3g %%' % phoEResMC) labels.append('True Scale: %.3g %%' % (100*phoEScaleMC)) labels.append('<EdM/dE>: %.3g GeV' % phoF.getVal()) llabels = Latex(labels, (0.21, 0.83)) ## Make plots plots = [] phoRes = w.var('phoRes') phoRes.SetTitle('#sigma_{eff}(E_{#gamma})') phoScale.SetTitle('E_{#gamma} Scale') ## for x in [phoRes, phoScale]: ## x.SetTitle(x.GetName()) ## Theory for unsmeared photon canvases.next('theory')#.SetLogy() mmgMassShiftedTitle = mmgMassShifted.GetTitle().replace('mmgMass', 'm(#mu#mu#gamma)') mmgMassShifted.setUnit('GeV') mmgMassShifted.SetTitle(mmgMassShiftedTitle.replace('m(#mu#mu#gamma)', 'm(#mu#mu + gen #gamma)'))
def decorate_canvas(self, canvas): ''' Decorate the new canvas with the results of the fit and other labels. ''' gpad_save = ROOT.gPad canvas.cd() phoScale = self.workspace.var('phoScale') phoRes = self.workspace.var('phoRes') ## Draw fit results: Latex([ 'Fit Parameters:', '#mu(E_{#gamma}) = %.2f #pm %.2f %%' % ( phoScale.getVal(), phoScale.getError() ), '#sigma(E_{#gamma}) = %.2f #pm %.2f %%' % ( phoRes.getVal(), phoRes.getError() ), ], position=(0.65, 0.8), textsize=22, rowheight=0.07, textfont=42 ).draw() ## CMS Preliminary: Latex(['CMS 2011, #sqrt{s} = 7 TeV'], position=(0.17, 0.93), textsize=22, textfont=42).draw() labels = [] tokens = self.name.split('_') ## Data or MC if 'data' in tokens: labels.append('Data, L = 4.89 fb^{-1}') else: labels.append('Simulation') ## EB or EE if 'EB' in tokens: labels.append('ECAL Barrel') else: labels.append('ECAL Endcaps') if 'highR9' in tokens: labels.append('R_{9} > 0.94') ## Find the name token with the pt information pt_token = '' for token in tokens: print token if ('pt' in token) and ('to' in token): pt_token = token print 'Pt range:', pt_token if pt_token: ## We found it. Parse it to get the pt range lo, hi = pt_token.replace('pt', '').split('to') labels.append('Photon E_{T} #in [%s, %s) GeV' % (lo, hi)) Latex(labels, position=(0.22, 0.8), textsize=22, rowheight=0.07, textfont = 42 ).draw() canvas.Modified() canvas.Update() gpad_save.cd()
def decorate_canvas(self, canvas): ''' Decorate the new canvas with the results of the fit and other labels. ''' gpad_save = ROOT.gPad canvas.cd() phoScale = self.workspace.var('phoScale') phoRes = self.workspace.var('phoRes') ## Draw fit results: Latex( [ #'Fit Parameters:', 's = %.2f #pm %.2f %%' % (phoScale.getVal(), phoScale.getError()), 'r = %.2f #pm %.2f %%' % (phoRes.getVal(), phoRes.getError()), ], position=(0.59, 0.8), textsize=22, rowheight=0.07).draw() ## CMS Preliminary: ## Data or MC if 'data' in self.name: Latex([ 'CMS Preliminary, #sqrt{s} = 8 TeV, #int L dt = 19.6 fb^{-1}' ], position=(0.15, 0.93), textsize=22).draw() else: Latex(['CMS Preliminary, #sqrt{s} = 8 TeV, Simulation'], position=(0.15, 0.93), textsize=22).draw() labels = [] ## Data or MC #if 'data' in self.name: #labels.extend([ #'Data', #]) #else: #labels.append('Simulation') ## EB or EE #if 'EB' in self.name: #labels.append('ECAL Barrel') #else: #labels.append('ECAL Endcaps') #if 'highR9' in self.name: #labels.append('R_{9} > 0.94') #labels.append('E_{T}^{#gamma} > 20 GeV') ## Regression or not if 'HggRegression' in self.subdir.split('_'): labels.append('Regression') else: labels.append('No Regression') Latex(labels, position=(0.2, 0.8), textsize=22, rowheight=0.07).draw() canvas.Modified() canvas.Update() gpad_save.cd()
t.setVal(0) t.SetTitle('log(E_{reco}^{#gamma}/E_{gen}^{#gamma})') phoScale.setVal(t2pdf.s0val) phoRes.setVal(t2pdf.r0val) t2pdf.fitTo(t2data, roo.Range(ROOT.TMath.Log(0.5), ROOT.TMath.Log(1.5))) plot = t.frame(roo.Range(-0.3, 0.3)) t2data.plotOn(plot) t2pdf.plotOn(plot) plot.Draw() Latex([ 's_{shape}: %.3f %%' % t2pdf.s0val, 's_{fit}: %.3f #pm %.3f %%' % (phoScale.getVal(), phoScale.getError()), 's_{fit} - s_{shape}: %.4f #pm %.4f %%' % ( phoScale.getVal() - t2pdf.s0val, phoScale.getError() ), 'r_{shape}: %.3f %%' % t2pdf.r0val, 'r_{fit}: %.3f #pm %.3f %%' % (phoRes.getVal(), phoRes.getError()), 'r_{fit}/r_{shape}: %.4f #pm %.4f' % ( phoRes.getVal() / t2pdf.r0val, phoRes.getError() / t2pdf.r0val), ], position=(0.2, 0.75)).draw() canvases.update() t.setRange(*t1range) xtpdf.fitTo(xtdata, roo.NumCPU(8), roo.Verbose(True), roo.Timer(True), roo.SumW2Error(True), roo.Minos(ROOT.RooArgSet(phoRes))) ## Plot fXT(t|s,r) fitted to data ## canvases.next('tpdf').SetGrid()
## Import the data in the workspace data.SetName('data_%s' % name) w.Import(data) ## Also build the PDF's ## m = w.factory('KeysPdf::model%d(mmgMass, data%d, NoMirror, 2)' % (i, i)) ## dataCollection.append(data) ## models.append(m) ## fit the transformed model to the test data tmodel.fitTo(data) sFitted.append(phoScale.getVal()) sFittedErr.append(phoScale.getError()) labels.append('#Deltas = %.2f #pm %.2f %%' % (phoScale.getVal(), phoScale.getError())) latexlabels = Latex(labels, position = (0.25, 0.8)) ## Scan -log(L) vs photon scale sframe = phoScale.frame(Bins(100), Range(sFitted[-1] - 5*sFittedErr[-1], sFitted[-1] + 5*sFittedErr[-1])) nll = RooNLLVar('nll', 'nll', tmodel, data) nll.plotOn(sframe, ShiftToZero()) canvases.next(name + '_nll') phoScale.SetTitle('#Deltas') # sframe.GetXaxis().SetTitle('#Deltas (%)') sframe.GetYaxis().SetTitle('-#Delta log L(#Deltas)') sframe.Draw() latexlabels.draw() canvases.canvases[-1].Update()
tdata = calibrator.get_smeared_data(stest, rtest) tdata.SetName('tdata') pdf.fitTo(tdata, roo.Range(60, 120), roo.Minos()) calibrator.phoEResPdf.fitTo(tdata, roo.Range(-50, 50)) canvases.next('test_fit') plot = mmgMass.frame(roo.Range(70, 110)) tdata.plotOn(plot) pdf.plotOn(plot) plot.Draw() Latex( [ 's_{true}: %.3f #pm %.3f %%' % (calibrator.s.getVal(), calibrator.s.getError()), ## 's_{fit}: %.3f #pm %.3f %%' % (phoScale.getVal(), ## phoScale.getError()), 'r_{true}: %.3f #pm %.3f %%' % (calibrator.r.getVal(), calibrator.r.getError()), 'r_{fit}: %.3f ^{+%.3f}_{%.3f} %%' % (phoRes.getVal(), phoRes.getErrorHi(), phoRes.getErrorLo()), ], position=(0.2, 0.8)).draw() canvases.next('test_nll').SetGrid() nll = pdf.createNLL(tdata, roo.Range(60, 120)) rframe = phoRes.frame( roo.Range(phoRes.getVal() + 3 * phoRes.getErrorLo(), phoRes.getVal() + 3 * phoRes.getErrorHi())) nll.plotOn(rframe, roo.ShiftToZero()) rframe.Draw() canvases.update()
def process_monte_carlo(): ''' Get, fit and plot monte carlo. ''' global fitdata1 fitdata1 = fit_calibrator.get_smeared_data( sfit, rfit, 'fitdata1', 'fitdata1', True ) fitdata1.reduce(ROOT.RooArgSet(mmgMass, mmMass)) fitdata1.append(data['zj1']) fitdata1.SetName('fitdata1') data['fit1'] = fitdata1 if reduce_data == True: fitdata1 = fitdata1.reduce(roo.Range(reduced_entries, fitdata1.numEntries())) check_timer('3. get fit data (%d entries)' % fitdata1.numEntries()) nll = pm.createNLL(fitdata1, roo.Range('fit'), roo.NumCPU(8)) minuit = ROOT.RooMinuit(nll) minuit.setProfile() minuit.setVerbose() phoScale.setError(1) phoRes.setError(1) ## Initial HESSE status = minuit.hesse() fitres = minuit.save(name + '_fitres1_inithesse') w.Import(fitres, fitres.GetName()) check_timer('4. initial hesse (status: %d)' % status) ## Minimization minuit.setStrategy(2) status = minuit.migrad() fitres = minuit.save(name + '_fitres2_migrad') w.Import(fitres, fitres.GetName()) check_timer('5. migrad (status: %d)' % status) ## Parabolic errors status = minuit.hesse() fitres = minuit.save(name + '_fitres3_hesse') w.Import(fitres, fitres.GetName()) check_timer('6. hesse (status: %d)' % status) ## Minos errors status = minuit.minos() fitres = minuit.save(name + '_fitres4_minos') w.Import(fitres, fitres.GetName()) check_timer('7. minos (status: %d)' % status) #fres = pm.fitTo(fitdata1, roo.SumW2Error(True), #roo.Range('fit'), ## roo.Strategy(2), #roo.InitialHesse(True), #roo.Minos(), #roo.Verbose(True), #roo.NumCPU(8), roo.Save(), roo.Timer()) signal_model._phorhist.GetXaxis().SetRangeUser(75, 105) signal_model._phorhist.GetYaxis().SetRangeUser(0, 15) signal_model._phorhist.GetXaxis().SetTitle('%s (%s)' % (mmgMass.GetTitle(), mmgMass.getUnit())) signal_model._phorhist.GetYaxis().SetTitle('E^{#gamma} Resolution (%)') signal_model._phorhist.GetZaxis().SetTitle('Probability Density (1/GeV/%)') signal_model._phorhist.SetTitle(latex_title) signal_model._phorhist.GetXaxis().SetTitleOffset(1.5) signal_model._phorhist.GetYaxis().SetTitleOffset(1.5) signal_model._phorhist.GetZaxis().SetTitleOffset(1.5) signal_model._phorhist.SetStats(False) canvases.next(name + '_phorhist') signal_model._phorhist.Draw('surf1') global graph graph = signal_model.make_mctrue_graph() graph.GetXaxis().SetTitle('E^{#gamma} resolution (%)') graph.GetYaxis().SetTitle('m_{#mu^{+}#mu^{-}#gamma} effective #sigma (GeV)') graph.SetTitle(latex_title) canvases.next(name + '_mwidth_vs_phor').SetGrid() graph.Draw('ap') mmgMass.setBins(80) plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle('Fall11 MC, ' + latex_title) fitdata1.plotOn(plot) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot')) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot'), roo.Components('*zj*'), roo.LineStyle(ROOT.kDashed)) canvases.next(name + '_fit').SetGrid() plot.Draw() ## Estimate the MC truth phos and phor: old_precision = set_default_integrator_precision(2e-9, 2e-9) calibrator0.s.setRange(-15, 15) calibrator0.r.setRange(0,25) calibrator0.phoEResPdf.fitTo(fitdata1, roo.Range(-50, 50), roo.Strategy(2)) set_default_integrator_precision(*old_precision) set_mc_truth(calibrator0.s, calibrator0.r) ## Store the result in the workspace: w.saveSnapshot('mc_fit', ROOT.RooArgSet(phoScale, phoRes, phoScaleTrue, phoResTrue)) ## Draw the results on the canvas: Latex([ 'E^{#gamma} Scale (%)', ' MC Truth: %.2f #pm %.2f' % (calibrator0.s.getVal(), calibrator0.s.getError()), ' MC Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f}' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} Resolution (%)', ' MC Truth: %.2f #pm %.2f' % (calibrator0.r.getVal(), calibrator0.r.getError()), ' MC Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f}' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), '', 'Signal Purity (%)', ' MC Truth: %.2f' % fsr_purity, ' MC Fit: %.2f #pm %.2f' % ( 100 * w.var('signal_f').getVal(), 100 * w.var('signal_f').getError() ) ], position=(0.2, 0.8) ).draw() check_timer('8. fast plots')