def makeRatioPlot(hNum, hDen, hDen2="", nameNum="num", nameDen="den", nameDen2="", xtitle="pt",ytitle="Entries", ratiotitle="Ratio", norm=False, log=True, plotName="ratio", outDir='out'): TH1.SetDefaultSumw2() # prepare settings of histos hNum.SetLineColor(kBlack) hNum.SetLineWidth(2) hNum.SetMarkerStyle(20) #hNum.SetMarkerStyle(1) hNum.SetMarkerColor(kBlack) hNum.GetYaxis().SetTitle(ytitle) hDen.SetLineColor(kRed+1) hDen.SetMarkerColor(kRed+1) hDen.SetLineWidth(2) hDen.SetMarkerStyle(21) #hDen.SetMarkerStyle(1) if nameDen2 != "": hDen2.SetLineColor(kBlue) hDen2.SetMarkerColor(kBlue) hDen2.SetLineWidth(2) hDen2.SetMarkerStyle(22) #hDen2.SetMarkerStyle(1) makeHistSettings(hDen2)# makeHistSettings(hNum) makeHistSettings(hDen) # prepare canva canvas=TCanvas(plotName, plotName, 600, 600) ROOT.SetOwnership(canvas, False) # Crucial to avoid crashes due to the way python deletes the objects canvas.cd() yMinP1=0.305; bottomMarginP1=0.005; pad1 = TPad('pad1','pad1',0,yMinP1,0.99,1) if log: pad1.SetLogy() pad1.SetBottomMargin(bottomMarginP1) pad1.SetFillColor(kWhite) pad1.SetTickx() pad1.SetTicky() pad2 = TPad('pad2','pad2',0.,0.01,.99,0.300) pad2.SetTopMargin(0.010) pad2.SetBottomMargin(0.40) pad2.SetFillColor(kWhite) pad2.SetGridy() pad1.SetNumber(1) pad2.SetNumber(2) pad1.Draw() pad2.Draw() # prepare legend leg = TLegend(0.75,0.68,0.82,0.88,'') leg.SetBorderSize(0) leg.SetTextSize(0.05) # Draw pad1.cd() histo_saver = [] #hNumNorm = hNum.Clone() if norm: hNumNorm = hNum.DrawNormalized('LP') histo_saver.append(hNumNorm) else: hNum.Draw('PE') if log: hNum.SetMaximum(hNum.GetMaximum()*4) if norm: hNumNorm.SetMaximum(hNumNorm.GetMaximum()*4) else: hNum.SetMaximum(hNum.GetMaximum()*2) if norm: hNumNorm.SetMaximum(hNumNorm.GetMaximum()*2) #leg.Draw('same') #hDenNorm = hDen.Clone() if norm: hDenNorm = hDen.DrawNormalized('samePE') histo_saver.append(hDenNorm) else: hDen.Draw('samePE') #hDenNorm2 = hDen2.Clone() if nameDen2 != "": if norm: hDenNorm2 = hDen2.DrawNormalized('samePE') histo_saver.append(hDenNorm2) else: hDen2.Draw('samePE') leg.AddEntry(hDen2, nameDen2, 'PE') leg.AddEntry(hDen, nameDen, 'PE') leg.AddEntry(hNum, nameNum, 'PE') leg.Draw('same') #print hNumNorm.Integral(), hDenNorm.Integral(), hDenNorm2.Integral() #print hNum.Integral(), hDen.Integral(), hDen2.Integral() ####################################################### ### RATIO PAD ####################################################### pad2.cd() hRatio = hNum.Clone() if nameDen2 != "": hRatio2 = hNum.Clone() if norm: hRatio = hNumNorm.Clone() hRatio2 = hNumNorm.Clone() #print 'Ratio integral before division' #print hRatio.Integral(), hRatio2.Integral() hRatio.Divide(hDenNorm) if nameDen2 != "": hRatio2.Divide(hDenNorm2) #print 'Ratio integral after division' #print hRatio.Integral(), hRatio2.Integral() else: hRatio.Divide(hDen) if nameDen2 != "": hRatio2.Divide(hDen2) #hRatio.SetLineColor(kRed+2) if nameDen2 != "": hRatio2.SetLineColor(kBlue) #print hRatio.Integral() makeRatioSettings(hRatio) if nameDen2 != "": makeRatioSettings(hRatio2) hRatio.GetXaxis().SetTitle(xtitle) hRatio.GetYaxis().SetTitle(ratiotitle) hRatio.SetTitle('') hRatio.Draw('PE') if nameDen2 != "": hRatio2.Draw('PEsame') #hRatio.GetXaxis().SetRangeUser(200.,2000.) canvas.SaveAs('{d}/{name}.pdf'.format(d=outDir, name = plotName)) canvas.SaveAs('{d}/{name}.png'.format(d=outDir, name = plotName))
hs_keras_bkg.Add(keras_others) scale2 = keras_data.Integral() / keras_sig.Integral() keras_sig.Scale(scale2) keras_sig.SetLineColor(8) keras_sig.SetLineWidth(3) keras_sig_gen.Scale(scale2) keras_sig_gen.SetLineColor(9) keras_sig_gen.SetLineWidth(3) ######################################## c1 = TCanvas('c1', 'c1', 450, 450) pad1 = TPad("pad1", "pad1", 0.0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.02) pad1.SetLeftMargin(0.12) pad1.Draw() c1.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0.0, 0.0, 1, 0.28) pad2.SetBottomMargin(0.3) pad2.SetTopMargin(0.02) pad2.SetLeftMargin(0.12) pad2.SetGridx() pad2.SetGridy() pad2.Draw() l = TLegend(0.15, 0.77, 0.89, 0.87) l.SetNColumns(5) l.SetTextFont(62) l.SetTextSize(0.05) l.SetLineColor(0) l.SetFillColor(0)
t.DrawText( 2, 18.3, 'Previous typed lines can be recalled.' ) t.SetTextFont( 72 ) t.SetTextSize( 0.026 ) t.DrawText( 3, 17, r'>>> x, y = 5, 7' ) t.DrawText( 3, 16, r'>>> import math; x*math.sqrt(y)' ) t.DrawText( 3, 14, r'>>> for i in range(2,7): print "sqrt(%d) = %f" % (i,math.sqrt(i))' ) t.DrawText( 3, 10, r'>>> import ROOT; f1 = ROOT.TF1( "f1", "sin(x)/x", 0, 10 )' ) t.DrawText( 3, 9, r'>>> f1.Draw()' ) t.SetTextFont( 81 ) t.SetTextSize( 0.018 ) t.DrawText( 4, 15, '13.228756555322953' ) t.DrawText( 4, 13.3, 'sqrt(2) = 1.414214' ) t.DrawText( 4, 12.7, 'sqrt(3) = 1.732051' ) t.DrawText( 4, 12.1, 'sqrt(4) = 2.000000' ) t.DrawText( 4, 11.5, 'sqrt(5) = 2.236068' ) t.DrawText( 4, 10.9, 'sqrt(6) = 2.449490' ) pad = TPad( 'pad', 'pad', .2, .05, .8, .35 ) pad.SetFillColor( 42 ) pad.SetFrameFillColor( 33 ) pad.SetBorderSize( 10 ) pad.Draw() pad.cd() pad.SetGrid() f1 = TF1( 'f1', 'sin(x)/x', 0, 10 ) f1.Draw() nut.cd() nut.Update()
histo_data = tfile.Get( '{chan}/data/NOMINAL/{chan}_data_NOMINAL_{distr}'.format(chan=args.channel, distr=args.distr)) ## don't #set mc errors = 0 for bini in range(histo_mc_sum.GetSize()): histo_mc_sum.SetBinError(bini, 0.) #from plotting_root import rgb, nick_colour cst = TCanvas("cst", "stacked hists", 10, 10, 700, 700) pad1 = TPad("pad1", "This is pad1", 0., 0., 1., 1.) pad1.Draw() pad1.cd() histo_data.Divide(histo_mc_sum) histo_mc_sum.Divide(histo_mc_sum) histo_mc_sum.Draw() histo_data.Draw("same") cst.SaveAs('./prefit-bin-significance_{chan}_{sys}_{distr}.png'.format( chan=args.channel, sys=args.systematic, distr=args.distr)) # calc chi2 in the normalized data chi2 = 0 nbins = 0
def drawHisto(histlist,histoD,xTitle,yTitle,outName,uncHists=""): legend = TLegend(0.35, 0.72, 0.85, 0.92,"") #,"brNDC" legend.SetFillStyle(0) legend.SetTextSize(0.045) legend.SetNColumns(2) myStack = THStack("myStack","") for hist in histlist: myStack.Add(hist,"hist") histoErr = histlist[0].Clone() for iHist in range(1,len(histlist)): histoErr.Add(histlist[iHist]) MCCount = myStack.GetStack().Last().Integral() DataCount = histoD.Integral() MCNormFactor = DataCount/MCCount # myStack.Delete() myStack = THStack("myStack","") for hist in histlist: hist.Scale(MCNormFactor) myStack.Add(hist,"hist") histoErr.Scale(MCNormFactor) if uncHists!="": MCMean = myStack.GetStack().Last().Clone() MCErr = MCMean.Clone() MCErr.Reset() for ibin in range(1,MCMean.GetNbinsX()+1): thisbinunc = 0 for ihist in uncHists: thisbinunc += ihist.GetBinContent(ibin)**2 #sum assuming correlated sfunc = thisbinunc**0.5*MCNormFactor if args.nostat: MCMean.SetBinError(ibin, sfunc) MCErr.SetBinContent(ibin, sfunc) else: MCMean.SetBinError(ibin, math.sqrt(sfunc**2 + histoErr.GetBinError(ibin)**2)) MCErr.SetBinContent(ibin, math.sqrt(sfunc**2 + histoErr.GetBinError(ibin)**2)) c = TCanvas("main","main",1200,1200) c.SetCanvasSize(1200,1200) upperCanvas = TPad("up","up",0,0.24,1,1) upperCanvas.SetBottomMargin(0.03) upperCanvas.SetLeftMargin(0.12) upperCanvas.SetTopMargin(0.06) # upperCanvas.SetLogy(isLog) upperCanvas.Draw() upperCanvas.cd() myStack.Draw() myStack.GetYaxis().SetTitle(yTitle) myStack.GetHistogram().GetZaxis().SetTitle() myStack.GetYaxis().SetLabelSize(0.048) myStack.GetYaxis().SetTitleSize(0.07) myStack.GetYaxis().SetTitleOffset(0.78) myStack.GetYaxis().SetTitleFont(42) legend.Draw("same") if uncHists!="": MCMean.Draw("e2 same") MCMean.SetFillColor(kGreen) MCMean.SetLineColor(kGreen) MCMean.SetMarkerSize(0) MCMean.SetFillStyle(3013) if not args.nostat: histoErr.Draw("e2 same") # histoErr.Sumw2() histoErr.SetFillColor(kGray+3) histoErr.SetLineColor(kGray+3) histoErr.SetMarkerSize(0) histoErr.SetFillStyle(3013) histoMC = myStack.GetStack().Last() histoBkg= myStack.GetStack().Before(histoMC) print "Total MC:", histoMC.Integral(), ", Data:",histoD.Integral() histoD.Draw("same p e") legend.AddEntry(histoD,"Data","PE") for hist in histlist: legend.AddEntry(hist,hist.GetName().replace('uds','udsg').replace('b','bottom').replace('c','charm'),'f') legend.AddEntry(histoErr,"MC Stat. Unc.",'f') if uncHists!="": legend.AddEntry(MCMean,"SF Unc.",'f') maxY = histoD.GetMaximum() #if myStack.GetMinimum() >= 0: myStack.SetMinimum(1e-3) myStack.SetMaximum(maxY*1.35) c.cd() lowerCanvas = TPad("down","down",0,0,1,0.26) lowerCanvas.Draw() lowerCanvas.cd() lowerCanvas.SetTicky(1) lowerCanvas.SetLeftMargin(0.1) lowerCanvas.SetRightMargin(0.1) lowerCanvas.SetTopMargin(0.0) lowerCanvas.SetBottomMargin(0.4) lowerCanvas.SetLeftMargin(0.12) lowerCanvas.SetFrameFillStyle(0) lowerCanvas.SetFrameBorderMode(0) lowerCanvas.SetGridy() histoRatio = histoD.Clone() histoRatio.Divide(histoMC) for ib in range(1,histoRatio.GetNbinsX()+1): if histoD.GetBinContent(ib) != 0: histoRatio.SetBinError(ib, histoD.GetBinError(ib)/histoD.GetBinContent(ib)*histoRatio.GetBinContent(ib)) else: histoRatio.SetBinError(ib,0.) histoRatio.GetYaxis().SetTitle("Data/MC") histoRatio.GetYaxis().SetTitleSize(0.15) histoRatio.GetYaxis().SetTitleOffset(0.38) histoRatio.GetYaxis().SetTitleFont(42) histoRatio.GetYaxis().SetLabelSize(0.14) histoRatio.GetYaxis().CenterTitle() histoRatio.GetYaxis().SetLabelFont(42) histoRatio.GetYaxis().SetNdivisions(5) histoRatio.GetXaxis().SetTitle(xTitle) histoRatio.GetXaxis().SetLabelSize(0.14) histoRatio.GetXaxis().SetTitleSize(0.19) histoRatio.GetXaxis().SetTitleOffset(0.88) histoRatio.GetXaxis().SetTitleFont(42) histoRatio.GetXaxis().SetTickLength(0.07) histoRatio.GetXaxis().SetLabelFont(42) histoRatio.SetTitle("") histoRatio.Draw("P e") histoRatio.SetMaximum(1.49) histoRatio.SetMinimum(0.51) if uncHists!="": RatioErr = MCErr.Clone() RatioErr.Divide(histoMC) RatioErrVals = RatioErr.Clone() for ibin in range(1,RatioErr.GetNbinsX()+1): RatioErrVals.SetBinContent(ibin,1.) RatioErrVals.SetBinError(ibin,RatioErr.GetBinContent(ibin)) RatioErrVals.Draw("e2 same") RatioErrVals.SetFillColor(kGreen) RatioErrVals.SetLineColor(kGreen) RatioErrVals.SetMarkerSize(0) RatioErrVals.SetFillStyle(3013) if not args.nostat: RatioStatUnc = histoMC.Clone() for ibin in range(1,RatioStatUnc.GetNbinsX()+1): RatioStatUnc.SetBinContent(ibin,1) if histoMC.GetBinContent(ibin) != 0: RatioStatUnc.SetBinError(ibin,histoMC.GetBinError(ibin)/histoMC.GetBinContent(ibin)) else: RatioStatUnc.SetBinError(ibin,0) RatioStatUnc.Draw("e2 same") RatioStatUnc.SetFillColor(kGray+3) RatioStatUnc.SetLineColor(kGray+3) RatioStatUnc.SetMarkerSize(0) RatioStatUnc.SetFillStyle(3013) histoRatio.Draw("P e same") # To bring on top hLine = TLine(-0.2,1,1,1) hLine.SetLineColor(kRed) hLine.Draw() # if drawDataMCRatioLine: # MCCount = histoMC.Integral() # if MCCount > 0.: # DataCount = histoD.Integral() # MCNormFactor = DataCount/MCCount # hLine2 = TLine(start,MCNormFactor,end,MCNormFactor) # hLine2.SetLineColor(kBlue) # hLine2.Draw() # ---------------------------------------------------------- # ======================== LaTeX ========================== texTL = TLatex() texTL.SetTextSize(0.07) texTL.SetTextAlign(13) texTR = TLatex() texTR.SetTextSize(0.05) texTR.SetTextAlign(31) # if dataset=="" or noRatio: # texTL.DrawLatexNDC(0.13,0.87, "CMS #it{#bf{Preliminary}}") # texTR.DrawLatexNDC(0.89,0.91, "#bf{"+str(lumi/1000.)+" fb^{-1} (13 TeV)}") # else: upperCanvas.cd() texTL.DrawLatexNDC(0.16,0.92, "CMS") # #it{#bf{Preliminary}}") if args.prelim: texTL2 = TLatex() texTL2.SetTextSize(0.05) texTL2.SetTextAlign(13) suff = "#it{#bf{Preliminary}}" texTL2.DrawLatexNDC(0.16,0.85, suff) texTR.DrawLatexNDC(0.89,0.95, "#bf{"+str(lumi/1000.)+" fb^{-1} (13 TeV)}") # ---------------------------------------------------------- c.SaveAs(outName+".pdf") c.SaveAs(outName+".png")
def calcAndDrawSignificance(SignalHist, BkgrHist, xtitle, legendNames, DataName, destination, ylog=False, customLabels=None, extraText=None, scaleSignalToBkgr=False, DivideByLine=None): GeneralSettings() #Make sure the code works for single backgrounds if not isinstance(BkgrHist, (list, )): BkgrHist = [BkgrHist] if not isinstance(SignalHist, (list, )): SignalHist = [SignalHist] BkgrHist, legendNames = orderHist(BkgrHist, legendNames) #Add all backgrounds totBkgr = BkgrHist[0].Clone("TotBkgr") for h in BkgrHist[1:]: totBkgr.Add(h) #Normalize signal to background if needed if scaleSignalToBkgr: for h in SignalHist: h.scale(totBkgr.GetSumOfWeights() / h.GetSumOfWeights) #Define a canvas Canv = TCanvas("Canv" + destination, "Canv" + destination, 1500, 1000) #Set Histogram Styles for h, n in zip(BkgrHist, legendNames): h.SetFillColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) h.SetLineColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) for i, h in enumerate(SignalHist): h.SetMarkerColor(TColor.GetColor(GetLineColor(i))) h.SetLineColor(TColor.GetColor(GetLineColor(i))) h.SetMarkerStyle(GetMarker(i)) list_of_significance_hists = [] for i, sh in enumerate(SignalHist): #Calculate significance total = totBkgr.Clone("Total") total.Add(sh) sqrt_total = total.Clone('Sqrt_Total') for xbin in xrange( 1, total.GetSize() - 1 ): #GetSize returns nbins + 2 (for overflow and underflow bin) sqrt_x = np.sqrt(total.GetBinContent(xbin)) sqrt_total.SetBinContent(xbin, sqrt_x) sqrt_total.SetBinError(xbin, 0.5 * total.GetBinError(xbin) / sqrt_x) significance = sh.Clone('Signal' + str(i)) significance.Divide(sqrt_total) list_of_significance_hists.append(significance) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in BkgrHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) #hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(BkgrHist + SignalHist, True) overallMax = GetOverallMaximum([totBkgr] + SignalHist) if ylog: if overallMin == 0.: overallMin = 0.1 ymin = 0.3 * overallMin ymax = 30 * overallMax plotpad.SetLogy() else: ymin = 0.7 * overallMin ymax = 1.3 * overallMax hs.SetMinimum(ymin) hs.SetMaximum(ymax) for h in SignalHist: h.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(BkgrHist, legendNames): legend.AddEntry(h, n) for h, n in zip(SignalHist, DataName): legend.AddEntry(h, n) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Draw lines if needed if DivideByLine is not None: tdrStyle_Left_Margin = 0.16 tdrStyle_Right_Margin = 0.02 plot_size_hor = 1 - tdrStyle_Left_Margin - tdrStyle_Right_Margin #Option one, user provides the number of divisions and we divide equally if isinstance(DivideByLine[0], int): x_pos = np.linspace(totBkgr.GetXaxis().GetXmin(), totBkgr.GetXaxis().GetXmax(), DivideByLine[0] + 1) #Option two, user provides the specific boundaries if isinstance(DivideByLine[0], (list, )): x_pos = DivideByLine[0] #Draw the lines lines = [] for i, x in enumerate(x_pos[1:-1]): lines.append(TLine(x, ymin, x, ymax)) lines[i].SetLineColor(ROOT.kRed) lines[i].SetLineStyle(10) for line in lines: line.Draw('same') #Add extra text for i, name in enumerate(DivideByLine[1]): x = ((x_pos[i + 1] + x_pos[i]) / (2 * (x_pos[-1] - x_pos[0]) / plot_size_hor)) + tdrStyle_Left_Margin extraText.append(extraTextFormat(name, x, 0.1, None, 22)) #Draw extra text if needed if extraText is not None: DrawExtraText(plotpad, extraText) #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #print list_of_significance_hists[0].GetMaximum(), list_of_significance_hists[1].GetMaximum(), list_of_significance_hists[2].GetMaximum() overallMin = GetOverallMinimum(list_of_significance_hists) overallMax = GetOverallMaximum(list_of_significance_hists) significance = list_of_significance_hists[0] #Prepare lines before changing maximum lines_bottom = [] for i, sig in enumerate(list_of_significance_hists): lines_bottom.append( TLine(sig.GetXaxis().GetXmin(), sig.GetMaximum(), sig.GetXaxis().GetXmax(), sig.GetMaximum())) lines_bottom[i].SetLineColor(TColor.GetColor(GetLineColor(i))) lines_bottom[i].SetLineStyle(3) #Set Style for bottom plot significance.SetTitle(";" + xtitle + "; S/#sqrt{S+B}") significance.GetXaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleOffset(.6) significance.GetXaxis().SetLabelSize(.12) significance.GetYaxis().SetLabelSize(.12) significance.SetMinimum(0.) significance.SetMaximum(1.3 * overallMax) significance.Draw("EP") for sig in list_of_significance_hists[1:]: sig.Draw('EPSame') for line in lines_bottom: line.Draw("same") #Set custom x labels xaxis = significance.GetXaxis() if customLabels != None: number_of_bins = significance.GetNbinsX() if number_of_bins != len(customLabels): if DivideByLine is not None: for i in range(number_of_bins): xaxis.SetBinLabel( i + 1, customLabels[i % len(customLabels)] ) #Only works when DivideByLine[0] is an integer else: print 'Please provide ' + str( number_of_bins) + ' labels instead of ' + str( len(customLabels)) return else: for i, label in zip(range(number_of_bins), customLabels): xaxis.SetBinLabel(i + 1, label) #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, 'Simulation Preliminary', True) #Save everything savePlots(Canv, destination) ROOT.SetOwnership( Canv, False ) #https://root-forum.cern.ch/t/tlatex-crashing-in-pyroot-after-many-uses/21638/4 return
def plotClosure(observed, predicted, xtitle, ytitle, DataName, additionalInfo, destination, yLog=False): GeneralSettings() Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) observed.SetMarkerColor(ROOT.kBlack) observed.SetLineColor(ROOT.kBlack) observed.SetMarkerStyle(20) predicted.SetFillColor(TColor.GetColor('#3399ff')) predicted.SetLineColor(TColor.GetColor('#3399ff')) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() predicted.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; " + ytitle + " / " + str( predicted.GetBinWidth(1)) + ' ' + getUnit(xtitle) predicted.SetTitle(title) predicted.GetXaxis().SetLabelOffset(9999999) #Set range overallMin = GetOverallMinimum([observed, predicted], yLog) overallMax = GetOverallMaximum([observed, predicted]) if yLog: plotpad.SetLogy() predicted.SetMinimum(0.3 * overallMin) predicted.SetMaximum(10 * overallMax) else: predicted.SetMinimum(0.5 * overallMin) predicted.SetMaximum(1.2 * overallMax) observed.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) legend.AddEntry(observed, DataName + ' (observed)') legend.AddEntry(predicted, DataName + ' (predicted)') legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Draw extra text DrawExtraText(plotpad, additionalInfo) #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() ratio = observed.Clone('ratio') ratio.Divide(predicted) #Set Style for bottom plot ratio.SetTitle(";" + xtitle + "; Obs./pred.") ratio.GetXaxis().SetTitleSize(.12) ratio.GetYaxis().SetTitleSize(.12) ratio.GetYaxis().SetTitleOffset(.6) ratio.GetXaxis().SetLabelSize(.12) ratio.GetYaxis().SetLabelSize(.12) ratio.SetMinimum(0.5) ratio.SetMaximum(1.5) ratio.Draw("EP") #Draw a guide for the eye line = TLine(ratio.GetXaxis().GetXmin(), 1, ratio.GetXaxis().GetXmax(), 1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(1) line.SetLineStyle(1) line.Draw("Same") #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, 'Preliminary', True) #Save everything savePlots(Canv, destination)
def plotDataVSMC(DataHist, MCHist, xtitle, legendNames, DataName, destination, ytitle_bottom='Data/MC'): GeneralSettings() Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) #Set Histogram Styles for i, h in enumerate(MCHist): h.SetFillColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) h.SetLineColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) DataHist.SetMarkerColor(ROOT.kBlack) DataHist.SetLineColor(ROOT.kBlack) DataHist.SetMarkerStyle(20) #Add all MC samples to use in ratios totBkgr = MCHist[0].Clone("totBkgr") for h in MCHist[1:]: totBkgr.Add(h) DataOverMC = DataHist.Clone("DataOverMC") DataOverMC.Divide(totBkgr) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in MCHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events / " + str(MCHist[0].GetBinWidth(1)) + " GeV" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(MCHist + [DataHist]) overallMax = GetOverallMaximum([totBkgr] + [DataHist]) hs.SetMinimum(0.5 * overallMin) hs.SetMaximum(1.2 * overallMax) DataHist.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(MCHist, legendNames): legend.AddEntry(h, n) legend.AddEntry(DataHist, DataName) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #Set Style for bottom plot DataOverMC.SetTitle(";" + xtitle + "; " + ytitle_bottom) DataOverMC.GetXaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleOffset(.6) DataOverMC.GetXaxis().SetLabelSize(.12) DataOverMC.GetYaxis().SetLabelSize(.12) DataOverMC.SetMinimum(0.6) DataOverMC.SetMaximum(1.4) DataOverMC.Draw("EP") #Draw a guide for the eye line = TLine(DataOverMC.GetXaxis().GetXmin(), 1, DataOverMC.GetXaxis().GetXmax(), 1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(1) line.SetLineStyle(1) line.Draw("Same") #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, 'Preliminary', True) print 'save' #Save everything savePlots(Canv, destination) print 'saved'
def DrawOverlap(fileVec, histVec, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1]): gStyle.SetOptTitle(0) gStyle.SetOptStat(0) gStyle.SetTitleOffset(1.1, "Y") gStyle.SetTitleOffset(0.9, "X") gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) i = 0 histList_ = [] histList = [] histList1 = [] maximum = [] ## Legend leg = TLegend(0.1, 0.70, 0.89, 0.89) #,NULL,"brNDC"); leg.SetBorderSize(0) leg.SetNColumns(3) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(22) leg.SetTextSize(0.035) c = TCanvas("c1", "c1", 0, 0, 500, 500) #c.SetBottomMargin(0.15) #c.SetLeftMargin(0.15) #c.SetLogy(0) #c.SetLogx(0) c1_2 = TPad("c1_2", "newpad", 0.04, 0.13, 1, 0.994) c1_2.Draw() print("you have provided " + str(len(fileVec)) + " files and " + str(len(histVec)) + " histograms to make a overlapping plot") print "opening rootfiles" c.cd() c1_2.SetBottomMargin(0.013) c1_2.SetLogy(logstatus[1]) c1_2.SetLogx(logstatus[0]) c1_2.cd() ii = 0 inputfile = {} print str(fileVec[(len(fileVec) - 1)]) for ifile_ in range(len(fileVec)): print("opening file " + fileVec[ifile_]) inputfile[ifile_] = TFile(fileVec[ifile_]) print "fetching histograms" for ihisto_ in range(len(histVec)): print("printing histo " + str(histVec[ihisto_])) histo = inputfile[ifile_].Get(histVec[ihisto_]) #status_ = type(histo) is TGraphAsymmErrors histList.append(histo) # for ratio plot as they should nt be normalize histList1.append(histo) #print histList[ii].Integral() #histList[ii].Rebin(xRange[2]) histList[ii].Scale(1.0 / histList[ii].Integral()) maximum.append(histList[ii].GetMaximum()) maximum.sort() ii = ii + 1 print histList for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(100) #1.4 for log histList[ih].SetMinimum(0.01) #1.4 for log if logstatus[1] is 0: histList[ih].SetMaximum(1.4) #1.4 for log histList[ih].SetMinimum(0.001) #1.4 for log # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if tt is TGraphAsymmErrors: histList[ih].Draw("APL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist") if ih > 0: #histList[ih].SetLineWidth(2) if tt is TGraphAsymmErrors: histList[ih].Draw("PL same") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("hist same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(100) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetMarkerStyle(markerStyle[ih]) histList[ih].SetMarkerSize(1) leg.AddEntry(histList[ih], legendtext[ih], "PL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(3) leg.AddEntry(histList[ih], legendtext[ih], "L") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(0.88) histList[ih].GetYaxis().SetTitleFont(22) histList[ih].GetYaxis().SetLabelFont(22) histList[ih].GetYaxis().SetLabelSize(.052) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) histList[ih].GetXaxis().SetLabelSize(0.0000) histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) histList[ih].GetXaxis().SetTitleOffset(1.04) histList[ih].GetXaxis().SetTitleFont(22) histList[ih].GetXaxis().SetTickLength(0.07) histList[ih].GetXaxis().SetLabelFont(22) histList[ih].GetYaxis().SetLabelFont(22) histList[ih].GetXaxis().SetNdivisions(508) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); i = i + 1 pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(22) pt.SetTextSize(0.046) text = pt.AddText(0.2, 0.5, "CMS Internal") text = pt.AddText(0.65, 0.5, "#sqrt{s} = 13 TeV(2016) ") pt.Draw() # t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC") # t2a.SetBorderSize(0) # t2a.SetFillStyle(0) # t2a.SetTextSize(0.040) # t2a.SetTextAlign(12) # t2a.SetTextFont(62) # histolabel1= str(fileVec[(len(fileVec)-1)]) # text1 = t2a.AddText(0.06,0.5,"CMS Internal") # t2a.Draw() leg.Draw() # # c.cd() outputdirname = 'plots/' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
def report(): global freed_file print ' HeapMonReport.report(): heapmon_file=', freed_file #findStaticHoles() tfile = TFile(freed_file, "READ") print " root compression factor = ", tfile.GetCompressionFactor() mem_canvas = TCanvas("HeapMon_report", "Memory Holes Statistics", 10, 10, 800, 1034) mem_canvas.SetFillColor(17) mem_canvas.cd() pad1 = TPad("pad1", "pad1", 0.01, 0.57, 0.50, 0.93, 33) pad2 = TPad("pad2", "pad2", 0.51, 0.57, 0.99, 0.93, 33) pad3 = TPad("pad3", "pad3", 0.01, 0.01, 0.99, 0.50, 33) pad3.SetPhi(210) pad3.SetTheta(25) pad1.Draw() pad2.Draw() pad3.Draw() memTree = tfile.Get("holeTree") infoTree = tfile.Get("infoTree") mallocTree = tfile.Get("mallocTree") #holesm_th1i = TH1I('holesm_th1i', 'Holes size evolution', fcount, 0, fcount) #holesn_th1i = TH1I('holesn_th1i', 'Holes number evolution', fcount, 0, fcount) #total_th1i = TH1I('total_th1i', 'Total memory size evolution', fcount, 0, fcount) max_hole_size = memTree.GetMaximum("hole_size") print " max_hole_size=", max_hole_size, " min_hole_size", memTree.GetMinimum( "hole_size") max_scan_number = memTree.GetMaximum("scan_number") print " max_scan_number=", max_scan_number memHist1 = TH2I("mem2d", "Hole-sizes distribution evolution", 128, -0.5, max_hole_size - 0.5, 50, 0, max_scan_number) memTree.Project("mem2d", "scan_number:hole_size") multiGraph1 = TMultiGraph() multiGraph2 = TMultiGraph() print " memHist.GetMaximum() = ", memHist1.GetMaximum() # Working on a Report gStyle.SetOptStat(0) gStyle.SetPalette(1) gStyle.SetCanvasColor(33) gStyle.SetFrameFillColor(18) memHist1.SetFillColor(30) memHist1.SetFillStyle(0) memHist1.GetXaxis().SetTitle("Size of holes, kb") memHist1.GetXaxis().SetLabelOffset(0.02) memHist1.GetXaxis().SetLabelSize(0.02) memHist1.GetXaxis().SetTitleSize(0.04) memHist1.GetXaxis().SetTitleColor(2) memHist1.GetYaxis().SetTitle("Event number") memHist1.GetYaxis().SetLabelSize(0.04) memHist1.GetXaxis().SetLabelOffset(0.04) memHist1.GetYaxis().SetTitleSize(0.04) memHist1.GetYaxis().SetTitleColor(2) memHist1.GetZaxis().SetTitle("Number of holes") memHist1.GetZaxis().SetLabelSize(0.02) memHist1.GetZaxis().SetTitleSize(0.04) memHist1.GetZaxis().SetTitleColor(2) title = TPaveLabel(0.1, 0.95, 0.9, 0.99, "Job Memory Usage Plots") title.SetFillColor(42) title.SetTextFont(42) title.Draw() text_box = TPaveText(0.1, 0.51, 0.9, 0.54) text_box.AddText("Malloc freed ('marked') Heap Memory Profile") text_box.SetFillColor(42) text_box.SetTextAlign(12) text_box.SetTextFont(42) text_box.Draw() x1 = 0.2 y1 = 0.91 x2 = 0.8 y2 = 0.98 #Drawing upper-left corner Pad1 of the report pad1.cd() pad1.SetGridx() pad1.SetGridy() infoTree.Draw("total_maps_memory:scan_number", "", "goff") mapsGraph = TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(), infoTree.GetV1()) mapsGraph.SetLineColor(1) mapsGraph.SetLineWidth(1) #mapsGraph.SetFillStyle(3001); mapsGraph.SetFillColor(2); mapsGraph.SetName("total_maps_memory") #VmSize, VmLck, VmRSS, VmData, VmStk, VmExe, VmLib; infoTree.Draw("VmSize:scan_number", "", "goff") vmsizeGraph = TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(), infoTree.GetV1()) vmsizeGraph.SetLineColor(2) vmsizeGraph.SetLineWidth(1) #vmsizeGraph.SetFillStyle(3002); vmsizeGraph.SetFillColor(3); vmsizeGraph.SetName("VmSize") infoTree.Draw("VmRSS:scan_number", "", "goff") vmrssGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmrssGraph.SetLineColor(3) vmrssGraph.SetLineWidth(1) #vmrssGraph.SetFillStyle(3003); vmrssGraph.SetFillColor(4); vmrssGraph.SetName("VmRSS") infoTree.Draw("VmData:scan_number", "", "goff") vmdataGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmdataGraph.SetLineColor(4) vmdataGraph.SetLineWidth(1) #vmdataGraph.SetFillStyle(3004); vmdataGraph.SetFillColor(4); vmdataGraph.SetName("VmData") infoTree.Draw("VmStk:scan_number", "", "goff") vmstkGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmstkGraph.SetLineColor(5) vmstkGraph.SetLineWidth(1) #vmstkGraph.SetFillStyle(3005); vmstkGraph.SetFillColor(4); vmstkGraph.SetName("VmStk") infoTree.Draw("VmExe:scan_number", "", "goff") vmexeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmexeGraph.SetLineColor(6) vmexeGraph.SetLineWidth(1) #vmexeGraph.SetFillStyle(3003); vmexeGraph.SetFillColor(4); vmexeGraph.SetName("VmExe") infoTree.Draw("VmLib:scan_number", "", "goff") vmlibGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmlibGraph.SetLineColor(7) vmlibGraph.SetLineWidth(1) #vmlibGraph.SetFillStyle(3003); vmlibGraph.SetFillColor(4); vmlibGraph.SetName("VmLib") infoTree.Draw("VmLck:scan_number", "", "goff") vmlckGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) vmlckGraph.SetLineColor(8) vmlckGraph.SetLineWidth(1) #vmlckGraph.SetFillStyle(3003); vmlckGraph.SetFillColor(4); vmlckGraph.SetName("VmLck") infoTree.Draw("total_hole_memory:scan_number", "", "goff") holeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) holeGraph.SetLineColor(9) holeGraph.SetLineWidth(1) #holeGraph.SetFillStyle(3004); holeGraph.SetFillColor(5); holeGraph.SetName("HolesSize") mallocTree.Draw("malloc_free:scan_number", "", "goff") freeGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1()) freeGraph.SetLineColor(11) freeGraph.SetLineWidth(1) freeGraph.SetFillStyle(3003) freeGraph.SetFillColor(4) freeGraph.SetName("malloc_free") mallocTree.Draw("malloc_inuse:scan_number", "", "goff") inuseGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1()) inuseGraph.SetLineColor(21) inuseGraph.SetLineWidth(1) inuseGraph.SetFillStyle(3003) inuseGraph.SetFillColor(4) inuseGraph.SetName("malloc_inuse") mallocTree.Draw("malloc_sbrk:scan_number", "", "goff") sbrkGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1()) sbrkGraph.SetLineColor(31) sbrkGraph.SetLineWidth(1) sbrkGraph.SetFillStyle(3003) sbrkGraph.SetFillColor(4) sbrkGraph.SetName("malloc_sbrk") mallocTree.Draw("malloc_mmap:scan_number", "", "goff") mmapGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1()) mmapGraph.SetLineColor(41) mmapGraph.SetLineWidth(1) mmapGraph.SetFillStyle(3003) mmapGraph.SetFillColor(4) mmapGraph.SetName("malloc_mmap") pad1.cd() multiGraph1.Add(mapsGraph) multiGraph1.Add(vmsizeGraph) multiGraph1.Add(vmrssGraph) multiGraph1.Add(vmdataGraph) multiGraph1.Add(vmlckGraph) multiGraph1.Add(vmexeGraph) multiGraph1.Add(vmstkGraph) #multiGraph1.Add(vmlibGraph); multiGraph1.Add(inuseGraph) multiGraph1.Add(sbrkGraph) multiGraph1.Add(mmapGraph) multiGraph1.Add(holeGraph) multiGraph1.Add(freeGraph) #multiGraph1.SetTitle("PROCESS VM and Malloc MEMORY USAGE"); title.DrawPaveLabel(x1, y1, x2, y2, "PROCESS VM and Malloc MEMORY USAGE", "brNDC") multiGraph1.Draw("ALg") hist = multiGraph1.GetHistogram() hist.SetXTitle("Event Number") hist.SetYTitle("Memory, kb") legend1 = TLegend(0.84, 0.20, 0.99, 0.90) legend1.AddEntry(mapsGraph, "Maps", "l") legend1.AddEntry(vmsizeGraph, "VmSize", "l") legend1.AddEntry(vmrssGraph, "VmRSS", "l") legend1.AddEntry(vmdataGraph, "VmData", "l") legend1.AddEntry(sbrkGraph, "MallocSbrk", "l") legend1.AddEntry(inuseGraph, "MallocInuse", "l") #legend1.AddEntry(vmlibGraph, "VmLib", "l"); legend1.AddEntry(mmapGraph, "MallocMmap", "l") legend1.AddEntry(freeGraph, "MallocFree", "l") legend1.AddEntry(holeGraph, "Freed-Holes", "l") legend1.AddEntry(vmstkGraph, "VmStk", "l") legend1.AddEntry(vmexeGraph, "VmExe", "l") legend1.AddEntry(vmlckGraph, "VmLck", "l") legend1.Draw() #multiGraph1.Draw("ALg") #title.DrawPaveLabel(x1,y1,x2,y2,"Process Memory Usage Charts","brNDC"); #Drawing upper-left corner Pad1 of the report pad2.cd() pad2.SetGridx() pad2.SetGridy() infoTree.Draw("total_hole_memory:scan_number", "", "goff") holeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1()) holeGraph.SetLineColor(9) holeGraph.SetLineWidth(1) holeGraph.SetFillStyle(3004) holeGraph.SetFillColor(5) holeGraph.SetName("total_hole_memory") mallocTree.Draw("malloc_free:scan_number", "", "goff") freeGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1()) freeGraph.SetLineColor(11) freeGraph.SetLineWidth(1) freeGraph.SetFillStyle(3004) freeGraph.SetFillColor(5) freeGraph.SetName("malloc_free") pad2.cd() multiGraph2.Add(holeGraph) multiGraph2.Add(freeGraph) #multiGraph2.Add(sbrkGraph); #multiGraph2.Add(mmapGraph); #multiGraph2.SetTitle("Free and Marked Holes Memory Graph"); title.DrawPaveLabel(x1, y1, x2, y2, "Malloc Free and Marked Holes Memory", "brNDC") multiGraph2.Draw("ALg") hist = multiGraph2.GetHistogram() hist.SetXTitle("Event Number") hist.SetYTitle("Memory, kb") legend2 = TLegend(0.9, 0.30, 0.99, 0.90) legend2.AddEntry(freeGraph, "Free", "l") legend2.AddEntry(holeGraph, "Holes", "l") #legend2.AddEntry(inuseGraph, "Inuse", "l"); #legend2.AddEntry(mmapGraph, "Mmap", "l"); #legend2.AddEntry(sbrkGraph, "Sbrk", "l"); legend2.Draw() #multiGraph2.Draw("ALg") #title.DrawPaveLabel(x1,y1,x2,y2,"Malloc Memory Usage and Deallocation Charts","brNDC"); #PAD3 pad3.cd() pad3.SetLogz() memHist1.Draw("lego2") #title.DrawPaveLabel(x1,y1,x2,y2,"TH2I-LEGO2","brNDC"); mem_canvas.SetBorderSize(1) #mem_canvas.Modified() mem_canvas.Update() mem_canvas.Print(".pdf") mem_canvas.Print(".C")