sigma ) #pdf = RooNumConvPdf("pdf", 'convolution', x, p1, p2) x.setBins(10000,"fft") ; pdf = RooFFTConvPdf("pdf", 'convolution', x, p2, p1) pdf.setBufferFraction(5.0) #pdf.setBufferFraction(50.0) # Plot PDF canvas = TCanvas("c1","",1200,480); canvas.Divide(3,1); canvas.cd(1) xframe = x.frame() p1.plotOn( xframe ) xframe.Draw() gPad.SetLogy() #canvas.cd(2) #xframe2 = x.frame() #p2.plotOn( xframe2 ) #xframe2.Draw() #gPad.SetLogy() canvas.cd(3) xframe3 = x.frame() pdf.plotOn( xframe3 ) xframe3.Draw() gPad.SetLogy()
## reducedData['phoERes'].plotOn(plot) ## phoEResShape.plotOn(plot) ## phoEResShape2.plotOn(plot, LineColor(kRed)) ## plot.Draw() ## llabels.draw() ## plots.append(plot) ## Mass smearing due to photon resolution canvases.next("mmgMassPhoSmear") # .SetLogy() mmgMassShifted.SetTitle("m(#mu#mu + reco #gamma) - m(#mu#mu + gen #gamma)") plot = mmgMassShifted.frame(Range(-5, 5)) # Range(-5,5)) #Range(0, 500)) mmgMassShifted.SetTitle(mmgMassShiftedTitle) plot.SetTitle('"Resolution:" Modeling of Mass Smearing Due to Photon Energy Resolution') reducedData["mmgMassPhoSmear"].plotOn(plot) phoSmear.fitTo(reducedData["mmgMassPhoSmear"], Range(-5, 5), NumCPU(3)) phoSmear.plotOn(plot) phoSmear.paramOn(plot) phoSmear2.fitTo(reducedData["mmgMassPhoSmear"], Range(-5, 5), NumCPU(3)) phoSmear2.plotOn(plot, LineColor(kRed), LineStyle(kDashed)) plot.Draw() llabels.draw() plots.append(plot) ## Plot theory, smearing and smeared theory plot = mmgMassShifted.frame(Range(-5, 5)) plot.SetTitle("Model = Theory * Resolution") phoScale.setVal(0) phoRes.setVal(phoEResMC) theory.plotOn(plot) phoSmear.plotOn(plot, LineColor(kRed)) theoryXphoSmear.plotOn(plot, LineColor(kBlack))
phoSmearData.merge(data.reduce(RooArgSet(mmgMass, mmMass))) phoSmearData.Print() mmgMass.setBins(3) mmMass.setBins(5) mmgMassShifted.setBins(40) phoSmearDataBinned = phoSmearData.binnedClone() # phoSmear.fitTo(reducedData['mmgMassPhoSmear'], Range(-5, 5), NumCPU(3)) phoSmear.fitTo(phoSmearDataBinned, ConditionalObservables(RooArgSet(mmMass, mmgMass))) canvases.next('mmgMassPhoSmear')#.SetLogy() mmgMassShifted.SetTitle('m(#mu#mu + reco #gamma) - m(#mu#mu + gen #gamma)') plot = mmgMassShifted.frame(Range(-5,5)) #Range(-5,5)) #Range(0, 500)) mmgMassShifted.SetTitle(mmgMassShiftedTitle) plot.SetTitle('"Resolution:" Modeling of Mass Smearing Due to Photon Energy Resolution') reducedData['mmgMassPhoSmear'].plotOn(plot) phoSmear.plotOn(plot) phoSmear.paramOn(plot) plot.Draw() llabels.draw() plots.append(plot) ## ## Plot theory, smearing and smeared theory ## plot = mmgMassShifted.frame(Range(-5, 5)) ## plot.SetTitle('Model = Theory * Resolution') ## phoScale.setVal(0) ## phoRes.setVal(phoEResMC) ## theory.plotOn(plot) ## phoSmear.plotOn(plot, LineColor(kRed)) ## theoryXphoSmear.plotOn(plot, LineColor(kBlack)) ## c1 = canvases.next('convolution') ## c1.SetGridx()
# Not to be included in the Moment Morphing (just a check) file3 = R.TFile(f3) hist3 = file3.Get('my_model_hist') hist3.SetDirectory(0) hist3_events = hist3.Integral() # Setup Workspace and frame w = R.RooWorkspace('w') x = w.factory('x[70,230]') x.setBins(32) frame = x.frame() # Z = 125 GeV data_hist1 = RooDataHist('dhist1', 'dhist1', RooArgList(x), hist1) pdf1 = RooHistPdf('phist1', 'phist1', RooArgSet(x), data_hist1) pdf1.plotOn(frame, RooFit.LineColor(R.kGreen), RooFit.Normalization(hist1_events)) # Z = 175 GeV data_hist2 = RooDataHist('dhist2', 'dhist2', RooArgList(x), hist2) pdf2 = RooHistPdf('phist2', 'phist2', RooArgSet(x), data_hist2) pdf2.plotOn(frame, RooFit.LineColor(R.kGreen), RooFit.Normalization(hist2_events)) # Not to be included in the Moment Morphing (just a check) data_hist3 = RooDataHist('dhist3', 'dhist3', RooArgList(x), hist3) pdf3 = RooHistPdf('phist3', 'phist3', RooArgSet(x), data_hist3) pdf3.plotOn(frame, RooFit.LineColor(R.kBlue), RooFit.Normalization(hist3_events)) data_hist3.plotOn(frame) # Create a RooArgList to store pdfs and fill it pdfs = RooArgList() pdfs.add(pdf1)
# sframe.GetXaxis().SetTitle('#Deltas (%)') sframe.GetYaxis().SetTitle('-#Delta log L(#Deltas)') sframe.Draw() latexlabels.draw() canvases.canvases[-1].Update() ## Display data overlaid with fitted and extrapolated models canvases.next(name + '_mmgMass') frame = mmgMass.frame(Range(60,120)) frame.SetTitle('') frame.GetXaxis().SetTitle( 'm_{#mu#mu#gamma} (GeV)' ) data.plotOn(frame) # m.plotOn(frame) tmodel.plotOn(frame) #tmodel.paramOn(frame) frame.Draw() latexlabels.draw() canvases.canvases[-1].Update() ## Get the test datasets and models ## Plot fitted vs true print 'report:' fPho.Print() phoScale.Print() mmgMode.Print() mmgScale.Print()
def morph(hist1, hist2, mass1, mass2, targetMass, debug=False): from ROOT import gROOT, RooRealVar, RooIntegralMorph,\ kRed,kBlue,kViolet, RooDataHist, RooArgSet,\ RooArgList, RooHistPdf, RooAbsReal, RooFit import re if mass1 < mass2: histLow = hist1 massLow = mass1 histHigh = hist2 massHigh = mass2 else: histLow = hist2 massLow = mass2 histHigh = hist1 massHigh = mass1 x = RooRealVar("x", "x", histLow.GetXaxis().GetXmin(), histLow.GetXaxis().GetXmax()) mAlpha = 1.0 - float(targetMass - massLow) / float(massHigh - massLow) print 'alpha:', mAlpha, newIntegral = histLow.Integral() + \ (targetMass - massLow) * \ (histHigh.Integral()-histLow.Integral()) / \ (massHigh-massLow) print 'low integral:', histLow.Integral(), \ 'high integral:', histHigh.Integral(), \ 'new integral:', newIntegral newHistLow = RooDataHist("sigHistLow_hist", "sigHistLow_hist", RooArgList(x), histLow) sigHistLow = RooHistPdf("sigHistLow", "sigHistLow", RooArgList(x), RooArgList(x), newHistLow) newHistHigh = RooDataHist("sigHistHigh_hist", "sigHistHigh_hist", RooArgList(x), histHigh) sigHistHigh = RooHistPdf("sigHistHigh", "sigHistHigh", RooArgList(x), RooArgList(x), newHistHigh) #x.Print("v") x.setBins(histLow.GetNbinsX(), "cache") alpha_morph = RooRealVar("alpha_morph", "#alpha_{morph}", mAlpha, 0., 1.) alpha_morph.setBins(10, "cache") sigModel = RooIntegralMorph("sigModel", "sigModel", sigHistLow, sigHistHigh, x, alpha_morph) if (debug): from ROOT import gPad, RooFit frame = x.frame() sigHistLow.plotOn(frame, RooFit.LineColor(kRed + 1), RooFit.LineStyle(2)) sigHistHigh.plotOn(frame, RooFit.LineColor(kBlue + 1), RooFit.LineStyle(2)) sigModel.plotOn(frame, RooFit.LineColor(kViolet + 1), RooFit.LineStyle(9)) frame.Draw() gPad.Update() gPad.WaitPrimitive() morphHist = sigModel.createHistogram( re.sub(r'\d+', '%i' % targetMass, hist1.GetName()), x, RooFit.Binning(histLow.GetNbinsX())) morphHist.Scale(newIntegral / morphHist.Integral()) morphHist.SetName(re.sub(r'\d+', '%i' % targetMass, hist1.GetName())) # if debug: # morphHist.Print() return morphHist
def main(options, args): from ROOT import gSystem, gROOT, gStyle gROOT.SetBatch() gSystem.Load("libRooFitCore") if options.doWebPage: from lip.Tools.rootutils import loadToolsLib, apply_modifs loadToolsLib() from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList from ROOT import kWhite, kBlue, kOpenSquare if options.doWebPage: from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot rootglobestyle.setTDRStyle() gStyle.SetMarkerSize(1.5) gStyle.SetTitleYOffset(1.5) gStyle.SetPadLeftMargin(0.16) gStyle.SetPadRightMargin(0.05) gStyle.SetPadTopMargin(0.05) gStyle.SetPadBottomMargin(0.13) gStyle.SetLabelFont(42, "XYZ") gStyle.SetLabelOffset(0.007, "XYZ") gStyle.SetLabelSize(0.05, "XYZ") gStyle.SetTitleSize(0.06, "XYZ") gStyle.SetTitleXOffset(0.9) gStyle.SetTitleYOffset(1.24) gStyle.SetTitleFont(42, "XYZ") ## ## Read files ## options.outdir = "%s_m%1.0f" % (options.outdir, options.mH) if options.fp: options.outdir += "_fp" ncat = options.ncat cats = options.cats if cats is "": categories = ["_cat%d" % i for i in range(0, ncat)] else: categories = ["_cat%s" % i for i in cats.split(",")] if options.mva: clables = { "_cat0": ("MVA > 0.89", ""), "_cat1": ("0.74 #leq MVA", "MVA < 0.89"), "_cat2": ("0.545 #leq MVA", "MVA < 0.74"), "_cat3": ("0.05 #leq MVA", "MVA < 0.545"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } else: clables = { "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"), "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"), "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"), "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } helper = Helper() fin = TFile.Open(options.infile) helper.files.append(fin) ws = fin.Get("cms_hgg_workspace") mass = ws.var("CMS_hgg_mass") mass.SetTitle("m_{#gamma#gamma}") mass.setUnit("GeV") mass.setRange(100., 150.) mass.setBins(100, "plot") mass.setBins(5000) print ws aset = RooArgSet(mass) helper.objs.append(mass) helper.objs.append(aset) fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8)) if not options.binned and not options.refit: finpdf = TFile.Open(options.infilepdf) helper.files.append(finpdf) wspdf = finpdf.Get("wsig") else: wspdf = ws for c in categories: processes = ["ggh", "vbf", "wzh"] if options.fp: processes = ["vbf", "wzh"] ### elif clables[c][0] == "Di-jet": ### processes = [ "vbf", "ggh" ] dsname = "sig_mass_m%1.0f%s" % (options.mH, c) print dsname print ws ds = ws.data("sig_%s_mass_m%1.0f%s" % (processes[0], options.mH, c)).Clone(dsname) for proc in processes[1:]: ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c))) helper.dsets.append(ds) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, ds) pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass, ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: if options.refit: if options.refitall and clables[c][0] != "Di-jet": rpdfs = [] for proc in processes: for ngaus in range(1, 4): pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus, ngaus == 3) pp.fitTo( ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)), RooFit.Strategy(0), *fitopt) rpdfs.append(pp) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs))) else: if options.refitall and clables[c][0] == "Di-jet": for ngaus in range(1, 5): pdf = build_pdf(ws, c, ngaus, ngaus == 5) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: for ngaus in range(1, 4): pdf = build_pdf(ws, c, ngaus, ngaus == 3) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p)) for p in processes) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs)) helper.add(pdf, pdf.GetName()) plot_pdf = pdf.Clone("pdf_%s" % dsname) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(ds) cdf = pdf.createCdf(aset) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) ### hmin, hmax, hm = get_FWHM( points ) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma%s" % c) helper.add((hmin, hmax, hm), "FWHM%s" % c) helper.add(ds.sumEntries(), "sumEntries%s" % c) # signal model integral # data integral for PAS tables data = ws.data("data_mass%s" % c) helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" % (options.mH - 10., options.mH + 10.)), "data_sumEntries%s" % c) del cdf del pdf dsname = "sig_mass_m%1.0f_combcat" % options.mH print dsname combined_ds = helper.dsets[0].Clone(dsname) for d in helper.dsets[1:]: combined_ds.append(d) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, combined_ds) pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass, combined_ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: #### pdf = build_pdf(ws,"_combcat") #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt ) #### plot_pdf = pdf.Clone( "pdf_%s" % dsname ) pdf = RooAddPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, RooArgList(*(helper.histos["hggpdfrel%s" % c] for c in categories))) plot_pdf = pdf cdf = pdf.createCdf(aset) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(combined_ds) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma_combcat") helper.add((hmin, hmax, hm), "FWHM_combcat") helper.add(plot_ds.sumEntries(), "sumEntries_combcat") mass.setRange("higgsrange", options.mH - 25., options.mH + 15.) del cdf del pdf del helper.dsets ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}") label = TLatex(0.7, 0.86, "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}") label.SetNDC(1) ## ## Make web page with plots ## if options.doWebPage: hth = HtmlHelper(options.outdir) hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set( "href", "../?C=M;O=D") hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set( "href", "./") tab = hth.body().add(HtmlTable()) ip = 0 for c in ["_combcat"] + categories: ### for c in categories: if options.doWebPage and ip % 4 == 0: row = tab.row() ip = ip + 1 dsname = "sig_mass_m%1.0f%s" % (options.mH, c) canv = TCanvas(dsname, dsname, 600, 600) helper.objs.append(canv) ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322) leg = TLegend(0.2, 0.96, 0.5, 0.55) #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] ) hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange")) helper.objs.append(hplotcompint) helper.objs.append(leg) plot_ds = helper.histos["plot_%s" % dsname] plot_pdf = helper.histos["pdf_%s" % dsname] wmin, wmax = helper.histos["eff_sigma%s" % c] hmin, hmax, hm = helper.histos["FWHM%s" % c] print hmin, hmax, hm style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0)) style_seff = ( RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), ) style_ds = (RooFit.MarkerStyle(kOpenSquare), ) plot_ds.plotOn(hplotcompint, RooFit.Invisible()) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.FillColor(19), RooFit.DrawOption("F"), *style_seff) seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.LineColor(15), *style_seff) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range("higgsrange"), *style) pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_ds.plotOn(hplotcompint, *style_ds) pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) iob = int(hplotcompint.numItems() - 1) leg.AddEntry(pointsleg, "Simulation", "pe") leg.AddEntry(pdfleg, "Parametric model", "l") leg.AddEntry(seffleg, "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl") clabel = TLatex(0.74, 0.65, "#scale[0.65]{#splitline{%s}{%s}}" % clables[c]) clabel.SetNDC(1) helper.objs.append(clabel) hm = hplotcompint.GetMaximum() * 0.5 * 0.9 ### hm = pdfleg.GetMaximum()*0.5 fwhmarrow = TArrow(hmin, hm, hmax, hm) fwhmarrow.SetArrowSize(0.03) helper.objs.append(fwhmarrow) fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC") fwhmlabel.SetFillStyle(0) fwhmlabel.SetLineColor(kWhite) reducedFWHM = (hmax - hmin) / 2.3548200 fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM) helper.objs.append(fwhmlabel) hplotcompint.SetTitle("") hplotcompint.GetXaxis().SetNoExponent(True) hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)") hplotcompint.GetXaxis().SetNdivisions(509) ## hplotcompint.GetYaxis().SetTitle("A.U."); ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4); hplotcompint.Draw() leg.Draw("same") label.Draw("same") clabel.Draw("same") fwhmarrow.Draw("<>") fwhmlabel.Draw("same") plot_ds.sumEntries() if options.doWebPage: hpl = HtmlPlot(canv, False, "", True, True, True) hpl.caption("<i>%s</i>" % canv.GetTitle()) row.cell(hpl) else: if os.path.isdir(options.outdir) is False: os.mkdir(options.outdir) for ext in "C", "png", "pdf": canv.SaveAs( os.path.join(options.outdir, "%s.%s" % (canv.GetName(), ext))) if "comb" in c: ip = 0 if options.doWebPage: print "Creating pages..." hth.dump() for f in helper.files: f.Close() gROOT.Reset() from pprint import pprint pprint(helper) print 'Summary statistics per event class' print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH sigTotal = 0. dataTotal = 0. for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] sigTotal += sigVal dataTotal += datVal for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] - helper.histos["eff_sigma%s" % c][0]) fwhm = (helper.histos["FWHM%s" % c][1] - helper.histos["FWHM%s" % c][0]) / 2.3548200 print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % ( sigVal, 100. * sigVal / sigTotal, datVal / (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm) print "Done."
#Now, some plots: ipframe_1 = LOG_D0_IPCHI2_OWNPV.frame(RooFit.Title("Bin "+str(i))) ipframe_2 = LOG_D0_IPCHI2_OWNPV.frame(RooFit.Title("D^{*}#mu, bin "+str(i))) ipframe_3 = DTF_D0sPi_M.frame(RooFit.Title("Signal D* mass, bin "+str(i))) ipframe_4 = DTF_D0sPi_M.frame(RooFit.Title("D*_{from B} mass, bin"+str(i))) dataset_RS_dtb.plotOn(ipframe_1) Two_hists.plotOn(ipframe_1, RooFit.Components("key_COMB"), RooFit.LineColor(2),RooFit.LineWidth(4)) Two_hists.plotOn(ipframe_1, RooFit.Components("shape_COMB"), RooFit.LineColor(2),RooFit.LineWidth(2)) Two_hists.plotOn(ipframe_1, RooFit.Components("shape_RS_0"), RooFit.LineColor(3),RooFit.LineWidth(2)) Two_hists.plotOn(ipframe_1, RooFit.Components("s_fage"), RooFit.LineColor(3),RooFit.LineWidth(2)) Two_hists.plotOn(ipframe_1, RooFit.LineColor(4),RooFit.LineWidth(2)) dataset_COMB_CORR_dtb.plotOn(ipframe_2) shape_COMB.plotOn(ipframe_2, RooFit.LineColor(2),RooFit.LineWidth(4)) dataset_RS_dtb.plotOn(ipframe_3) dataset_COMB_CORR_dtb.plotOn(ipframe_4) c_IP = TCanvas("c_IP","c_IP",900,900) c_IP.Divide(2,2) c_IP.cd(1) ipframe_1.Draw() c_IP.cd(2) ipframe_2.Draw() c_IP.cd(3) ipframe_3.Draw() c_IP.cd(4) ipframe_4.Draw()
k = KeysPdf('k', 'k', x, data1, KeysPdf.NoMirror, 2) ## 4. Use k to build HistPDF with _transformed_ x variable t = (x-m)/s ## h1((x-hm)/hs|m1,s1) t = w.factory('FormulaVar::t("(x - hm) / hs", {x, hm[0,-5,5], hs[1,0.1,3]})') hist = k.createHistogram('x', 10000) dh = DataHist('dh', 'dh', ArgList(x), hist) h = HistPdf('h', 'h', ArgList(t), ArgList(x), dh, 2) ## 5. Plot results f1 = x.frame() f1.SetTitle('Training Data') data1.plotOn(f1) g.plotOn(f1) k.plotOn(f1, LineColor(kRed), LineStyle(kDashed)) h.plotOn(f1, LineColor(kBlack), LineStyle(kDashed)) canvases.next('Training_Data') f1.Draw() ## 6. Fit h1 to data2 to simulate a "measurement" of m2, s2. h.fitTo(data2) f2 = x.frame() f2.SetTitle('Test Data') data2.plotOn(f2) h.plotOn(f2) h.paramOn(f2) canvases.next('Test_Data') f2.Draw() for c in canvases.canvases:
def main(options,args): from ROOT import gSystem, gROOT, gStyle gROOT.SetBatch() gSystem.Load("libRooFitCore") if options.doWebPage: from lip.Tools.rootutils import loadToolsLib, apply_modifs loadToolsLib() from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList from ROOT import kWhite, kBlue, kOpenSquare if options.doWebPage: from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot rootglobestyle.setTDRStyle() gStyle.SetMarkerSize(1.5) gStyle.SetTitleYOffset(1.5) gStyle.SetPadLeftMargin(0.16) gStyle.SetPadRightMargin(0.05) gStyle.SetPadTopMargin(0.05) gStyle.SetPadBottomMargin(0.13) gStyle.SetLabelFont(42,"XYZ") gStyle.SetLabelOffset(0.007, "XYZ") gStyle.SetLabelSize(0.05,"XYZ") gStyle.SetTitleSize(0.06,"XYZ") gStyle.SetTitleXOffset(0.9) gStyle.SetTitleYOffset(1.24) gStyle.SetTitleFont(42,"XYZ") ## ## Read files ## options.outdir = "%s_m%1.0f" % ( options.outdir, options.mH ) if options.fp: options.outdir += "_fp" ncat=options.ncat cats=options.cats if cats is "": categories =[ "_cat%d" % i for i in range(0,ncat) ] else: categories =[ "_cat%s" % i for i in cats.split(",") ] if options.mva: clables = { "_cat0" : ("MVA > 0.89",""), "_cat1" : ("0.74 #leq MVA","MVA < 0.89"), "_cat2" : ("0.545 #leq MVA","MVA < 0.74"), "_cat3" : ("0.05 #leq MVA","MVA < 0.545"), "_cat4" : ("Di-jet","Tagged"), "_cat5" : ("Di-jet","Tagged"), "_combcat" : ("All Classes","Combined") } else: clables = { "_cat0" : ("max(|#eta|<1.5","min(R_{9})>0.94"), "_cat1" : ("max(|#eta|<1.5","min(R_{9})<0.94"), "_cat2" : ("max(|#eta|>1.5","min(R_{9})>0.94"), "_cat3" : ("max(|#eta|>1.5","min(R_{9})<0.94"), "_cat4" : ("Di-jet","Tagged"), "_cat5" : ("Di-jet","Tagged"), "_combcat" : ("All Classes","Combined") } helper = Helper() fin = TFile.Open(options.infile) helper.files.append(fin) ws = fin.Get("cms_hgg_workspace") mass = ws.var("CMS_hgg_mass") mass.SetTitle("m_{#gamma#gamma}"); mass.setUnit("GeV"); mass.setRange(100.,150.) mass.setBins(100,"plot") mass.setBins(5000) print ws aset = RooArgSet(mass) helper.objs.append( mass ) helper.objs.append( aset ) fitopt = ( RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8) ) if not options.binned and not options.refit: finpdf = TFile.Open(options.infilepdf) helper.files.append(finpdf) wspdf = finpdf.Get("wsig") else: wspdf = ws for c in categories: processes = [ "ggh", "vbf", "wzh" ] if options.fp: processes = [ "vbf", "wzh" ] ### elif clables[c][0] == "Di-jet": ### processes = [ "vbf", "ggh" ] dsname = "sig_mass_m%1.0f%s" % (options.mH,c) print dsname print ws ds = ws.data( "sig_%s_mass_m%1.0f%s" % (processes[0],options.mH,c) ).Clone(dsname) for proc in processes[1:]: ds.append( ws.data( "sig_%s_mass_m%1.0f%s" % (proc,options.mH,c) ) ) helper.dsets.append( ds ) if options.binned: binned_ds = RooDataHist( "binned_%s" % dsname,"binned_%s" % dsname,aset, ds) pdf = RooKeysPdf( "pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass, ds ) plot_pdf = RooHistPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds ) helper.add( binned_ds, binned_ds.GetName() ) else: if options.refit: if options.refitall and clables[c][0] != "Di-jet": rpdfs = [] for proc in processes: for ngaus in range(1,4): pp = build_pdf(ws,"%s_%s" % (c,proc),ngaus,ngaus==3 ) pp.fitTo( ws.data( "sig_%s_mass_m%1.0f%s" % (proc,options.mH,c)), RooFit.Strategy(0), *fitopt ) rpdfs.append(pp) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs) )) else: if options.refitall and clables[c][0] == "Di-jet": for ngaus in range(1,5): pdf = build_pdf(ws,c,ngaus,ngaus==5) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt ) else: for ngaus in range(1,4): pdf = build_pdf(ws,c,ngaus,ngaus==3) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt ) else: pdfs = (wspdf.pdf( "hggpdfrel%s_%s" % (c, p)) for p in processes ) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs )) helper.add(pdf,pdf.GetName()) plot_pdf = pdf.Clone("pdf_%s" % dsname) plot_ds = RooDataHist( "plot_%s" % dsname,"plot_%s" % dsname, aset, "plot") plot_ds.add( ds ) cdf = pdf.createCdf(aset) hmin, hmax, hm = get_FWHM( mass, pdf, cdf, options.mH-10., options.mH+10. ) wmin, wmax = get_eff_sigma( mass, pdf, cdf, options.mH-10., options.mH+10. ) ### hmin, hmax, hm = get_FWHM( points ) helper.add( plot_ds, plot_ds.GetName() ) helper.add( plot_pdf, plot_pdf.GetName() ) helper.add( (wmin,wmax), "eff_sigma%s" % c ) helper.add( (hmin, hmax, hm), "FWHM%s" % c ) helper.add( ds.sumEntries(), "sumEntries%s" %c ) # signal model integral # data integral for PAS tables data = ws.data( "data_mass%s"%c) helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f"%(options.mH-10.,options.mH+10.)),"data_sumEntries%s"%c) del cdf del pdf dsname = "sig_mass_m%1.0f_combcat" % options.mH print dsname combined_ds = helper.dsets[0].Clone(dsname) for d in helper.dsets[1:]: combined_ds.append(d) if options.binned: binned_ds = RooDataHist( "binned_%s" % dsname,"binned_%s" % dsname,aset, combined_ds) pdf = RooKeysPdf( "pdf_%s" % (dsname), "pdf_%s" % dsname, mass, combined_ds ) plot_pdf = RooHistPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds ) helper.add( binned_ds, binned_ds.GetName() ) else: #### pdf = build_pdf(ws,"_combcat") #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt ) #### plot_pdf = pdf.Clone( "pdf_%s" % dsname ) pdf = RooAddPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, RooArgList( *(helper.histos["hggpdfrel%s" % c] for c in categories) ) ) plot_pdf = pdf cdf = pdf.createCdf(aset) plot_ds = RooDataHist( "plot_%s" % dsname,"plot_%s" % dsname, aset, "plot") plot_ds.add( combined_ds ) wmin, wmax = get_eff_sigma( mass, pdf, cdf, options.mH-10., options.mH+10. ) hmin, hmax, hm = get_FWHM( mass, pdf, cdf, options.mH-10., options.mH+10. ) helper.add( plot_ds, plot_ds.GetName() ) helper.add( plot_pdf, plot_pdf.GetName() ) helper.add( (wmin,wmax), "eff_sigma_combcat" ) helper.add( (hmin, hmax, hm), "FWHM_combcat" ) helper.add( plot_ds.sumEntries(), "sumEntries_combcat" ) mass.setRange("higgsrange",options.mH-25.,options.mH+15.); del cdf del pdf del helper.dsets ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}") label = TLatex(0.7,0.86,"#scale[0.65]{#splitline{CMS preliminary}{Simulation}}") label.SetNDC(1) ## ## Make web page with plots ## if options.doWebPage: hth = HtmlHelper(options.outdir) hth.navbar().cell( HtmlTag("a") ).firstChild().txt("..").set("href","../?C=M;O=D") hth.navbar().cell( HtmlTag("a") ).firstChild().txt("home").set("href","./") tab = hth.body().add( HtmlTable() ) ip = 0 for c in ["_combcat"]+categories: ### for c in categories: if options.doWebPage and ip % 4 == 0: row = tab.row() ip = ip + 1 dsname = "sig_mass_m%1.0f%s" % (options.mH,c) canv = TCanvas(dsname,dsname,600,600) helper.objs.append(canv) ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322) leg = TLegend(0.2,0.96,0.5,0.55) #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] ) hplotcompint = mass.frame(RooFit.Bins(250),RooFit.Range("higgsrange")) helper.objs.append(hplotcompint) helper.objs.append(leg) plot_ds =helper.histos["plot_%s" % dsname ] plot_pdf =helper.histos["pdf_%s" % dsname ] wmin,wmax = helper.histos["eff_sigma%s" % c ] hmin, hmax, hm = helper.histos["FWHM%s" % c ] print hmin, hmax, hm style = ( RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0) ) style_seff = ( RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), ) style_ds = ( RooFit.MarkerStyle(kOpenSquare), ) plot_ds.plotOn(hplotcompint,RooFit.Invisible()) plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range(wmin,wmax), RooFit.FillColor(19), RooFit.DrawOption("F"), *style_seff) seffleg = hplotcompint.getObject(int(hplotcompint.numItems()-1)) plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range(wmin,wmax), RooFit.LineColor(15), *style_seff) plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range("higgsrange"),*style) pdfleg = hplotcompint.getObject(int(hplotcompint.numItems()-1)) plot_ds.plotOn(hplotcompint,*style_ds) pointsleg = hplotcompint.getObject(int(hplotcompint.numItems()-1)) iob = int( hplotcompint.numItems() - 1 ) leg.AddEntry( pointsleg, "Simulation", "pe" ) leg.AddEntry( pdfleg, "Parametric model", "l" ) leg.AddEntry( seffleg, "#sigma_{eff} = %1.2f GeV " % ( 0.5*(wmax-wmin) ), "fl" ) clabel = TLatex(0.74,0.65,"#scale[0.65]{#splitline{%s}{%s}}" % clables[c]) clabel.SetNDC(1) helper.objs.append(clabel) hm = hplotcompint.GetMaximum()*0.5*0.9 ### hm = pdfleg.GetMaximum()*0.5 fwhmarrow = TArrow(hmin,hm,hmax,hm) fwhmarrow.SetArrowSize(0.03) helper.objs.append(fwhmarrow) fwhmlabel = TPaveText(0.20,0.58,0.56,0.48,"brNDC") fwhmlabel.SetFillStyle(0) fwhmlabel.SetLineColor(kWhite) reducedFWHM = (hmax-hmin)/2.3548200 fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM) helper.objs.append(fwhmlabel) hplotcompint.SetTitle(""); hplotcompint.GetXaxis().SetNoExponent(True); hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)"); hplotcompint.GetXaxis().SetNdivisions(509); ## hplotcompint.GetYaxis().SetTitle("A.U."); ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4); hplotcompint.Draw(); leg.Draw("same") label.Draw("same") clabel.Draw("same") fwhmarrow.Draw("<>") fwhmlabel.Draw("same") plot_ds.sumEntries() if options.doWebPage: hpl = HtmlPlot(canv,False,"",True,True,True) hpl.caption("<i>%s</i>" % canv.GetTitle()) row.cell( hpl ) else: if os.path.isdir(options.outdir) is False: os.mkdir(options.outdir) for ext in "C","png","pdf": canv.SaveAs( os.path.join(options.outdir,"%s.%s" % (canv.GetName(), ext)) ) if "comb" in c: ip = 0 if options.doWebPage: print "Creating pages..." hth.dump() for f in helper.files: f.Close() gROOT.Reset() from pprint import pprint pprint(helper) print 'Summary statistics per event class' print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35'%options.mH sigTotal=0. dataTotal=0. for c in categories: sigVal = helper.histos["sumEntries%s"%c] datVal = helper.histos["data_sumEntries%s"%c] sigTotal+=sigVal dataTotal+=datVal for c in categories: sigVal = helper.histos["sumEntries%s"%c] datVal = helper.histos["data_sumEntries%s"%c] effSig = 0.5*(helper.histos["eff_sigma%s"%c][1]-helper.histos["eff_sigma%s"%c][0]) fwhm = (helper.histos["FWHM%s"%c][1]-helper.histos["FWHM%s"%c][0]) / 2.3548200 print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f'%(sigVal,100.*sigVal/sigTotal,datVal/(10.+10.),100.*datVal/dataTotal,effSig,fwhm) print "Done."
def morph(hist1, hist2, mass1, mass2, targetMass, debug = False): from ROOT import gROOT, RooRealVar, RooIntegralMorph,\ kRed,kBlue,kViolet, RooDataHist, RooArgSet,\ RooArgList, RooHistPdf, RooAbsReal, RooFit import re if mass1<mass2: histLow = hist1 massLow = mass1 histHigh = hist2 massHigh = mass2 else: histLow = hist2 massLow = mass2 histHigh = hist1 massHigh = mass1 x = RooRealVar("x", "x", histLow.GetXaxis().GetXmin(), histLow.GetXaxis().GetXmax()) mAlpha = 1.0 - float(targetMass-massLow)/float(massHigh-massLow) print 'alpha:',mAlpha, newIntegral = histLow.Integral() + \ (targetMass - massLow) * \ (histHigh.Integral()-histLow.Integral()) / \ (massHigh-massLow) print 'low integral:', histLow.Integral(), \ 'high integral:', histHigh.Integral(), \ 'new integral:', newIntegral newHistLow = RooDataHist("sigHistLow_hist", "sigHistLow_hist", RooArgList(x), histLow); sigHistLow = RooHistPdf("sigHistLow", "sigHistLow", RooArgList(x), RooArgList(x), newHistLow); newHistHigh = RooDataHist("sigHistHigh_hist", "sigHistHigh_hist", RooArgList(x), histHigh); sigHistHigh = RooHistPdf("sigHistHigh", "sigHistHigh", RooArgList(x), RooArgList(x), newHistHigh); #x.Print("v") x.setBins( histLow.GetNbinsX(), "cache") alpha_morph = RooRealVar("alpha_morph", "#alpha_{morph}", mAlpha, 0., 1.) alpha_morph.setBins(10,"cache") ; sigModel = RooIntegralMorph("sigModel", "sigModel", sigHistLow, sigHistHigh, x, alpha_morph) if (debug): from ROOT import gPad, RooFit frame = x.frame() sigHistLow.plotOn(frame, RooFit.LineColor(kRed+1), RooFit.LineStyle(2)) sigHistHigh.plotOn(frame, RooFit.LineColor(kBlue+1), RooFit.LineStyle(2)) sigModel.plotOn(frame, RooFit.LineColor(kViolet+1), RooFit.LineStyle(9)) frame.Draw() gPad.Update() gPad.WaitPrimitive() morphHist = sigModel.createHistogram(re.sub(r'\d+', '%i' % targetMass, hist1.GetName()), x, RooFit.Binning(histLow.GetNbinsX())) morphHist.Scale(newIntegral/morphHist.Integral()) morphHist.SetName(re.sub(r'\d+', '%i' % targetMass, hist1.GetName())) # if debug: # morphHist.Print() return morphHist
## Find the mode of the tmodel. mmgMode.setVal(modelHist.GetBinCenter(modelHist.GetMaximumBin())) mmgMode.setConstant(True) fPho.setConstant(True) ## Fit the photon scale phoScale.setConstant(False) mmgScale.setConstant(True) ## Make plots canvases.next('nominal') mmgFrame = mmgMass.frame(Range(60,120)) mmgData.plotOn(mmgFrame) phoScale.setVal(0) model.plotOn(mmgFrame) tmodel.plotOn(mmgFrame, LineStyle(kDashed), LineColor(kRed)) mmgFrame.Draw() ## Get the test datasets and models dataCollection = [] models = [] sFitted = [] sFittedErr = [] for i, (fac, s) in enumerate(zip(fTest, sTest)): mmgMass.SetTitle('scaledMmgMass3(%f, mmgMass, mmMass)' % fac) phoPtRangeMod = (phoPtRange[0] * fac, phoPtRange[1] * fac) cutsMod = cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRangeMod] data = dataset.get(variable=mmgMass, cuts=cutsMod) ## Import the data in the workspace data.SetName('data%d' % i) w.Import(data)