def main_singleCategory(options, args): if options.category in [30, 31]: print 'Error! Too few AF2 stats. Not going to do it.' return cans = [] options.outdir = '' if options.functions: flist = options.functions.split(',') options.outdir += '_'.join(flist) elif options.family == 'official': #flist = ['Exponential','ExpPoly2','ExpPoly3','Bern4','Bern5','Pow','Pow2','Laurent0','Laurent1','Laurent2'] flist = [ 'Exponential', 'ExpPoly2', 'Bern4', 'Bern5', 'Pow', 'Pow2', 'Laurent1', 'Laurent2' ] options.outdir += 'official_functions' elif options.family == 'selected': flist = [Tools.selected[Tools.categories[options.category]]] options.outdir += 'selected_functions' print flist elif options.family == 'ExpPoly': flist = ['Exponential'] + list('ExpPoly%d' % (d) for d in range(2, 4)) options.outdir += 'exppoly_family' elif options.family == 'Laurent': flist = list('Laurent%d' % (d) for d in range(0, 3)) options.outdir += 'Laurent_family' elif options.family == 'PolyOverX4': flist = ['1/x^4'] + list('poly%d/x^4' % (d) for d in range(1, 6)) options.outdir += 'PolyOverX4_family' elif options.family == 'Bernstein': flist = list('Bern%d' % (d) for d in range(4, 6)) options.outdir += 'Bern_family' elif options.family == 'PowerSum': flist = ['Pow', 'Pow2'] options.outdir += 'PowerSum_family' else: flist = [ 'Exponential', # bad 'ExpPoly2', 'ExpPoly3', ] options.outdir += '_'.join(flist) options.outdir += '_c%02d_%s' % (options.category, Tools.categories[options.category]) functions = [] Tools.PopulateFunctionList(functions, flist) Tools.LinkFunctionsForFtest(functions) if len(functions) == 0: print 'Error! no functions loaded!' import sys sys.exit() for f in functions: f.SetCategory(options.category) f.SetFileName(options.file) f.SetSignalWS(options.signalws) f.Initialize() ## ## Plot the data and af2 (fit bkg-only just before this.) SpuriousSignal_05_M17_ggH_1J_BSM ## for f in functions: f.function.fitTo(f.data, *(Tools.args_bkgonly)) cans.append( plotfunc.RatioCanvas( "TemplateFit_%02d_%s" % (options.category, Tools.categories[options.category]), "main plot", 600, 500)) functions[0].af2hist.SetMarkerSize(0) #rebin = Tools.RebinUntilSmallErrors(functions[0].af2hist,0,Tools.lower_range,Tools.upper_range,errormax=0.3) rebin = 5 functions[0].af2hist.Rebin(rebin) binwidth = functions[0].af2hist.GetBinWidth(1) bins = int((Tools.upper_range - Tools.lower_range) / float(binwidth)) functions[0].af2hist.SetTitle('#gamma#gamma MC') functions[0].af2hist.SetLineWidth(2) if options.family == 'selected': functions[0].af2hist.SetLineColor(ROOT.kGray + 2) functions[0].af2hist.SetFillColor(0) plotfunc.AddHistogram(cans[-1], functions[0].af2hist, drawopt='') for i, f in enumerate(functions): f.obsVar.setBins(int(bins)) f.bins = bins f.frame = f.obsVar.frame() if i: f.af2hist.Rebin(rebin) f.af2_rebinned = ROOT.RooDataHist('af2_rebinned', '', ROOT.RooArgList(f.obsVar), f.af2hist, 1.) #f.af2_rebinned.plotOn(f.frame,ROOT.RooFit.Range("lower,upper")) #f.function.plotOn(f.frame,ROOT.RooFit.NormRange("lower,upper"),ROOT.RooFit.Range("all")) f.chisquare = Tools.GetChiSquare_ForSpuriousSignal( f.frame, f.af2_rebinned, f.function, f.ndof) f.pvalue_chi2 = ROOT.TMath.Prob(f.chisquare * (f.bins - 1 - f.ndof), f.bins - 1 - f.ndof) print 'Original chi2: %2.6f p-value: %2.6f' % (f.chisquare, f.pvalue_chi2) f.minNll = 0 curve = f.frame.getCurve() curve.SetMarkerSize(0) curve.SetLineWidth(1) curve.SetTitle(f.name) curve.SetLineWidth(2) # resid = f.frame.residHist(); resid.SetMarkerSize(0) # plotfunc.AddRatioManual(cans[-1],curve,resid,drawopt1='l',drawopt2='l') pull = f.frame.pullHist() pull.SetMarkerSize(0.7) # for special if options.family == 'selected': color = { 'Pow': ROOT.kBlack + 0, 'Exponential': ROOT.kRed + 1, 'ExpPoly2': ROOT.kBlue + 1, 'Bern3': ROOT.kGreen + 1, 'Bern4': ROOT.kMagenta + 1, 'Bern5': ROOT.kOrange + 1, }.get(f.name) pull.SetMarkerColor(color) pull.SetLineColor(color) curve.SetLineColor(color) curve.SetFillColor(0) plotfunc.AddRatioManual(cans[-1], curve, pull, drawopt1='l', drawopt2='p') f.chisquare_toy = Tools.ChiSquareToys_ForSpuriousSignal( f, options.outdir) if not options.family == 'selected': plotfunc.SetColors(cans[-1]) plotfunc.FormatCanvasAxes(cans[-1]) plotfunc.SetXaxisRanges(cans[-1], Tools.lower_range, Tools.upper_range) plotfunc.SetAxisLabels(cans[-1], 'm_{#gamma#gamma} [GeV]', 'entries', 'pull') the_text = [ plotfunc.GetAtlasInternalText(), plotfunc.GetSqrtsText(13) + ', ' + plotfunc.GetLuminosityText(36.1), Tools.CategoryNames[Tools.categories[options.category]] ] plotfunc.DrawText(cans[-1], the_text, 0.19, 0.70, 0.59, 0.91, totalentries=3) plotfunc.MakeLegend(cans[-1], 0.60, 0.70, 0.90, 0.91, totalentries=3) #plotfunc.GetTopPad(cans[-1]).GetPrimitive('legend').AddEntry(0,'^{ }background-only fit','') #list(plotfunc.GetTopPad(cans[-1]).GetPrimitive('legend').GetListOfPrimitives())[-1].SetLabel('^{ }background-only fit') plotfunc.SetYaxisRanges(plotfunc.GetBotPad(cans[-1]), -4, 4) taxisfunc.AutoFixYaxis(plotfunc.GetTopPad(cans[-1]), ignorelegend=False, minzero=True) for can in cans[:-1]: plotfunc.FormatCanvasAxes(can) anaplot.UpdateCanvases(cans, options) if not options.batch: raw_input('Press enter to exit') anaplot.doSaving(options, cans) return
def main_singleCategory(options, args): if options.category in [19, 23]: # ggH_0J_Cen is 0 print 'Error! This category has been merged away.' return cans = [] options.outdir = '' if options.analysis == 'couplings2017': category_name = Tools.categories_couplings2017[options.category] category_title = Tools.CategoryNames_couplings2017[category_name] fcns['selected'] = [Tools.selected_couplings2017[category_name]] fcns['ftest'] = ChiSquareTools.ftest[category_name] background_label = '#gamma#gamma' lumi = 36.1 elif options.analysis == 'ysy': category_name = Tools.categories_ysy[options.category] category_title = Tools.CategoryNames_ysy[category_name] fcns['selected'] = [Tools.selected_ysy[category_name]] fcns['ftest'] = ChiSquareTools.ftest[category_name] background_label = 'll#gamma' lumi = 139 else: print('Error - do not understand analysis name %s' % (options.analysis)) import sys sys.exit() family_name = { 'official': 'official_functions', 'selected': 'selected_function', }.get(options.family, options.family + '_family') # A list of options is provided if options.functions: flist = options.functions.split(',') options.outdir += '_'.join(flist) # Otherwise a family must be provided: else: flist = fcns.get(options.family) options.outdir += family_name options.outdir += '_c%02d_%s' % (options.category, category_name) functions = [] FunctionsModule.PopulateFunctionList(functions, flist, options.lower, options.upper) ChiSquareTools.LinkFunctionsForFtest(functions) if len(functions) == 0: print 'Error! no functions loaded!' import sys sys.exit() for f in functions: f.SetAnalysis(options.analysis) f.SetCategory(options.category) f.SetFileName(options.file) f.Initialize() # rebin = 5 # if options.category > 16 : # rebin = 1 # if options.category > 23 : # ttH categories # rebin = 10 # Rebin to get 1 bin per GeV rebin = int(functions[0].datahist.GetNbinsX() / 55) print 'Proceeding with Data histogram:', functions[0].datahist functions[0].datahist.Rebin(rebin) for i, f in enumerate(functions): if i: f.datahist.Rebin(rebin) f.datasb_rebinned = ROOT.RooDataHist('data_real_rebinned', '', ROOT.RooArgList(f.obsVar), f.datahist, 1.) if not os.path.exists(options.outdir): os.makedirs(options.outdir) ftest_text = '' cans.append( plotfunc.RatioCanvas( "Ftests_%02d_%s" % (options.category, category_name), "main plot", 600, 500)) functions[0].datahist.SetBinErrorOption(ROOT.TH1.kPoisson) plotfunc.AddHistogram(cans[-1], functions[0].datahist) ## ## Ftests to sideband ## for f in functions: if not hasattr(f, 'ftest_function'): continue nbins_blind = int(f.datasb_rebinned.numEntries() - 10) print 'Sideband numEntries:', f.datasb_rebinned.numEntries( ), 'nbins:', nbins_blind # ndof_bins = nbins_blind-f.ndof-1 # ndof_bins_2 = nbins_blind-f.ftest_function.ndof-1 ndof_bins = nbins_blind - f.ndof ndof_bins_2 = nbins_blind - f.ftest_function.ndof # # Fitting data sidebands - first function # print 'Fitting data sidebands' print f.PrintParameters() ChiSquareTools.FitForChi2_DataSidebands(f) print f.PrintParameters() print 'Fitting data sidebands done' ftest_text += f.PrintParameters() + '\n' chi2 = ROOT.GetChiSquare(f.obsVar, f.function_ext, f.datasb_rebinned, ndof_bins) pvalue_chi2 = ROOT.TMath.Prob(chi2 * (ndof_bins), ndof_bins) # # Plotting stuff - first function # Tools.ClearRooPlot(f.frame) ChiSquareTools.NormalizeToSideband(f) f.datasb_rebinned.plotOn( f.frame, ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson)) print 'about to plot' #f.workspace.var('a1').setVal(-1.6) print f.PrintParameters() f.function_ext.plotOn(f.frame, *(Tools.plotOptions_sb_all)) print f.PrintParameters() print 'about to plot done' curve = f.frame.getCurve() curve.SetMarkerSize(0) curve.SetLineWidth(2) curve.SetTitle('%s, p(#chi^{2}) = %2.1f%%' % (f.name, pvalue_chi2 * 100.)) curve.SetLineColor(ROOT.kRed + 1) curve.SetFillColor(0) pull = f.frame.pullHist() pull.SetMarkerSize(0.7) pull.SetLineColor(ROOT.kRed + 1) pull.SetMarkerColor(ROOT.kRed + 1) plotfunc.AddRatioManual(cans[-1], curve, pull, drawopt1='l', drawopt2='p') # # Fitting data sidebands - first function # print 'Fitting data sidebands (other function)' print f.ftest_function.PrintParameters() ChiSquareTools.FitForChi2_DataSidebands(f.ftest_function) print f.ftest_function.PrintParameters() print 'Fitting data sidebands (other function) done' ftest_text += f.ftest_function.PrintParameters() + '\n' chi2_2 = ROOT.GetChiSquare(f.obsVar, f.ftest_function.function_ext, f.datasb_rebinned, ndof_bins_2) pvalue_chi2_2 = ROOT.TMath.Prob(chi2_2 * (ndof_bins_2), ndof_bins_2) # # Plotting stuff - other function # Tools.ClearRooPlot(f.frame) ChiSquareTools.NormalizeToSideband(f.ftest_function) f.datasb_rebinned.plotOn(f.frame) f.ftest_function.function_ext.plotOn(f.frame, *(Tools.plotOptions_sb_all)) curve = f.frame.getCurve() curve.SetMarkerSize(0) curve.SetLineWidth(2) curve.SetTitle('%s, p(#chi^{2}) = %2.1f%%' % (f.ftest_function.name, pvalue_chi2_2 * 100.)) curve.SetLineColor(ROOT.kAzure - 2) curve.SetFillColor(0) pull = f.frame.pullHist() pull.SetMarkerSize(0.7) pull.SetLineColor(ROOT.kAzure - 2) pull.SetMarkerColor(ROOT.kAzure - 2) plotfunc.AddRatioManual(cans[-1], curve, pull, drawopt1='l', drawopt2='p') ftest = ChiSquareTools.GetF(chi2, chi2_2, ndof_bins, ndof_bins_2) ftest_text += 'chi2/ndf: %2.5f\n' % (chi2) ftest_text += 'chi2_2/ndf: %2.5f\n' % (chi2_2) ftest_text += 'chi2: %2.5f\n' % (chi2 * ndof_bins) ftest_text += 'chi2_2: %2.5f\n' % (chi2_2 * ndof_bins_2) ftest_text += 'ftest: %2.5f\n' % (ftest) #p_ftest = 1.0 - ROOT.TMath.FDistI(ftest,1,ndof_bins_2) p_ftest = 1.0 - ROOT.TMath.FDistI(ftest, ndof_bins - ndof_bins_2, ndof_bins_2) ftest_text += 'p_ftest: %2.5f\n' % (p_ftest) # # Throw Toys # print 'Running toy Ftests' fisher_dist = ChiSquareTools.ToyFtest(f, f.ftest_function, ftest, options.outdir, options.ntoys) print 'Running toy Ftests done' if fisher_dist.Integral(0, 100000): ftest_text += 'p_ftest_toys: %2.5f\n' % ( fisher_dist.Integral(fisher_dist.FindBin(ftest), 100000) / float(fisher_dist.Integral(0, 100000))) # chi2_lowerSideBand = ROOT.RooChi2Var("chi2_low","chi2_low",f.function_ext,f.data_realdata,ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson),ROOT.RooFit.Range("lower")); # chi2_upperSideBand = ROOT.RooChi2Var("chi2_upp","chi2_upp",f.function_ext,f.data_realdata,ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson),ROOT.RooFit.Range("upper")); # chi2_all = ROOT.RooChi2Var("chi2_all","chi2_all",f.function_ext,f.data_realdata,ROOT.RooFit.Range("lower,upper")); # chi2_lowerSideBand = ROOT.RooChi2Var("chi2_low","chi2_low",f.function_ext,f.data_realdata,ROOT.RooFit.Range("lower")); # chi2_upperSideBand = ROOT.RooChi2Var("chi2_upp","chi2_upp",f.function_ext,f.data_realdata,ROOT.RooFit.Range("upper")); # print 'chi2_all .getValV()',chi2_all.getValV() # print 'chi2_lowerSideBand.getValV()',chi2_lowerSideBand.getValV() # print 'chi2_upperSideBand.getValV()',chi2_upperSideBand.getValV() # print 'total:',(chi2_lowerSideBand.getValV()+chi2_upperSideBand.getValV()) / float(f.bins-1-f.ndof) # Get the chi2 from the background-only fit # print 'f.frame.chiSquare(1+f.ndof-10)',f.frame.chiSquare(1+f.ndof)*(f.bins-1-f.ndof) # f.chisquare_sb = f.frame.chiSquare(1+f.ndof-10) # n-1 bins MINUS 10 BINS # f.pvalue_chi2_sb = ROOT.TMath.Prob(f.chisquare_sb*(f.bins-1-f.ndof-10),f.bins-1-f.ndof-10) # print 'chisquare:',f.chisquare_sb,f.pvalue_chi2_sb continue curve = f.frame.getCurve() curve.SetMarkerSize(0) curve.SetLineWidth(1) curve.SetTitle(f.name) curve.SetLineWidth(2) # resid = f.frame.residHist(); resid.SetMarkerSize(0) # plotfunc.AddRatioManual(cans[-1],curve,resid,drawopt1='l',drawopt2='l') pull = f.frame.pullHist() pull.SetMarkerSize(0.7) # for special if options.family == 'selected': color = { 'Pow': ROOT.kBlack + 0, 'Exponential': ROOT.kRed + 1, 'ExpPoly2': ROOT.kBlue + 1, 'Bern3': ROOT.kGreen + 1, 'Bern4': ROOT.kMagenta + 1, 'Bern5': ROOT.kOrange + 1, }.get(f.name) pull.SetMarkerColor(color) pull.SetLineColor(color) curve.SetLineColor(color) curve.SetFillColor(0) plotfunc.AddRatioManual(cans[-1], curve, pull, drawopt1='l', drawopt2='p') plotfunc.SetAxisLabels(cans[-1], 'm_{#gamma#gamma} [GeV]', 'entries', 'pull') the_text = [ plotfunc.GetAtlasInternalText(), plotfunc.GetSqrtsText(13) + ', ' + plotfunc.GetLuminosityText(36.1), category_title, '1-p(F_{%d%d}) = %2.1f%%' % (functions[0].ndof, functions[0].ftest_function.ndof, p_ftest * 100) ] plotfunc.DrawText(cans[-1], the_text, 0.19, 0.63, 0.59, 0.91, totalentries=4) plotfunc.MakeLegend(cans[-1], 0.57, 0.63, 0.90, 0.91, totalentries=4) plotfunc.SetYaxisRanges(plotfunc.GetBotPad(cans[-1]), -4, 4) plotfunc.SetXaxisRanges(cans[-1], functions[0].lower_range, functions[0].upper_range) taxisfunc.AutoFixYaxis(plotfunc.GetTopPad(cans[-1]), forcemin=0.001) print ftest_text a = open('%s/ftests.txt' % (options.outdir), 'w') a.write(options.file + '\n') a.write(ftest_text + '\n') a.close() for can in cans: plotfunc.FormatCanvasAxes(can) anaplot.UpdateCanvases(cans, options) if not options.batch: raw_input('Press enter to exit') anaplot.doSaving(options, cans) return
def main(options,args) : jj_file = ROOT.TFile(options.jj,'read') yj_file = ROOT.TFile(options.yj,'read') af2_file = ROOT.TFile(options.af2,'read') outfile = ROOT.TFile('out.root','RECREATE') cans = [] for i,c in enumerate(['Inclusive']+Tools.categories) : if c == 'M17_VHMET_LOW' : break #print 'HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_AF2'%(i+offset,c) tmp = [] af2 = af2_file.Get('HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_AF2' %(i+offset,c)).Clone() yj = yj_file .Get('HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_data'%(i+offset,c)) jj = jj_file .Get('HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_data'%(i+offset,c)) # print c, af2.Integral(), yj.Integral(), jj.Integral() # continue data_blinded = af2_file.Get('HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_data'%(i+offset,c)) higgs = af2_file.Get('HGamEventInfoAuxDyn_m_yy_over_1000_c%d_%s_Higgs'%(i+offset,c)) data_integral = integral(data_blinded,105,160) outfile.cd() data_blinded.Write() higgs.Write() af2.Sumw2(); yj.Sumw2(); jj.Sumw2(); # Get the parameters for the reweighting procedure yj_newcans,yj_par0,yj_par1,yj_integral_factor = DoRescaleProcedure(af2,yj,'yj',i+offset,c) jj_newcans,jj_par0,jj_par1,jj_integral_factor = DoRescaleProcedure(af2,jj,'jj',i+offset,c) tmp += yj_newcans tmp += jj_newcans # Get the fractions of yy, yj, jj fractions_file = open('fractions.txt','read') for l,line in enumerate(fractions_file) : if (l != i+offset) : continue #print l,line yy_frac = float(line.split()[-3])/100. yj_frac = float(line.split()[-2])/100. jj_frac = float(line.split()[-1])/100. fractions_file.close() print yy_frac,yj_frac,jj_frac # The full reweighting function # yj jj function = ROOT.TF1('%d_%s'%(i+offset,c),'([0]*(x-132.5)/(160-105) + [1])*[2]*[3] + ([4]*(x-132.5)/(160-105) + [5])*[6]*[7] + [8]',105,160) function.SetParameters(yj_par0,yj_par1,yj_frac,yj_integral_factor,jj_par0,jj_par1,jj_frac,jj_integral_factor,yy_frac) data_integral = float(integral(data_blinded,105,120) + integral(data_blinded,130,160) ) af2_integral = float(integral(af2,105,120)+integral(af2,130,160) ) if af2_integral == 0 : print 'ERROR! AF2 Integral for category %s is 0!'%(c) return rebin = 10 # yy for stack af2_yy_stack = af2.Clone(); af2_yy_stack.SetName(af2_yy_stack.GetName()+'_yy_forStack') af2_yy_stack.Scale( yy_frac * data_integral / af2_integral ) af2_yy_stack.Rebin(rebin) # yj for stack af2_yj_stack = af2.Clone(); af2_yj_stack.SetName(af2_yj_stack.GetName()+'_yj_forStack') af2_yj_stack.SetTitle('#gamma^{}#font[12]{j}') function_yj = ROOT.TF1('%d_%s'%(i+offset,c),'([0]*(x-132.5)/(160-105) + [1])*[2]*[3]',105,160) function_yj.SetParameters(yj_par0,yj_par1,yj_frac,yj_integral_factor) function_yj.SetRange(af2.GetBinLowEdge(1),af2.GetBinLowEdge(af2.GetNbinsX()+1)) af2_yj_stack.Multiply(function_yj) af2_yj_stack.Scale( data_integral / af2_integral ) af2_yj_stack.Rebin(rebin) # jj for stack af2_jj_stack = af2.Clone(); af2_jj_stack.SetName(af2_jj_stack.GetName()+'_jj_forStack') af2_jj_stack.SetTitle('#font[12]{jj}') function_jj = ROOT.TF1('%d_%s'%(i+offset,c),'([0]*(x-132.5)/(160-105) + [1])*[2]*[3]',105,160) function_jj.SetParameters(jj_par0,jj_par1,jj_frac,jj_integral_factor) function_jj.SetRange(af2.GetBinLowEdge(1),af2.GetBinLowEdge(af2.GetNbinsX()+1)) af2_jj_stack.Multiply(function_jj) af2_jj_stack.Scale( data_integral / af2_integral ) af2_jj_stack.Rebin(rebin) anaplot.PrepareBkgHistosForStack([af2_jj_stack,af2_yj_stack,af2_yy_stack],'') # full thing. function.SetRange(af2.GetBinLowEdge(1),af2.GetBinLowEdge(af2.GetNbinsX()+1)) af2.Multiply(function) af2.Scale( data_integral / float(integral(af2,105,120)+integral(af2,130,160) ) ) main_can = plotfunc.RatioCanvas('Mimic_Plot_%02d_%s'%(i+offset,c),'Mimic plot',600,500) plotfunc.AddHistogram(main_can,af2_jj_stack) plotfunc.AddHistogram(main_can,af2_yj_stack) plotfunc.AddHistogram(main_can,af2_yy_stack) plotfunc.Stack(main_can) outfile.cd() af2.Write() # Print the final plots, below. #print Tools.FindRebinFactors(af2) af2.Rebin(rebin) data_blinded.Rebin(rebin) data_blinded.SetTitle('Data') #data_blinded.SetBinErrorOption(ROOT.TH1.kPoisson); af2.SetMarkerSize(0); af2.SetLineColor(1); af2.SetLineWidth(2); af2.SetFillColor(1) af2.SetFillStyle(3254); af2.SetTitle('SM') plotfunc.AddHistogram(main_can,af2,drawopt='E2') if False : # RATIO plotfunc.AddRatio(main_can,data_blinded,af2) taxisfunc.SetYaxisRanges(plotfunc.GetBotPad(main_can),0.5,1.5) else : # PULL plotfunc.AddRatio(main_can,data_blinded,af2,divide='pull') taxisfunc.SetYaxisRanges(plotfunc.GetBotPad(main_can),-3.5,4.5) the_text = [plotfunc.GetAtlasInternalText(), plotfunc.GetSqrtsText(13)+', '+plotfunc.GetLuminosityText(36.1), Tools.CategoryNames[c] ] plotfunc.DrawText(main_can,the_text,.2,.67,.61,.90,totalentries=3) plotfunc.MakeLegend(main_can,0.70,0.67,0.92,0.90,ncolumns=2,option=['f','f','f','f','p']) taxisfunc.SetXaxisRanges(main_can,105,160) taxisfunc.AutoFixYaxis(plotfunc.GetTopPad(main_can),minzero=True) plotfunc.SetAxisLabels(main_can,'m_{#gamma#gamma} [GeV]','entries','pull') tmp.append(main_can) for can in tmp : plotfunc.FormatCanvasAxes(can) anaplot.UpdateCanvases(tmp) os.system('mkdir -p c%02d_%s'%(i,c)) for can in tmp : can.Print('c%02d_%s/%s.pdf'%(i,c,can.GetName())) can.Print('c%02d_%s/%s.eps'%(i,c,can.GetName())) cans += yj_newcans cans += jj_newcans if options.nobatch : raw_input('pause') return
def main(): a = ROOT.TH1F('a', 'Legend text for a', 48, -6, 6) b = ROOT.TH1F('b', 'Legend text for b', 48, -6, 6) hist_2d = ROOT.TH2F('hist_2d', 'Legend text for 2d hist', 48, -6, 6, 48, -6, 6) d = ROOT.TGraph( 8, array('d', [-5.5, -4.5, -3.5, -2.5, -2.0, 0, 3.5, 4.5]), array('d', [1000, 2000, 3000, 2500, 1000, 2000, 2200, 2400, 2500, 2600])) d.SetNameTitle('mygraph', 'Legend text for graph') d.SetLineWidth(2) e = ROOT.TF1('e', '12*sin(x*3)+20', -5, 5) for i in [a, b]: i.Sumw2() rand = ROOT.TRandom3(1) for i in range(100000): a.Fill(rand.Gaus(0, 1)) b.Fill(rand.Gaus(0, 1)) hist_2d.Fill(rand.Gaus(0, 1), rand.Gaus(0, 1)) a.Fill(2, 2000) # # The function-based way of making plots # mycanvas = ROOT.TCanvas('mycanvas', 'blah', 600, 500) plotfunc.AddHistogram(mycanvas, a) plotfunc.AddHistogram(mycanvas, b) plotfunc.AddHistogram(mycanvas, e, drawopt='l') plotfunc.SetAxisLabels(mycanvas, 'x axis', 'y axis') mycanvas.SetLogy() # Manual plotfunc.FormatCanvasAxes(mycanvas) plotfunc.SetColors(mycanvas) plotfunc.DrawText(mycanvas, [ plotfunc.GetAtlasInternalText(status='Internal'), plotfunc.GetSqrtsText(13) + ', ' + plotfunc.GetLuminosityText() ], 0.20, 0.78, 0.5, 0.92, totalentries=3) plotfunc.MakeLegend(mycanvas) plotfunc.AutoFixAxes(mycanvas) # Automatic (this one line replaces everything under "Manual") # plotfunc.FullFormatCanvasDefault(mycanvas) # # A ratio canvas from functions # mycanvas_ratio = plotfunc.RatioCanvas('my_ratiocanvas', 'blah', 600, 500) plotfunc.AddHistogram(mycanvas_ratio, a) plotfunc.AddRatio(mycanvas_ratio, b, a) plotfunc.AddHistogram(mycanvas_ratio, d, drawopt='pl') plotfunc.SetAxisLabels(mycanvas_ratio, 'x axis', 'y axis') plotfunc.FullFormatCanvasDefault(mycanvas_ratio) taxisfunc.SetYaxisRanges(mycanvas_ratio.GetPrimitive('pad_bot'), 0, 2) # mycanvas_ratio.Print(plot_functions_can.GetName()+'.pdf') # # Stack Histogram # mycanvas_stack = ROOT.TCanvas('my_stackcanvas', 'blah', 600, 500) plotfunc.AddHistogram(mycanvas_stack, a) plotfunc.AddHistogram(mycanvas_stack, b) plotfunc.SetColors(mycanvas_stack, [ROOT.kGreen + 1, ROOT.kAzure + 2], fill=True) plotfunc.Stack(mycanvas_stack) plotfunc.SetAxisLabels(mycanvas_stack, 'x axis', 'y axis') plotfunc.FullFormatCanvasDefault(mycanvas_stack) # # 2d Histogram # mycanvas_2d = ROOT.TCanvas('my_2dcanvas', 'blah', 600, 500) plotfunc.FormatCanvasAxes(mycanvas_2d) plotfunc.AddHistogram(mycanvas_2d, hist_2d, 'colz') plotfunc.SetAxisLabels(mycanvas_2d, 'x axis', 'y axis') plotfunc.DrawText(mycanvas_2d, [ plotfunc.GetAtlasInternalText(status='Internal'), plotfunc.GetSqrtsText(13) + ', ' + plotfunc.GetLuminosityText() ], 0.20, 0.79, 0.5, 0.93, totalentries=3) plotfunc.SetRightMargin(mycanvas_2d, 0.15) # # Not very important, but plotted objects are stored in the tobject_collector to prevent # them from going out of scope. # print '##' print '## The PlotFunctions TObject collector saved the follwing objects' print '## from going out of scope:' print '##' for i in plotfunc.tobject_collector: print ' -', i, i.GetName() raw_input('Press enter to exit')
def DrawHistos(variable,options,bkg_hists=[],sig_hists=[],data_hist=None,name='',skipBError=False) : # # bkg_hists is a list of background histograms (TH1) # sig_hists is a list of signal histograms (TH1) # variable is a variable name available in pennSoftLepton/Variables.cxx # import ROOT import PlotFunctions as plotfunc import TAxisFunctions as taxisfunc # # Clean up name # canname = CleanUpName(variable) # # stack, before adding SUSY histograms # if not options.ratio and not options.pull : can = ROOT.TCanvas(canname,canname,500,500) else : can = plotfunc.RatioCanvas(canname,canname,500,500) totb = None if bkg_hists : # Make a histogram that includes the total of all bkgs: totb = bkg_hists[0].Clone() totb.SetNameTitle(('%s_%s_SM'%(canname,name)).replace('__','_'),'remove me') totb.SetLineColor(1) totb.SetLineWidth(1) totb.SetMarkerSize(0) totb.SetFillColor(0) for i in bkg_hists[1:] : totb.Add(i) if not skipBError : # A copy of the total bkg histo, for plotting the error bar totberror = totb.Clone() totberror.SetName(totb.GetName().replace('_SM','_error')) totberror.SetTitle('SM (stat)') totberror.SetFillColor(12) totberror.SetFillStyle(3254) for index,i in enumerate(bkg_hists) : # if no data, but you specified you wanted a ratio, then do ratio of MC if (not options.stack) : i.SetLineWidth(2) i.SetLineColor(i.GetMarkerColor()) if len(bkg_hists) == 1 : i.SetFillColor(0) if (index > 0) and (not data_hist) and (not options.stack) and (options.ratio) : plotfunc.AddRatio(can,i,bkg_hists[0]) elif len(bkg_hists) == 1 : plotfunc.AddHistogram(can,i,drawopt='hist') else : plotfunc.AddHistogram(can,i) if bkg_hists and options.stack : plotfunc.Stack(can) if not skipBError : plotfunc.AddHistogram(can,totberror,drawopt='E2',keepname=True) plotfunc.AddHistogram(can,totb,drawopt='hist',keepname=True) for h in sig_hists : plotfunc.AddHistogram(can,h) if data_hist : if options.ratio and totb : plotfunc.AddRatio(can,data_hist,totb) elif options.pull and totb : plotfunc.AddRatio(can,data_hist,totb,divide='pull') else : plotfunc.AddHistogram(can,data_hist) plotfunc.FormatCanvasAxes(can) text_lines = [plotfunc.GetSqrtsText(13)] if options.fb > 0 and not options.normalize : text_lines += [plotfunc.GetLuminosityText(options.fb)] text_lines += [plotfunc.GetAtlasInternalText()] if hasattr(options,'plottext') and options.plottext : text_lines += options.plottext if options.log : if options.ratio or options.pull : if taxisfunc.MinimumForLog(can.GetPrimitive('pad_top')) > 0 : can.GetPrimitive('pad_top').SetLogy() else : if taxisfunc.MinimumForLog(can) > 0 : can.SetLogy() if options.ratio or options.pull : plotfunc.DrawText(can,text_lines,0.2,0.65,0.5,0.90,totalentries=4) plotfunc.MakeLegend(can,0.53,0.65,0.92,0.90,totalentries=5,ncolumns=2,skip=['remove me']) taxisfunc.SetYaxisRanges(plotfunc.GetBotPad(can),0,2) else : plotfunc.DrawText(can,text_lines,0.2,0.75,0.5,0.94,totalentries=4) plotfunc.MakeLegend(can,0.53,0.75,0.94,0.94,totalentries=5,ncolumns=2,skip=['remove me']) ylabel = 'entries (normalized)' if options.normalize else 'entries' plotfunc.SetAxisLabels(can,options.xlabel.get(variable),ylabel,yratiolabel=('pull' if options.pull else 'ratio')) plotfunc.AutoFixAxes(can) if not options.log : if can.GetPrimitive('pad_top') : plotfunc.AutoFixYaxis(can.GetPrimitive('pad_top'),minzero=True) else : plotfunc.AutoFixYaxis(can,minzero=True) return can
def ShowerShapeEvolutionPlot(can, labels, plotset1, plotset2=None, plotset3=None, plotset4=None, plotset5=None, plotset6=None): all_plotsets = [] for others in [plotset1, plotset2, plotset3, plotset4, plotset5, plotset6]: if others: all_plotsets.append(others) # Check that everything is the same length for plotset in all_plotsets: if len(plotset) != len(labels): print 'Error in ShowerShapeEvolutionPlot: Mismatched lengths!' return # # make the background 2d plot for labeling of the y-axis # sample_plot = all_plotsets[0][0] plot2d_for_ylabels = ROOT.TH2F( 'plot2d_for_ylabels', 'remove', sample_plot.GetNbinsX(), sample_plot.GetXaxis().GetBinLowEdge(1), sample_plot.GetXaxis().GetBinLowEdge(sample_plot.GetNbinsX() + 1), len(all_plotsets[0]), 0, len(all_plotsets[0])) for i in range(plot2d_for_ylabels.GetNbinsY()): plot2d_for_ylabels.GetYaxis().SetBinLabel(i + 1, labels[i]) plotfunc.AddHistogram(can, plot2d_for_ylabels, drawopt='colz') plotfunc.FormatCanvasAxes(can) # # Find the histogram with the largest peak relative to its integral # integral_lp = [-1] * len(all_plotsets[0]) index_lp = [-1] * len(all_plotsets[0]) max_over_integral = [0] * len(all_plotsets[0]) for j, plotset in enumerate(all_plotsets): for i, plot in enumerate(plotset): if not plot.Integral() or not plot.GetMaximum(): continue tmp_max_over_integral = plot.GetMaximum() / float( plot.Integral(0, plot.GetNbinsX() + 1)) if tmp_max_over_integral > max_over_integral[i]: max_over_integral[i] = tmp_max_over_integral tmp_scale = 0.9 / float(plot.GetMaximum()) integral_lp[i] = plot.Integral( 0, plot.GetNbinsX() + 1) * tmp_scale index_lp[i] = j # # Add the histograms # Scale the histograms and offset them by 1 # for j, plotset in enumerate(all_plotsets): for i, plot in enumerate(plotset): if not plot.Integral() or not plot.GetMaximum(): continue drawopt = 'hist' if plot.GetOption(): drawopt = plot.GetOption() plot_copy = plotfunc.AddHistogram(can, plot, drawopt) # Scale either to 0.9 of maximum, or to # the integral of the hist with the highest maximum relative to its integral if index_lp[i] == j: plot_copy.Scale(0.9 / float(plot_copy.GetMaximum())) else: plot_copy.Scale( integral_lp[i] / float(plot_copy.Integral(0, plot_copy.GetNbinsX() + 1))) # Y-axis offset for bin in range(plot_copy.GetNbinsX()): plot_copy.SetBinContent(bin + 1, i + plot_copy.GetBinContent(bin + 1)) # # Remove duplicate plot titles (= legend entries) # plottitles = [] for i in can.GetListOfPrimitives(): if hasattr(i, 'GetTitle') and i.GetTitle() in plottitles: i.SetTitle('remove') else: plottitles.append(i.GetTitle()) # # Final details # can.SetTopMargin(0.13) plotfunc.SetLeftMargin(can, 0.27) plotfunc.SetAxisLabels(can, sample_plot.GetXaxis().GetTitle(), '') can.SetGridy() plotfunc.MakeLegend(can, 0.7, 0.88, 0.9, 0.99, totalentries=2) can.Modified() can.Update() return
def IterateAllTheThings(i,j,outdir,options): #if type(i) in unsupported_types : return # TH1, TGraph Types if issubclass(type(i),ROOT.TH1) or issubclass(type(i),ROOT.TGraph) : c = plotfunc.RatioCanvas(i.GetName(),i.GetName(),600,500) i.SetTitle(options.label1) j.SetTitle(options.label2) plotfunc.AddHistogram(c,i) plotfunc.AddRatio(c,j,i) plotfunc.SetAxisLabels(c,j.GetXaxis().GetTitle(),j.GetYaxis().GetTitle()) plotfunc.FormatCanvasAxes(c) plotfunc.SetColors(c) plotfunc.MakeLegend(c) taxisfunc.AutoFixAxes(c) if not os.path.exists(outdir) : os.makedirs(outdir) c.Print('%s/%s.pdf'%(outdir,c.GetName())) c.Print('%s/%s.C'%(outdir,c.GetName())) # TCanvas elif issubclass(type(i),ROOT.TCanvas) : newdir = '%s/%s'%(outdir,i.GetName()) print 'Making new directory %s (line %d)'%(newdir,currentframe().f_lineno) IterateAllTheThings(i.GetListOfPrimitives(),j.GetListOfPrimitives(),newdir,options) # TDirectoryFile elif issubclass(type(i),ROOT.TDirectoryFile) : newdir = '%s/%s'%(outdir,i.GetName()) print 'Making new directory %s (line %d)'%(newdir,currentframe().f_lineno) IterateAllTheThings(i.GetListOfKeys(),j.GetListOfKeys(),newdir,options) #TTree elif issubclass(type(i),ROOT.TTree) : cans = [] treename = i.GetName() # for compatibility with GetVariableHistsFromTrees i_keys = [options.label1] i_trees = {options.label1:i} j_keys = [options.label2] j_trees = {options.label2:j} # get the histograms from the files variables = [] variables_j = list(vv.GetName() for vv in j.GetListOfBranches()) for vv in i.GetListOfBranches() : v = vv.GetName() # print v,vv.GetClassName() skip = ['AuxContainerBase', 'DataVector', 'EventFormat', 'MissingETContainer', 'EventInfo', 'EventAuxInfo', 'AuxInfoBase', ] if True in list(a in vv.GetClassName() for a in skip) : print 'Skipping %s (type %s)'%(v,vv.GetClassName()) continue if v not in variables_j : print 'Warning! %s not in second file. Skipping.'%(v) continue # print v,vv.GetClassName() variables.append(v) for v in variables : if v not in options.histformat.keys() : options.limits[v] = [-1,-1,-1] options.xlabel[v] = v mc_hists = [] if True : mc_hists.append(anaplot.GetVariableHistsFromTrees(i_trees,i_keys,v,'',options)[0]) mc_hists[-1].SetTitle(options.label1) mc_hists[-1].SetLineWidth(2) mc_hists[-1].SetLineColor(1) mc_hists[-1].SetMarkerColor(1) if True : mc_hists.append(anaplot.GetVariableHistsFromTrees(j_trees,j_keys,v,'',options)[0]) mc_hists[-1].SetTitle(options.label2) mc_hists[-1].SetLineWidth(ROOT.kRed+1) mc_hists[-1].SetLineColor(ROOT.kRed+1) mc_hists[-1].SetMarkerColor(ROOT.kRed+1) options.stack = False options.ratio = True cans.append(anaplot.DrawHistos(v,options,mc_hists)) anaplot.UpdateCanvases(cans,options) if not os.path.exists(outdir) : os.makedirs(outdir) for c in cans : c.Print('%s/%s.pdf'%(outdir,c.GetName())) c.Print('%s/%s.C'%(outdir,c.GetName())) # anaplot.doSaving(options,cans) #TList,THashList,ListOfKeys elif issubclass(type(i),ROOT.TList) : secondarray = list(jitem.GetName() for jitem in j) for iitem in i : if iitem.GetName() not in secondarray : print 'Warning! %s not in second file. Skipping.'%(iitem.GetName()) continue jitem = j.At(secondarray.index(iitem.GetName())) is_tkey = False is_th1_or_tgraph = False if issubclass(type(iitem.ReadObj()),ROOT.TH1) : #print '%s is a TH1!'%(iitem.GetName()) is_th1_or_tgraph = True elif issubclass(type(iitem.ReadObj()),ROOT.TGraph) : #print '%s is a TGraph!'%(iitem.GetName()) is_th1_or_tgraph = True elif issubclass(type(iitem),ROOT.TKey) : #print '%s is a TKey!'%(iitem.GetName()) is_tkey = True # TH1, TGraph if is_th1_or_tgraph : print 'Processing %s as a TH1 or TGraph.'%(iitem.GetName()) IterateAllTheThings(iitem.ReadObj(),jitem.ReadObj(),outdir,options) # TKey (not sure why we have to find is_tkey earlier) elif is_tkey : newdir = '%s/%s'%(outdir,iitem.GetName()) print 'Processing %s as a TKey. Making new directory %s (line %d)'%(iitem.GetName(),newdir,currentframe().f_lineno) IterateAllTheThings(iitem.ReadObj(),jitem.ReadObj(),newdir,options) else : print 'Within list: %s type'%(iitem.GetName()),type(iitem),'not supported yet. Let Kurt know! (Ref: 2)' else : print '%s type'%(i.GetName()),type(i),'not supported yet. Let Kurt know! (Ref: 1)' return