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 DoRescaleProcedure(af2,bkg,name,ci,c) : cans = [] if integral(af2,105,160) == 0 : return [],0,1,1 if integral(bkg,105,160) == 0 : return [],0,1,1 # Print the "before" picture cans.append(plotfunc.RatioCanvas('UntouchedRatio_%02d_%s_%s'%(ci,c,name),'%d_%s_%s'%(ci,c,name),600,500)) af2_rebin = plotfunc.AddHistogram(cans[-1],af2) bkg_rebin = bkg.Clone() bkg_rebin.SetName(bkg_rebin.GetName()+'_forRebinning') Tools.RebinUntilSmallErrors(af2_rebin,bkg_rebin,binmin=105,binmax=160,errormax=1) af2_rebin.Scale(integral(bkg_rebin,105,160)/integral(af2_rebin,105,160)) unused,af2_bkg_ratio = plotfunc.AddRatio(cans[-1],bkg_rebin,af2_rebin) taxisfunc.AutoFixAxes(cans[-1]) taxisfunc.SetXaxisRanges(cans[-1],105,160) taxisfunc.SetYaxisRanges(plotfunc.GetBotPad(cans[-1]),0,2) plotfunc.SetAxisLabels(cans[-1],'m_{#gamma#gamma} [GeV]','entries') # Fit the ratio of the CR and the AF2 with a line function = ROOT.TF1('%d_%s'%(ci,c),'[0]*(x-132.5)/(160-105) + [1]',105,160) if (integral(bkg,105,160) > 16) : af2_bkg_ratio.Fit('%d_%s'%(ci,c)) else : print 'Not enough events to do a fit! Setting parameters to 0,1.' function.SetParameters(0,1) af2_integral = integral(af2,105,160) af2_before = af2.Clone() af2_before.SetTitle(af2_before.GetName()+'_before') af2_before.SetTitle('AF2 unweighted') af2_result = af2.Clone() af2_result.SetTitle(af2_result.GetName()+'_rescaled') # Multiply the AF2 by the function function.SetRange(af2.GetBinLowEdge(1),af2.GetBinLowEdge(af2.GetNbinsX()+1)) af2_result.Multiply(function) af2_result.SetTitle('AF2 reweighted') # The multiplication above changes the integral, so you # have to calculate an "integral factor" to correct for this. integral_factor = af2_integral / float(integral(af2_result,105,160)) #Tools.RebinUntilSmallErrors(af2_result,bkg,binmin=105,binmax=160,errormax=1) af2_before.Rebin(10) af2_before.SetMarkerColor(ROOT.kGray) af2_before.SetFillColor(ROOT.kGray) af2_result.Rebin(10) bkg.Rebin(10) bkg.SetTitle(name.replace('y','#gamma^{}')) if integral(af2_result,105,160) : af2_before.Scale(integral(bkg,105,160)/integral(af2_before,105,160)) af2_result.Scale(integral(bkg,105,160)/integral(af2_result,105,160)) # Print the "after" (rescaled) result cans.append(plotfunc.RatioCanvas('rescaled_%02d_%s_%s'%(ci,c,name),'%d_%s_%s_rescaled'%(ci,c,name),600,500)) plotfunc.AddHistogram(cans[-1],af2_before) plotfunc.AddHistogram(cans[-1],bkg) plotfunc.AddRatio(cans[-1],af2_result,bkg,divide='pull') plotfunc.MakeLegend(cans[-1],0.64,0.70,0.74,0.87,option=['f','pl','f']) taxisfunc.AutoFixAxes(cans[-1]) taxisfunc.SetXaxisRanges(cans[-1],105,160) taxisfunc.SetYaxisRanges(plotfunc.GetBotPad(cans[-1]),-3,4) plotfunc.SetAxisLabels(cans[-1],'m_{#gamma#gamma} [GeV]','entries') return cans,function.GetParameter(0),function.GetParameter(1),integral_factor
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 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 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