def calc_punzi_FOM_vs_ctau(cutlist, labellist=[],mass_point=40,additional_string="",alpha=2,CL=5,FOM='punzi',header=""): file = {} nevt = {} tree = {} effs = {} chain = {} hist = {} eff_dict = { k:{} for k in cutlist} back_int = { k:{} for k in cutlist} back_int_weight = { k:{} for k in cutlist} back_eff = { k:{} for k in cutlist} punzi_dict = { k:{} for k in cutlist} graph = {} back_graph = {} ncuts = len(cutlist) if labellist == []: labellist=cutlist print NTUPLEDIR print "............." #prepare ctau ordered array for 1D plot mass_array = [] ctau_array = [] #for signal we have the normal efficiency for i, s in enumerate(sign): file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") # Read TFile tree[s] = file[s].Get("ntuple/tree") # Read TTree nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)# all gen events before cuts! #tree[s] = file[s].Get("skim") # Read TTree #nevt[s] = tree[s].GetEntries("")#if the tree is skimmed, this becomes a relative denominator #nevt[s] = (file[s].Get('c_nEvents')).GetBinContent(1)# all gen events before cuts! filename = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") if verbose_add: print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' if verbose_add: print filename if verbose_add: print "x-check: n gen events in counter, first bin:" if verbose_add: print (filename.Get('c_nEvents')).GetBinContent(1) if verbose_add: print "x-check: n entries in counter:" if verbose_add: print (filename.Get('c_nEvents')).GetEntries() effs[s] = [0]*(ncuts+1) effs[s] = [0]*(ncuts+1) weight = "1"#"EventWeight" var = "isMC" if samples[s]['mass'] not in mass_array: mass_array.append(samples[s]['mass']) if samples[s]['ctau'] not in ctau_array: ctau_array.append(samples[s]['ctau']) for j, c in enumerate(cutlist): tot_gen = nevt[s] n = tree[s].GetEntries("(" + cutlist[j] + ")") #wat?#test_op = cutlist[j] + " && number_of_matched_Jets>=1" #wat?#n = tree[s].GetEntries("(" + test_op + ")") ###BUGFIX: efficiency should be computed w.r.t. histo integral #hist[s+"_cut"+str(j)] = TH1F(s+"_cut"+str(j), ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) #hist[s+"_cut"+str(j)].Sumw2() #cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") #tree[s].Project(s+"_cut"+str(j), var, cutstring) #hist[s+"_cut"+str(j)].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) if verbose_add: print '\n' if verbose_add: print '**********************************************' if verbose_add: print "cut: ", c if verbose_add: print 'over signal ', s if verbose_add: print '\n' if verbose_add: print "signal num: ", n if verbose_add: print "signal den: ", tot_gen #if verbose_add: print "BUGFIX!!!!!!!!!!!" #if verbose: print "BUGFIX!!!!!!!!!!!" #if verbose_add: print "signal num from integral: ", hist[s+"_cut"+str(j)].Integral() #if verbose_add: print "signal den from generator: ", tot_gen #if verbose: print "BUGFIX!!!!!!!!!!!" if verbose_add: print ("signal eff %.2f") % (float(n)/(tot_gen)*100) if tot_gen==0: effs[s][j] = float(0.) else: effs[s][j] = (float(n)/(tot_gen)) eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j], 'nevents' : n} #sort mass array masses = np.array(mass_array) masses.sort() ctaus = np.array(ctau_array) ctaus.sort() #define multigraph mg = TMultiGraph() #leg = TLegend(0.78, 0.7, 0.98, 0.98) #leg2 = TLegend(0., 0.4, 0.98, 0.98) #leg2 = TLegend(0.3, 0.11, 0.65, 0.45)#DCMS,gen matching leg2 = TLegend(0.4, 0.11, 0.85, 0.45)#DCMS,summary plot leg2 = TLegend(0.4-0.3, 0.11+0.43, 0.85+0.05-0.3, 0.45+0.43)#EXO,summary plot leg2 = TLegend(0.4, 0.11, 0.85+0.05, 0.45)#EXO,summary plot leg3 = TLegend(0., 0.5, 0.5, 1.)#2 plots leg = TLegend(0., 0.4, 0.98, 0.98) leg.SetTextSize(0.03) leg2.SetTextSize(0.03) leg2.SetTextSize(0.025) leg.SetBorderSize(0) leg2.SetBorderSize(0) leg.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg2.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg3.SetTextSize(0.03) leg3.SetTextSize(0.025) leg3.SetBorderSize(0) leg3.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") #for background let's first consider the cut for j, c in enumerate(cutlist): print '\n' print "cut: ", c print 'over background' print '\n' #then loop over background integral = 0 weighted_integral = 0 back_tot_events = 0 for i, s in enumerate(back): chain[s] = TChain("ntuple/tree") #chain[s] = TChain("skim") #print "back: ", s back_file = {} for p, ss in enumerate(samples[s]['files']): back_file[ss] = TFile(NTUPLEDIR + ss + ".root", "READ") # Read TFile #?#if verbose: print "file: ", ss #?#if verbose: print "gen events: ", (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #?#if verbose: print "tree events: ", (back_file[ss].Get('ntuple/tree')).GetEntries() back_tot_events += (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #back_tot_events += (back_file[ss].Get('c_nEvents')).GetBinContent(1) chain[s].Add(NTUPLEDIR + ss + ".root") #print "MODIFIED WEIGHT!!!!!!" #weight = ("EventWeight*%s/5000." % str(back_tot_events)) weight = "EventWeight" #var = "nCHSJets" var = "isMC" hist[s] = TH1F(s, ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) hist[s].Sumw2() cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") chain[s].Project(s, var, "")#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) #if verbose: print "Hist content, no cut:" #if verbose: print hist[s].Print() #?#if verbose: print "events in the histo with get entries with empty project: ", hist[s].GetEntries() #?#if verbose: print "area under histo with empty project: ", hist[s].Integral() chain[s].Project(s, var, cutstring)#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) hist[s].Scale(samples[s]['weight'] if hist[s].Integral() >= 0 else 0) #?#if verbose: print "events in the histo with get entries after project: ", hist[s].GetEntries() #?#if verbose: print "area under histo after project: ", hist[s].Integral() if verbose: print "Hist content, with cut:" if verbose: print hist[s].Print() integral += hist[s].GetEntries() weighted_integral += hist[s].Integral() back_int[c] = integral back_int_weight[c] = weighted_integral if back_tot_events==0: back_eff[c] = float(0.) else: back_eff[c] = float(integral)/float(back_tot_events) if verbose: print "cut: ", c if verbose: print "back tot events (unweighted):", back_tot_events if verbose: print "back integral (unweighted): ", back_int[c] if verbose: print "back integral (weighted): ", back_int_weight[c] if verbose: print "back eff (unweighted): ", back_eff[c]*100 if FOM=="signaleff": punzi_dict[c]['back'] = {'back' : back_eff[c]*100} for i, s in enumerate(sign): if verbose: print "signal efficiency: ", eff_dict[c][s]['eff']*100 if FOM=="punzi": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']/(CL**2/2. + alpha*math.sqrt(back_int_weight[c]) + (CL/2.)*math.sqrt(CL**2 + 4*alpha*math.sqrt(back_int_weight[c]) + 4*back_int_weight[c]))} elif FOM=="signaleff": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']*100} elif FOM=="entries": punzi_dict[c][s] = {'sign': eff_dict[c][s]['nevents']} else: print "not punzi FOM, aborting!" exit() if FOM=="signaleff": dummy = TGraph()#len(ct),ct, np.array(ct)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) if header!="": leg2.AddEntry(dummy, header,'') leg3.AddEntry(dummy, header,'') #for each cut, we need a graph for j, c in enumerate(cutlist): #first let's build the ordered punzi vector w.r.t. masses, for a chosen ctau punzi_array = [] back_array = [] for la in ctaus: #la = str(a) if la== 0.001: st = CHANNEL+"_M"+str(mass_point)+"_ctau0" elif la==0.05 or la==0.1: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(str(la).replace("0.","0p")) else: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(int(la)) #st = "VBFH_M"+str(mass_point)+"_ctau"+str(a) punzi_array.append(punzi_dict[c][st]['sign']) mass = array('d', masses) ct = array('d', ctaus) p_array = array('d',punzi_array) #graph[c] = TGraph(len(mass),mass, np.array(p_array)) graph[c] = TGraph(len(ct),ct, np.array(p_array)) graph[c].SetMarkerStyle(markers[j])#21 graph[c].SetLineWidth(3) graph[c].SetMarkerSize(1.2) graph[c].SetMarkerColor(colors[j]) graph[c].SetLineColor(colors[j]) graph[c].SetFillColor(colors[j]) #graph[c].SetLogx() leg.AddEntry(graph[c],labellist[j],'PL') leg2.AddEntry(graph[c],labellist[j],'PL') leg3.AddEntry(graph[c],labellist[j],'PL') mg.Add(graph[c]) if FOM=="signaleff": #add plot for background for a in ctaus: back_array.append(punzi_dict[c]['back']['back']) mass = array('d', masses) ct = array('d', ctaus) e_array = array('d',back_array) #back_graph[c] = TGraph(len(mass),mass, np.array(e_array)) back_graph[c] = TGraph(len(ct),ct, np.array(e_array)) back_graph[c].SetMarkerStyle(0) back_graph[c].SetLineWidth(2) back_graph[c].SetMarkerSize(1.) back_graph[c].SetMarkerColor(colors[j]) back_graph[c].SetLineColor(colors[j]) back_graph[c].SetLineStyle(2) back_graph[c].SetFillColor(colors[j]) #back_graph[c].SetLogx() #leg.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#leg2.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#mg.Add(back_graph[c]) if FOM=="signaleff": dummy = TGraph(len(ct),ct, np.array(e_array)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) #w#leg2.AddEntry(dummy, 'cuts on bkg.','PL') #cmg = TCanvas("cmg", "cmg", 2000, 1400) #cmg = TCanvas("cmg", "cmg", 2000, 800)#best #cmg = TCanvas("cmg", "cmg", 1200, 1000) cmg = TCanvas("cmg", "cmg", 1300, 800)#DCMS cmg.cd() cmg.SetGrid() cmg.SetLogx() #if FOM=="signaleff": # cmg.SetLogx() #pad1 = TPad("pad1", "pad1", 0, 0., 0.85, 1.0) #pad1 = TPad("pad1", "pad1", 0, 0., 0.7, 1.0) #pad1.SetGrid() #pad1.SetLogx() if FOM=="signaleff": print "LOL" #pad1.SetLogy() #pad1.SetLogy() #pad1.Draw() #pad1.cd() #W#if FOM=="signaleff": #w#mg.SetMaximum(101) #mg.SetMinimum(1.e-50) mg.SetMinimum(0.)#!! mg.Draw("APL") mg.GetXaxis().SetTitleSize(0.05) mg.GetYaxis().SetTitleSize(0.05) mg.GetXaxis().SetTitle('c#tau_{#pi} (mm)') mg.GetYaxis().SetTitleOffset(0.9); if FOM=="punzi": mg.GetYaxis().SetTitle('Punzi significance @ '+str(alpha)+' #sigma, '+CHANNEL+' cuts') #mg.GetYaxis().SetTitleOffset(1.5) elif FOM=="signaleff": #mg.GetYaxis().SetTitle('Signal efficiency, '+CHANNEL+' cuts (%)') mg.GetYaxis().SetTitle('Signal gen-matching efficiency, '+CHANNEL+' (%)') elif FOM=="entries": mg.GetYaxis().SetTitle('Signal entries surviving cuts') else: print "not punzi FOM, aborting" latex = TLatex() latex.SetNDC() latex.SetTextSize(0.05) latex.SetTextColor(1) latex.SetTextFont(42) latex.SetTextAlign(33) latex.SetTextFont(62) latex.DrawLatex(0.25, 0.96, "CMS") latex.SetTextFont(52) latex.DrawLatex(0.66, 0.96, "Simulation Preliminary") cmg.Update() cmg.cd() leg2.SetTextSize(0.04) #leg.Clear()#????????? #w#leg2.Draw() cmgL = TCanvas("cmgL", "cmgL", 2000, 800)#DCMS cmgL.cd() #pad2 = TPad("pad2", "pad2", 0.85, 0., 1, 1.0) #pad2 = TPad("pad2", "pad2", 0.7, 0., 1, 1.0) #pad2.SetGrid() #pad2.SetLogx()macro/VBF_punzi_LLP_AOD.py #pad2.Draw() #pad2.cd() leg3.SetTextSize(0.04) #leg.Clear()#????????? leg3.Draw() cmgL.Update() if FOM=="punzi": cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".pdf") cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".png") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.png") elif FOM=="signaleff": cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") elif FOM=="entries": cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") else: print "not punzi FOM, aborting" if not options.bash: raw_input("Press Enter to continue...") cmg.Close()
discname = "DeepCSV" if "DeepFlav" in nomudir: discname = "DeepJet" withmufiles = [ i for i in os.listdir(withmudir) if i.startswith("TT_semi") and i.endswith(".root") ] nomufiles = [ i for i in os.listdir(nomudir) if i.startswith("TT_semi") and "syst" not in i and i.endswith(".root") ] for disc in ["CvsL", "CvsB"]: legend = TLegend(0.35, 0.75, 0.85, 0.90, "") #,"brNDC" legend.SetFillStyle(0) legend.SetTextSize(0.035) wmuMC = [] wmuData = [] nmuMC = [] nmuData = [] for wmu in withmufiles: if disc not in wmu: continue rfl = TFile.Open(withmudir + wmu, "READ") MC = rfl.Get("MCSum") D = rfl.Get("Data") MC.SetDirectory(0) D.SetDirectory(0) rfl.Close() if wmuMC == []:
from ROOT import TLatex from array import array f1 = ROOT.TFile.Open( "/Users/ms08962476/singularity/TIming_Studies/tev5mm_pythia6_zprime5tev_qq_1P5GeV_cut_rank_reduce_tosix_mass.root", 'r') h1 = f1.Get("Timing_momentum_correlation") c = TCanvas("c1", "c1", 0, 0, 500, 500) gStyle.SetOptStat(0) leg = TLegend(0.5, 0.1, 0.7, 0.3) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetBorderSize(0) leg.SetTextFont(22) leg.Draw() h1.GetXaxis().SetRangeUser(0, 1) h1.GetYaxis().SetRangeUser(0, 1) h1.SetXTitle("P Rank") h1.SetYTitle("T rank") h1.SetZTitle("Arbitrary number") ''' if(variable[var]=="shower_depth_out"): h3 = TH1F("h3","Ratio histogram",40,5,15) h3=h1.Clone("h3") h3.Divide(h2) h1.SetTitle("Shower Depth Data/MC comparison") h2.SetTitle("Shower Depth Data/MC comparison")
def RooFitHist(inputhist, title='title', path='.'): # RooFit.gErrorIgnoreLevel = RooFit.kInfo # <6.02 # RooFit.SetSilentMode()# >6.02 # RooMsgService().instance().SetSilentMode(kTRUE) fitbinning = array('d') binwidth = 200 #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 ) NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) # print(fitbinning) hist = inputhist.Rebin(NBins, "fit parameter", fitbinning) meanstart = hist.GetBinCenter(hist.GetMaximumBin()) sigmastart = hist.GetRMS() print('meanstart:', meanstart, 'sigmastart:', sigmastart) # inputhist.Draw() # hist.Draw() # hold=raw_input('press enter to exit.') gStyle.SetOptFit(1100) gStyle.SetOptTitle(0) RooFit.SumW2Error(kTRUE) mjj = RooRealVar('mjj', 'M_{jj-AK8}', fitbinning[0], fitbinning[len(fitbinning) - 1], 'GeV') mjjral = RooArgList(mjj) dh = RooDataHist('dh', 'dh', mjjral, RooFit.Import(hist)) shapes = {} #Gaussian gaussmean = RooRealVar('#mu_{gauss}', 'mass mean value', meanstart, 0, 2 * meanstart) gausssigma = RooRealVar('#sigma_{gauss}', 'mass resolution', sigmastart, 0, 2 * sigmastart) gauss = RooGaussian('gauss', 'gauss', mjj, gaussmean, gausssigma) shapes.update({'Gauss': gauss}) #CrystalBall mean = RooRealVar('#mu', 'mean', meanstart, 0, 2 * meanstart) sigma = RooRealVar('#sigma', 'sigma', sigmastart, 0, 2 * sigmastart) alpha = RooRealVar('#alpha', 'Gaussian tail', -1000, 0) n = RooRealVar('n', 'Normalization', -1000, 1000) cbshape = RooCBShape('cbshape', 'crystalball PDF', mjj, mean, sigma, alpha, n) shapes.update({'CrystalBall': cbshape}) #Voigt voigtmean = RooRealVar('#mu', 'mass mean value', meanstart, 0, 2 * meanstart) voigtwidth = RooRealVar('#gamma', 'width of voigt', 0, 5000) voigtsigma = RooRealVar('#sigma', 'mass resolution', sigmastart, 0, 2 * sigmastart) voigt = RooVoigtian('voigt', 'voigt', mjj, voigtmean, voigtwidth, voigtsigma) shapes.update({'Voigt': voigt}) #BreitWigner bwmean = RooRealVar('#mu', 'mass mean value', meanstart, 0, 2 * meanstart) bwwidth = RooRealVar('#sigma', 'width of bw', sigmastart, 0, 2 * sigmastart) bw = RooBreitWigner('bw', 'bw', mjj, bwmean, bwwidth) shapes.update({'BreitWigner': bw}) #Landau landaumean = RooRealVar('#mu_{landau}', 'mean landau', meanstart, 0, 2 * meanstart) landausigma = RooRealVar('#sigma_{landau}', 'mass resolution', sigmastart, 0, 2 * sigmastart) landau = RooLandau('landau', 'landau', mjj, landaumean, landausigma) shapes.update({'Landau': landau}) #LandauGauss Convolution landaugauss = RooFFTConvPdf('landaugauss', 'landau x gauss', mjj, landau, gauss) shapes.update({'LandauGauss': landaugauss}) #Logistics # logisticsmean=RooRealVar('#mu_{logistics}','mean logistics',meanstart,0,2*meanstart) # logisticssigma= RooRealVar('#sigma_{logistics}','mass resolution',sigmastart,0,2*sigmastart) # logistics=RooLogistics('logistics','logistics',mjj,logisticsmean,logisticssigma) # shapes.update({'Logistics':logistics}) #ExpAndGauss # expgaussmean=RooRealVar('#mu_{expgauss}','mean expgauss',meanstart,0,2*meanstart) # expgausssigma= RooRealVar('#sigma_{expgauss}','mass resolution',sigmastart,0,2*sigmastart) # expgausstrans= RooRealVar('trans','trans',0,100) # expgauss=RooExpAndGauss('expgauss','expgauss',mjj,expgaussmean,expgausssigma,expgausstrans) # shapes.update({'ExpAndGauss':expgauss}) #BifurGauss BifurGaussmean = RooRealVar('#mu_{BifurGauss}', 'mean BifurGauss', meanstart, 0, 2 * meanstart) BifurGausslsigma = RooRealVar('#sigma_{left}', 'mass resolution', sigmastart, 0, 2 * sigmastart) BifurGaussrsigma = RooRealVar('#sigma_{right}', 'mass resolution', sigmastart, 0, 2 * sigmastart) BifurGauss = RooBifurGauss('BifurGauss', 'BifurGauss', mjj, BifurGaussmean, BifurGausslsigma, BifurGaussrsigma) shapes.update({'BifurGauss': BifurGauss}) #Chebychev Chebychev1 = RooRealVar('c0', 'Chebychev0', -1000, 1000) Chebychev2 = RooRealVar('c1', 'Chebychev1', -1000, 1000) Chebychev3 = RooRealVar('c2', 'Chebychev2', 2, -1000, 1000) Chebychev = RooChebychev('Chebychev', 'Chebychev', mjj, RooArgList(Chebychev1, Chebychev2, Chebychev3)) shapes.update({'Chebychev': Chebychev}) #Polynomial Polynomial1 = RooRealVar('Polynomial1', 'Polynomial1', 100, 0, 1000) Polynomial2 = RooRealVar('Polynomial2', 'Polynomial2', 100, 0, 1000) Polynomial = RooPolynomial('Polynomial', 'Polynomial', mjj, RooArgList(Polynomial1, Polynomial2)) shapes.update({'Polynomial': Polynomial}) # mjj.setRange("FitRange",1050.,14000.) # for fname in ['Gauss','Logistics','BifurGauss']: for fname in ['BifurGauss']: plottitle = '%s Fit of %s' % (fname, title) shape = shapes[fname] # shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.SumW2Error(True)) shape.fitTo(dh, RooFit.SumW2Error(True)) frame = mjj.frame(RooFit.Title(plottitle)) frame.GetYaxis().SetTitleOffset(2) dh.plotOn(frame, RooFit.MarkerStyle(4)) shape.plotOn(frame, RooFit.LineColor(2)) ndof = dh.numEntries() - 3 #chiSquare legend chi2 = frame.chiSquare() probChi2 = TMath.Prob(chi2 * ndof, ndof) chi2 = round(chi2, 2) probChi2 = round(probChi2, 2) leg = TLegend(0.5, 0.5, 0.9, 0.65) leg.SetBorderSize(0) leg.SetFillStyle(0) shape.paramOn(frame, RooFit.Layout(0.5, 0.9, 0.9)) leg.AddEntry(0, '#chi^{2} =' + str(chi2), '') leg.AddEntry(0, 'Prob #chi^{2} = ' + str(probChi2), '') leg.SetTextSize(0.04) frame.addObject(leg) canv = TCanvas(plottitle, plottitle, 700, 700) canv.SetLogy() canv.SetLeftMargin(0.20) canv.cd() frame.SetMinimum(10**(-3)) frame.Draw() canv.Print(path + '/%s__%s.eps' % (title, fname)) return chi2
def plot(): region = "ElEl" flavour = "El" CR = "RealCR" tightness = "T" variable = "Pt" subdir = "".join((region, CR, flavour, tightness)) path = "../OutputPlots_MMRates_v028/" + subdir + "/" list_plots = [ "".join((flavour, "Probe", variable, ".root")), "".join( (flavour, "0", variable, ".root")), "".join( (flavour, "1", variable, ".root")) ] list_files = [] for item in list_plots: item = "".join((path, subdir, "_", item)) list_files.append(item) hist_list = [] for idx, item in enumerate(list_files): print("Now reading: {0}, index {1}".format(item, idx)) myfile = TFile(item) myhist = myfile.Get("observed") hist_list.append(myhist) # This will keep the histogram alive in memory even after the TFile gets destroyed myhist.SetDirectory(0) c = TCanvas("c", "Temp", 50, 50, 700, 900) legend = TLegend(0.6, 0.8, 0.8, 0.85) # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) ) header = "Lepton " + variable + " - " + subdir legend.SetHeader(header) legend.AddEntry(None, "", "") legend.SetBorderSize(0) # no border legend.SetFillColor(0) # legend_L background should be white legend.SetTextSize(15) # Increase entry font size! legend.SetTextFont(43) # Helvetica outfile = open(path + "Yields_" + subdir + "_" + variable + ".txt", "w") for idx, myhist in enumerate(hist_list): print("hist name {0}".format(myhist.GetName())) outfile.write("%s - %s \n" % (list_plots[idx], myhist.GetName())) outfile.write("{ Nr. events: %s }; \n" % (myhist.Integral())) # get the bin number for pT = 60 GeV bmin = myhist.FindBin(60.0) # get the overflow bin bmax = myhist.GetNbinsX() + 1 integral_range = myhist.Integral(bmin, bmax) outfile.write("{ Nr. events (pT > 60 GeV): %s }; \n" % (integral_range)) myhist.SetLineColor(2 * idx + 2) myhist.SetMarkerColor(2 * idx + 2) legend.AddEntry(myhist, list_plots[idx], "L") legend.AddEntry(None, "", "") if idx == 0: myhist.Draw("E0") else: myhist.Draw("E0 SAME") legend.Draw() c.SaveAs(path + "CompareData_" + subdir + "_" + variable + ".png") outfile.close()
exp_hct_bdt = TLine(1, xsec * expected[1], 2, xsec * expected[1]) exp_hct_keras_mat = TLine(2, xsec * expected[2], 3, xsec * expected[2]) exp_hct_bdt_mat = TLine(3, xsec * expected[3], 4, xsec * expected[3]) exp_hut_keras = TLine(4, xsec * expected[4], 5, xsec * expected[4]) exp_hut_bdt = TLine(5, xsec * expected[5], 6, xsec * expected[5]) exp_hut_keras_mat = TLine(6, xsec * expected[6], 7, xsec * expected[6]) exp_hut_bdt_mat = TLine(7, xsec * expected[7], 8, xsec * expected[7]) exp = [ exp_hct_keras, exp_hct_bdt, exp_hct_keras_mat, exp_hct_bdt_mat, exp_hut_keras, exp_hut_bdt, exp_hut_keras_mat, exp_hut_bdt_mat ] for lines2 in exp: lines2.SetLineColor(1) lines2.SetLineWidth(2) lines2.SetLineStyle(7) lines2.Draw('same') ################################ l = TLegend(0.17, 0.75, 0.6, 0.87) l.SetNColumns(2) l.SetTextSize(0.03) l.SetLineColor(0) l.SetFillColor(0) l.AddEntry(exp_hct_keras, 'Expected', 'l') l.AddEntry(obs_hct_keras, 'Observed', 'l') l.AddEntry(sig1box1, '68% expected', 'f') l.AddEntry(sig2box1, '95% expected', 'f') l.Draw('same') c1.Print('out.pdf')
def drawlegend(self, position=None, **kwargs): """Create and draw legend. Legend position can be controlled in several ways drawlegend(position) drawlegend(position=position) where position is a string which can contain the horizontal position, e.g. 'left', 'center', 'right', 'L', 'C', 'R', 'x=0.3', ... where 'x' is the position (between 0 an 1) of the left side in the frame. The position string can also contain the vertical position as e.g. 'top', 'middle', 'bottom', 'T', 'M', 'B', 'y=0.3', ... where 'y' is the position (between 0 an 1) of the top side in the frame. Instead of the strings, the exact legend coordinates can be controlled with the keywords x1, x2, y1 and y2, or, x1, y1, width and height: drawlegend(x1=0.2,width=0.4) drawlegend(x1=0.2,width=0.4,y1=0.9,height=0.4) drawlegend(x1=0.2,x2=0.6,y1=0.9,y2=0.4) These floats are normalized to the axis frame, ignoring the canvas margins: x=0 is the left, x=1 is the right, y=0 is the bottom and y=1 is the top side. Values less than 0, or larger than 1, will put the legend outside the frame. """ #if not ratio: # tsize *= 0.80 # signaltsize *= 0.80 verbosity = LOG.getverbosity(self, kwargs) hists = self.hists errstyle = 'lep' if gStyle.GetErrorX() else 'ep' entries = kwargs.get('entries', []) bands = kwargs.get('band', [self.errband]) # error bands bands = ensurelist(bands, nonzero=True) bandentries = kwargs.get('bandentries', []) title = kwargs.get('header', None) title = kwargs.get('title', title) # legend header/title latex = kwargs.get('latex', True) # automatically format strings as LaTeX style = kwargs.get('style', None) style0 = kwargs.get('style0', None) # style of first histogram errstyle = kwargs.get('errstyle', errstyle) # style for an error point styles = kwargs.get('styles', []) position = kwargs.get('pos', position) # legend position position = kwargs.get('position', position) or self.position option = kwargs.get('option', '') border = kwargs.get('border', False) transparent = kwargs.get('transparent', True) x1_user = kwargs.get('x1', None) # legend left side x2_user = kwargs.get('x2', None) # legend right side y1_user = kwargs.get('y1', None) # legend top side y2_user = kwargs.get('y2', None) # legend bottom side width = kwargs.get('width', -1) # legend width height = kwargs.get('height', -1) # legend height tsize = kwargs.get('tsize', _lsize) # text size twidth = kwargs.get('twidth', None) or 1 # scalefactor for legend width theight = kwargs.get('theight', None) or 1 # scalefactor for legend height texts = kwargs.get('text', []) # extra text below legend ncols = kwargs.get('ncols', self.ncols) or 1 # number of legend columns colsep = kwargs.get('colsep', 0.06) # seperation between legend columns bold = kwargs.get('bold', True) # bold legend header panel = kwargs.get('panel', 1) # panel (top=1, bottom=2) texts = ensurelist(texts, nonzero=True) entries = ensurelist(entries, nonzero=False) bandentries = ensurelist(bandentries, nonzero=True) headerfont = 62 if bold else 42 # CHECK LOG.insist(self.canvas, "Canvas does not exist!") self.canvas.cd(panel) scale = 485. / min(gPad.GetWh() * gPad.GetHNDC(), gPad.GetWw() * gPad.GetWNDC()) tsize *= scale # text size # ENTRIES #if len(bandentries)==len(bands) and len(entries)>len(hists): # for band, bandtitle in zip(band,bandentries): # entries.insert(hists.index(band),bandtitle) while len(entries) < len(hists): entries.append(hists[len(entries)].GetTitle()) while len(bandentries) < len(bands): bandentries.append(bands[len(bandentries)].GetTitle()) hists = hists + bands entries = entries + bandentries if latex: title = maketitle(title) entries = [maketitle(e) for e in entries] texts = [maketitle(t) for t in texts] maxlen = estimatelen([title] + entries + texts) # STYLES if style0: styles[0] = style0 while len(styles) < len(hists): hist = hists[len(styles)] if hist in bands: styles.append('f') elif style != None: styles.append(style) elif hasattr(hist, 'GetFillStyle') and hist.GetFillStyle() > 0: styles.append('f') elif 'E0' in hist.GetOption() or 'E1' in hist.GetOption(): styles.append(errstyle) else: styles.append('lp') # NUMBER of LINES nlines = sum([1 + e.count('\n') for e in entries]) #else: nlines += 0.80 if texts: nlines += sum([1 + t.count('\n') for t in texts]) if ncols > 1: nlines /= float(ncols) if title: nlines += 1 + title.count('\n') # DIMENSIONS if width < 0: width = twidth * max(0.22, min(0.60, 0.036 + 0.016 * maxlen)) if height < 0: height = theight * 1.34 * tsize * nlines if ncols > 1: width *= ncols / (1 - colsep) x2 = 0.90 x1 = x2 - width y1 = 0.92 y2 = y1 - height # POSITION if position == None: position = "" position = position.replace('left', 'L').replace( 'center', 'C').replace('right', 'R').replace( #.lower() 'top', 'T').replace('middle', 'M').replace('bottom', 'B') if not any(c in position for c in 'TMBy'): # set default vertical position += 'T' if not any(c in position for c in 'LCRx'): # set default horizontal position += 'RR' if ncols > 1 else 'R' # if title else 'L' if 'C' in position: if 'R' in position: center = 0.57 elif 'L' in position: center = 0.43 else: center = 0.50 x1 = center - width / 2 x2 = center + width / 2 elif 'LL' in position: x1 = 0.03 x2 = x1 + width elif 'L' in position: x1 = 0.08 x2 = x1 + width elif 'RR' in position: x2 = 0.97 x1 = x2 - width elif 'R' in position: x2 = 0.92 x1 = x2 - width elif 'x=' in position: x1 = float(re.findall(r"x=(\d\.\d+)", position)[0]) x2 = x1 + width if 'M' in position: if 'T' in position: middle = 0.57 elif 'B' in position: middle = 0.43 else: middle = 0.50 y1 = middle - height / 2 y2 = middle + height / 2 elif 'TT' in position: y2 = 0.97 y1 = y2 - height elif 'T' in position: y2 = 0.92 y1 = y2 - height elif 'BB' in position: y1 = 0.03 y2 = y1 + height elif 'B' in position: y1 = 0.08 y2 = y1 + height elif 'y=' in position: y2 = float(re.findall(r"y=(\d\.\d+)", position)[0]) y1 = y2 - height if x1_user != None: x1 = x1_user x2 = x1 + width if x2_user == None else x2_user if y1_user != None: y1 = y1_user y2 = y1 - height if y2_user == None else y2_user L, R = gPad.GetLeftMargin(), gPad.GetRightMargin() T, B = gPad.GetTopMargin(), gPad.GetBottomMargin() X1, X2 = L + (1 - L - R) * x1, L + ( 1 - L - R) * x2 # convert frame to canvas coordinates Y1, Y2 = B + (1 - T - B) * y1, B + ( 1 - T - B) * y2 # convert frame to canvas coordinates legend = TLegend(X1, Y1, X2, Y2) LOG.verb( "Plot.drawlegend: position=%r, height=%.3f, width=%.3f, (x1,y1,x2,y2)=(%.2f,%.2f,%.2f,%.2f), (X1,Y1,X2,Y2)=(%.2f,%.2f,%.2f,%.2f)" % (position, height, width, x1, y1, x2, y2, X1, Y1, X2, Y2), verbosity, 1) # MARGIN if ncols >= 2: margin = 0.090 / width else: margin = 0.044 / width legend.SetMargin(margin) # STYLE if transparent: legend.SetFillStyle(0) # 0 = transparent else: legend.SetFillColor(0) legend.SetBorderSize(border) legend.SetTextSize(tsize) legend.SetTextFont(headerfont) # bold for title if ncols > 1: legend.SetNColumns(ncols) legend.SetColumnSeparation(colsep) # HEADER if title: legend.SetHeader(title) legend.SetTextFont(42) # no bold for entries # ENTRIES if hists: for hist1, entry1, style1 in columnize(zip(hists, entries, styles), ncols): for entry in entry1.split('\n'): legend.AddEntry(hist1, entry, style1) hist1, style1 = 0, '' for line in texts: legend.AddEntry(0, line, '') if verbosity >= 2: print ">>> Plot.drawlegend: title=%r, texts=%s, latex=%s" % ( title, texts, latex) print ">>> Plot.drawlegend: hists=%s" % (hists) print ">>> Plot.drawlegend: entries=%s" % (entries) print ">>> Plot.drawlegend: styles=%s" % (styles) print ">>> Plot.drawlegend: nlines=%s, len(hists)=%s, len(texts)=%s, ncols=%s, margin=%s" % ( nlines, len(hists), len(texts), ncols, margin) legend.Draw(option) self.legends.append(legend) return legend
#ratio.Divide(hist_N,hist_D) ratio.GetYaxis().SetTitle("(QMisID r_{T})/(QMisID r_{L})") ratio.GetXaxis().SetTitle("p_{T} [GeV]") ratio.GetYaxis().SetRangeUser(0.0, 1.5) c = TCanvas("c1", "Temp", 50, 50, 1000, 800) legend = TLegend(0.2, 0.8, 0.4, 0.85) # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) ) legend.SetHeader("QMisID rate T/L ratio") legend.SetBorderSize(0) # no border legend.SetFillStyle(0) # Legend transparent background legend.SetTextSize(0.04) # Increase entry font size! legend.SetTextFont(42) # Helvetica leg_ATLAS = TLatex() leg_lumi = TLatex() leg_ATLAS.SetTextSize(0.03) leg_ATLAS.SetNDC() leg_lumi.SetTextSize(0.03) leg_lumi.SetNDC() ratio.Draw() legend.Draw() leg_ATLAS.DrawLatex(0.2, 0.75, "#bf{#it{ATLAS}} Work In Progress") leg_lumi.DrawLatex(0.2, 0.7, "#sqrt{s} = 13 TeV, #int L dt = 8.3 fb^{-1}") c.SaveAs("QMisID_Pt_rates_ratio_T_L.png")
def rooFit204(): print ">>> setup model signal components: gaussians..." x = RooRealVar("x","x",0,10) mean = RooRealVar("mean","mean of gaussian",5) sigma1 = RooRealVar("sigma1","width of gaussians",0.5) sigma2 = RooRealVar("sigma2","width of gaussians",1) sig1 = RooGaussian("sig1","Signal component 1",x,mean,sigma1) sig2 = RooGaussian("sig2","Signal component 2",x,mean,sigma2) sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.) sig = RooAddPdf("sig","Signal",RooArgList(sig1,sig2),RooArgList(sig1frac)) print ">>> setup model background components: Chebychev polynomial..." a0 = RooRealVar("a0","a0",0.5,0.,1.) a1 = RooRealVar("a1","a1",-0.2,0.,1.) bkg = RooChebychev("bkg","Background",x,RooArgList(a0,a1)) print ">>> construct extended components with specified range..." # Define signal range in which events counts are to be defined x.setRange("signalRange",5,6) # Associated nsig/nbkg as expected number of events with sig/bkg _in_the_range_ "signalRange" nsig = RooRealVar("nsig","number of signal events in signalRange", 500,0.,10000) nbkg = RooRealVar("nbkg","number of background events in signalRange",500,0,10000) esig = RooExtendPdf("esig","extended signal pdf", sig,nsig,"signalRange") ebkg = RooExtendPdf("ebkg","extended background pdf",bkg,nbkg,"signalRange") print ">>> sum extended components..." # Construct sum of two extended p.d.f. (no coefficients required) model = RooAddPdf("model","(g1+g2)+a",RooArgList(ebkg,esig)) print ">>> sample data, fit model..." data = model.generate(RooArgSet(x),1000) # RooDataSet result = model.fitTo(data,Extended(kTRUE),Save()) # RooFitResult print "\n>>> fit result:" result.Print() print "\n>>> plot everything..." frame1 = x.frame(Title("Fitting a sub range")) # RooPlot data.plotOn(frame1,Binning(50),Name("data")) model.plotOn(frame1,LineColor(kBlue),Name("model")) argset1 = RooArgSet(bkg) model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kBlue),Name("bkg"),Normalization(1.0,RooAbsReal.RelativeExpected)) #model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kRed),Name("bkg2")) print ">>> draw on canvas..." canvas = TCanvas("canvas","canvas",100,100,800,600) legend = TLegend(0.2,0.85,0.4,0.7) legend.SetTextSize(0.032) legend.SetBorderSize(0) legend.SetFillStyle(0) gPad.SetLeftMargin(0.14); gPad.SetRightMargin(0.02) frame1.GetYaxis().SetLabelOffset(0.008) frame1.GetYaxis().SetTitleOffset(1.4) frame1.GetYaxis().SetTitleSize(0.045) frame1.GetXaxis().SetTitleSize(0.045) frame1.Draw() legend.AddEntry("data", "data", 'LEP') legend.AddEntry("model", "fit", 'L') legend.AddEntry("bkg", "background only",'L') #legend.AddEntry("bkg2", "background only (no extended norm)",'L') legend.Draw() canvas.SaveAs("rooFit204.png")
def rooFit202(): print ">>> setup model component: gaussian signals and Chebychev polynomial background..." x = RooRealVar("x", "x", 0, 10) mean = RooRealVar("mean", "mean of gaussian", 5) sigma1 = RooRealVar("sigma1", "width of gaussian", 0.5) sigma2 = RooRealVar("sigma2", "width of gaussian", 1.0) sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1) sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2) a0 = RooRealVar("a0", "a0", 0.5, 0., 1.) a1 = RooRealVar("a1", "a1", -0.2, 0., 1.) bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1)) # Sum the signal components into a composite signal p.d.f. sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.) sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2), RooArgList(sig1frac)) print ">>>\n>>> METHOD 1" print ">>> construct extended composite model..." # Sum the composite signal and background into an extended pdf nsig*sig+nbkg*bkg nsig = RooRealVar("nsig", "number of signal events", 500, 0., 10000) nbkg = RooRealVar("nbkg", "number of background events", 500, 0, 10000) model = RooAddPdf("model", "(g1+g2)+a", RooArgList(bkg, sig), RooArgList(nbkg, nsig)) print ">>> sample, fit and plot extended model...\n" # Generate a data sample of expected number events in x from model # nsig + nbkg = model.expectedEvents() # NOTE: since the model predicts a specific number events, one can # omit the requested number of events to be generated # Introduce Poisson fluctuation with Extended(kTRUE) data = model.generate(RooArgSet(x), Extended(kTRUE)) # RooDataSet # Fit model to data, extended ML term automatically included # NOTE: Composite extended pdfs can only be successfully fit if the extended likelihood # term -log(Poisson(Nobs,Nexp)) is included in the minimization because they have # one extra degree of freedom in their parameterization that is constrained by # this extended term. If a pdf is capable of calculating an extended term (i.e. # any extended RooAddPdf), the extended term is AUTOMATICALLY included in the # likelihood calculation. Override this behaviour with Extended(): # Extended(kTRUE) ADD extended likelihood term # Extended(kFALSE) DO NOT ADD extended likelihood #model.fitTo(data,Extended(kTRUE)) model.fitTo(data) print "\n>>> plot data, model and model components..." # Plot data and PDF overlaid, use expected number of events for pdf projection # normalization, rather than observed number of events, data.numEntries() frame1 = x.frame(Title("extended ML fit example")) # RooPlot data.plotOn(frame1, Binning(30), Name("data")) model.plotOn(frame1, Normalization(1.0, RooAbsReal.RelativeExpected), Name("model")) # Overlay the background components of model # NOTE: By default, the pdf is normalized to event count of the last dataset added # to the plot frame. Use "RelativeExpected" to normalize to the expected # event count of the pdf instead argset1 = RooArgSet(bkg) argset2 = RooArgSet(sig1) argset3 = RooArgSet(sig2) argset4 = RooArgSet(bkg, sig2) model.plotOn(frame1, Components(argset1), LineStyle(kDashed), LineColor(kBlue), Normalization(1.0, RooAbsReal.RelativeExpected), Name("bkg")) #model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kBlue), Name("bkg2")) model.plotOn(frame1, Components(argset2), LineStyle(kDotted), LineColor(kMagenta), Normalization(1.0, RooAbsReal.RelativeExpected), Name("sig1")) model.plotOn(frame1, Components(argset3), LineStyle(kDotted), LineColor(kPink), Normalization(1.0, RooAbsReal.RelativeExpected), Name("sig2")) model.plotOn(frame1, Components(argset4), LineStyle(kDashed), LineColor(kAzure - 4), Normalization(1.0, RooAbsReal.RelativeExpected), Name("bkgsig2")) print "\n>>> structure of composite pdf:" model.Print("t") # "tree" mode print "\n>>> parameters:" params = model.getVariables() # RooArgSet params.Print("v") params.Print() print "\n>>> params.find(\"...\").getVal():" print ">>> sigma1 = %.2f" % params.find("sigma1").getVal() print ">>> sigma2 = %.2f" % params.find("sigma2").getVal() print ">>> nsig = %6.2f, sig1frac = %5.2f" % ( params.find("nsig").getVal(), params.find("sig1frac").getVal()) print ">>> nbkg = %6.2f" % params.find("nbkg").getVal() print ">>>\n>>> components:" comps = model.getComponents() # RooArgSet sig = comps.find("sig") # RooAbsArg sigVars = sig.getVariables() # RooArgSet sigVars.Print() print ">>>\n>>> METHOD 2" print ">>> construct extended components first..." # Associated nsig/nbkg as expected number of events with sig/bkg nsig = RooRealVar("nsig", "number of signal events", 500, 0., 10000) nbkg = RooRealVar("nbkg", "number of background events", 500, 0, 10000) esig = RooExtendPdf("esig", "extended signal pdf", sig, nsig) ebkg = RooExtendPdf("ebkg", "extended background pdf", bkg, nbkg) print ">>> sum extended components without coefficients..." # Construct sum of two extended p.d.f. (no coefficients required) model2 = RooAddPdf("model2", "(g1+g2)+a", RooArgList(ebkg, esig)) # METHOD 2 is functionally completely equivalent to METHOD 1. # Its advantage is that the yield parameter is associated to the shape pdf # directly, while in METHOD 1 the association is made after constructing # a RooAddPdf. Also, class RooExtendPdf offers extra functionality to # interpret event counts in a different range. print ">>> plot model..." model2.plotOn(frame1, LineStyle(kDashed), LineColor(kRed), Normalization(1.0, RooAbsReal.RelativeExpected), Name("model2")) print ">>> draw on canvas..." canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600) legend = TLegend(0.2, 0.85, 0.4, 0.65) legend.SetTextSize(0.032) legend.SetBorderSize(0) legend.SetFillStyle(0) gPad.SetLeftMargin(0.14) gPad.SetRightMargin(0.02) frame1.GetYaxis().SetLabelOffset(0.008) frame1.GetYaxis().SetTitleOffset(1.4) frame1.GetYaxis().SetTitleSize(0.045) frame1.GetXaxis().SetTitleSize(0.045) frame1.Draw() legend.AddEntry("data", "data", 'LEP') legend.AddEntry("model", "composite model", 'L') legend.AddEntry("model2", "composite model (method 2)", 'L') legend.AddEntry("bkg", "background only", 'L') #legend.AddEntry("bkg2", "background only (no extended norm)", 'L') legend.AddEntry("sig1", "signal 1", 'L') legend.AddEntry("sig2", "signal 2", 'L') legend.AddEntry("bkgsig2", "background + signal 2", 'L') legend.Draw() canvas.SaveAs("rooFit202.png")
def plot_hist(histlist, labellist, norm, log, overflow, filename, options, scaling=[]): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if len(scaling) > 1 and scaling[1] == 0: scaling = [] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): entries = histlist[i].GetEntries() mean = histlist[i].GetMean() histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) nbins = histlist[i].GetNbinsX() legend.AddEntry( histlist[i], "#splitline{" + labellist[i] + "}{#splitline{%d entries}{mean=%.2f}}" % (entries, mean), "l") if overflow: histlist[i].SetBinContent( nbins, histlist[i].GetBinContent(nbins) + histlist[i].GetBinContent(nbins + 1)) #overflow histlist[i].SetBinContent(1, histlist[i].GetBinContent(0) + histlist[i].GetBinContent(1)) #underflow if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) xlimit = [ histlist[0].GetBinLowEdge(1), histlist[0].GetBinLowEdge(histlist[0].GetNbinsX()) + histlist[0].GetBinWidth(histlist[0].GetNbinsX()) ] if len(scaling) != 0: top_axis = TGaxis(xlimit[0], maximum * 1.4, xlimit[1], maximum * 1.4, (xlimit[0] - scaling[0]) / scaling[1], (xlimit[1] - scaling[0]) / scaling[1], 510, "-") top_axis.SetTitle("normalized scale") top_axis.SetTickSize(0) top_axis.Draw("SAME") legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def sobWeightedPlot(self, fileName, datasetName, channel, cat, log, mass, tanb, blind, sob=False): # print 'yuta', channel, cat c = TCanvas(fileName, '', 600, 600) c.cd() if log: c.SetLogy(1) f = self.openTFile('Plot_' + fileName + '.root') isEMSM = fileName.find('SM') != -1 and fileName.find('em') != -1 isETSM = fileName.find('SM') != -1 and fileName.find('et') != -1 samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes'] if isEMSM: samples.append('ggH_hww') if isETSM: samples.append('Zee') dataGraph = self.tfileGet(f, 'Graph_from_data_obs') histDict = {} for sample in samples: histDict[sample] = self.tfileGet(f, sample) # print 'check :', sample, histDict[sample].GetSumOfWeights() if not histDict[sample]: print 'Missing histogram', sample, 'in file', 'Plot_' + fileName + '.root' # original for plots xminInset = 60 # 0 xmaxInset = 179 # 340 (for full range) # all range # xminInset = 0 # 0 # xmaxInset = 350 # 340 (for full range) # xminInset = 40 # 0 # xmaxInset = 200 # 340 (for full range) # xminInset = 120 # 0 # xmaxInset = 251 # 340 (for full range) if tanb > 0: xminInset = mass - 100 xmaxInset = mass + 100 if sob: xminInset = 0.4 xmaxInset = 0.7 ztt = histDict['Ztt'] ggH = histDict['ggH'] data = histDict['data_obs'] # This is to fix a weird plotting bug if sob: new_data = TH1F('new_data', '', ggH.GetNbinsX(), 0., 0.7) for i in range(1, new_data.GetNbinsX() + 1): new_data.SetBinContent(i, data.GetBinContent(i)) # print data.GetBinContent(i) data = new_data ggH_hww = 0 zee = 0 signal = histDict['signal'] if isEMSM: ggH_hww = histDict['ggH_hww'] if isETSM: print 'retrieve Zee' zee = histDict['Zee'] tt = histDict['ttbar'] ewk = histDict['EWK'] fakes = histDict['Fakes'] ztt.GetYaxis().SetRangeUser(0., 1.3 * self.findMaxY(data, 0)) if log: ztt.GetYaxis().SetRangeUser(0.001, 50. * self.findMaxY(data, 0)) ztt.GetXaxis().SetTitle('#bf{m_{#tau#tau} [GeV]}') ztt.GetYaxis().SetTitle('#bf{S/B Weighted dN/dm_{#tau#tau} [1/GeV]}') if tanb > 0. and not log: ztt.GetXaxis().SetRangeUser(0., mass + 200.) if sob: ztt.GetXaxis().SetTitle('S/(S+B)') ztt.GetYaxis().SetTitle('Events') ztt.SetTitleOffset(1.3, 'Y') ztt.SetTitleOffset(1., 'X') ztt.GetYaxis().SetNdivisions(505) ztt.SetNdivisions(505) for b in range(0, signal.GetNbinsX() + 2): if signal.GetBinCenter( b) < xminInset or xmaxInset < signal.GetBinCenter(b): signal.SetBinContent(b, 0.) signal.SetBinError(b, 0.) signal.SetName('sig') signal.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal signal.SetFillColor(2) signal.SetLineColor(2) signal.SetLineStyle(1) signal.SetLineWidth(0) ggH.SetBinContent(0, 0) # remove red line on top of y axis in plot ggH.SetBinContent(ggH.GetNbinsX() + 1, 0) ggH.SetBinError(0, 0) ggH.SetBinError(ggH.GetNbinsX() + 1, 0) ggH.SetName('ggH') ggH.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal ggH.SetFillColor(2) ggH.SetLineColor(2) ggH.SetLineStyle(1) ggH.SetLineWidth(0) if isEMSM: errorBand = TH1F(ggH_hww) else: errorBand = TH1F(ztt) errorBand.SetName("errorBand") errorBand.SetMarkerSize(0) errorBand.SetFillColor(1) errorBand.SetFillStyle(3013) errorBand.SetLineWidth(1) legend = TLegend() mssmLabel = '' if tanb > 0: mssmLabel = "tan#beta={tanb}".format(tanb=tanb) higgsLabel = "H(125 GeV)#rightarrow#tau#tau" if tanb > 0: higgsLabel = "H(125 GeV)#rightarrow#tau#tau" legend.SetFillStyle(0) legend.SetFillColor(0) legend.SetBorderSize(0) legend.AddEntry(ggH, higgsLabel, "F") if tanb > 0: legend.AddEntry(TObject(0), mssmLabel, "") legend.AddEntry(data, "observed", "LP") if isEMSM: legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F") legend.AddEntry(ztt, "Z#rightarrow#tau#tau", "F") legend.AddEntry(tt, "t#bar{t}", "F") if isETSM: legend.AddEntry(zee, "Z#rightarrowee", "F") legend.AddEntry(ewk, "electroweak", "F") legend.AddEntry(fakes, "QCD", "F") legend.SetX1NDC(0.63) legend.SetX2NDC(1.05) legend.SetY1NDC(0.25) legend.SetY2NDC(0.46) if log: legend.SetX1NDC(0.18) legend.SetX2NDC(0.60) legend.SetY1NDC(0.17) legend.SetY2NDC(0.38) legend.SetTextSize(.028) legend.SetTextAlign(12) if isEMSM: dataDiff = self.diffPlot(data, ggH_hww, 1) dataDiffGraph = self.diffGraph(dataGraph, ggH_hww, 1) errBand = self.getErrorBand(ggH_hww) else: dataDiff = self.diffPlot(data, ztt, 1) dataDiffGraph = self.diffGraph(dataGraph, ztt, 1) errBand = self.getErrorBand(ztt) errBand.SetFillStyle( 3013 ) # 1001=solid , 3004,3005=diagonal, 3013=hatched official for H.tau tau errBand.SetFillColor(1) errBand.SetLineStyle(1) errBand.SetLineColor(1) errBand.SetLineWidth(1) errBandFrame = TH1F( 'errBandFrame', '', int((xmaxInset - xminInset) / dataDiff.GetBinWidth(1)), xminInset, xmaxInset) errBandFrame.GetYaxis().SetTitle("") errBandFrame.GetYaxis().SetRangeUser( -1.1 * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) # errBandFrame.GetYaxis().SetRangeUser(-1.*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),1.1*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) # good ! # errBandFrame.GetYaxis().SetRangeUser(-0.2*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),0.5*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) print 'Yuta', channel, cat if (channel == 'e#tau_{h}' and cat == 'vbf') or (channel == 'e#tau_{h}' and cat == ''): print 'enter' errBandFrame.GetYaxis().SetRangeUser( -2. * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) errBandFrame.GetYaxis().SetNdivisions(5) errBandFrame.GetYaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetTitle("#bf{m_{#tau#tau} [GeV]} ") errBandFrame.GetXaxis().SetTitleColor(kBlack) errBandFrame.GetXaxis().SetTitleSize(0.07) errBandFrame.GetXaxis().SetTitleOffset(0.85) errBandFrame.GetXaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetNdivisions(506) # errBandFrame.SetNdivisions(505) legendDiff = TLegend() legendDiff.SetFillStyle(0) legendDiff.SetFillColor(0) legendDiff.SetBorderSize(0) legendDiff.AddEntry(signal, higgsLabel, "F") if tanb > 0: legendDiff.AddEntry(TObject(0), mssmLabel, '') # That might not work in python # legendDiff.AddEntry(dataDiff,"Data - Background","LP") legendDiff.AddEntry(dataDiffGraph, "Data - Background", "LEP") legendDiff.AddEntry(errBand, "Bkg. Uncertainty", "F") legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.67) legendDiff.SetY2NDC(0.88) if dataDiff.GetBinContent(dataDiff.FindBin(mass)) < 0.: legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.24) legendDiff.SetY2NDC(0.45) legendDiff.SetTextSize(.045) legendDiff.SetTextAlign(12) padBack = TPad( "padBack", "padBack", 0.57, 0.58, 0.975, 0.956) # TPad must be created after TCanvas otherwise ROOT crashes padBack.SetFillColor(0) pad = TPad( "diff", "diff", 0.45, 0.5, 0.9765, 0.957) # TPad must be created after TCanvas otherwise ROOT crashes pad.cd() pad.SetFillColor(0) pad.SetFillStyle(0) errBandFrame.Draw() errBand.Draw("e2lsame") signal.Draw("histsame") line = TLine() line.DrawLine(xminInset, 0, xmaxInset, 0) # dataDiff.Draw("pe same") if blind == False: self.HideBin(dataDiffGraph) dataDiffGraph.SetMarkerSize(0.5) dataDiffGraph.Draw('pe same') for ibin in range(0, dataDiffGraph.GetN()): x = Double(0.) y = Double(0.) dataDiffGraph.GetPoint(ibin, x, y) print 'Yuta_bin=', ibin, 'x=', x, 'y=', y, dataDiffGraph.GetErrorYhigh( ibin), dataDiffGraph.GetErrorYlow(ibin) print 'Yuta_error=', ibin, errBand.GetXaxis().GetBinCenter( ibin + 1), errBand.GetBinError(ibin + 1) legendDiff.Draw() pad.RedrawAxis() c.cd() ztt.Draw("hist") ggH.Draw("hist same") if isEMSM: ggH_hww.Draw("hist same") ztt.Draw("hist same") errorBand.Draw("e2 same") tt.Draw("hist same") if isETSM: zee.Draw("hist same") ewk.Draw("hist same") fakes.Draw("hist same") # data.Draw("pe same") dataGraph.SetMarkerSize(1) dataGraph.Draw('PE same') if blind == False: self.HideBin(dataGraph) print '#####', data.Integral(), data.GetBinContent(1) legend.Draw() c.RedrawAxis() padBack.Draw() # clear the background axe pad.Draw() if log: c.SetLogy(1) self.CMSPrelim(c, datasetName, channel, cat) savepath = 'figure/Plot_' + fileName if cat == '': savepath = savepath + '.pdf' else: savepath = savepath + '_' + cat + '.pdf' # c.Print('figure/Plot_'+fileName+".eps") # c.Print('figure/Plot_'+fileName+".png") # c.Print('figure/Plot_'+fileName+".pdf") c.Print(savepath) c.Close()
def plot_mjj_bkg(m_low, m_up, n_entries, path2file, filename, path2tree, tree): current_dir = os.getcwd() input_file = TFile.Open(path2file + filename, 'READ') tree = input_file.Get(path2tree + tree) Mjj = np.empty(1, dtype='float32') MjjReg_mjj = np.empty(1, dtype='float32') MjjReg_corr = np.empty(1, dtype='float32') tree.SetBranchAddress('Mjj', Mjj) tree.SetBranchAddress('MjjReg_mjj', MjjReg_mjj) tree.SetBranchAddress('MjjReg_corr', MjjReg_corr) n_points = 100 h_mjj = TH1D('h_reco_mjj', ';m_{jj} [GeV];Events;', n_points, 50, m_up) h_mjj_reg = TH1D('h_reco_mjj_reg', ';m_{jj} [GeV];Events;', n_points, 50, m_up) event_count = 0 for i in range(0, tree.GetEntries()): tree.GetEntry(i) if Mjj[0] <= m_up and Mjj[0] > m_low: h_mjj.Fill(Mjj[0]) h_mjj_reg.Fill(MjjReg_mjj[0]) event_count += 1 if event_count == n_entries: break c1 = TCanvas('c1', 'm_jj', 1200, 900) gStyle.SetOptStat(0) h_mjj_reg.SetLineColor(4) h_mjj_reg.GetXaxis().SetTitle('M_{jj}, [GeV]') h_mjj_reg.GetXaxis().SetRangeUser(m_low, m_up) h_mjj_reg.GetYaxis().SetTitle('') h_mjj.Draw() h_mjj.SetLineColor(2) h_mjj_reg.Draw("same") mjj_leg = TLegend(0.6, 0.7, 0.8, 0.8) mjj_leg.SetBorderSize(0) mjj_leg.AddEntry(h_mjj, 'no regression', 'l') mjj_leg.AddEntry(h_mjj_reg, 'm_{jj} regression', 'l') mjj_leg.SetTextSize(.04) mjj_leg.Draw() mjj_entries = h_mjj.GetEntries() mjj_reg_entries = h_mjj_reg.GetEntries() stat_mjj = TLatex() stat_mjj.SetNDC() stat_mjj.SetTextSize(0.04) stat_mjj.SetTextAlign(13) stat_mjj.SetTextFont(42) stat_mjj.SetTextColor(ROOT.kRed) stat_mjj.DrawLatex(0.15, .60, 'Evt = ' + '{:5.0f}'.format(mjj_entries)) stat_mjj.SetTextColor(ROOT.kBlue) stat_mjj.DrawLatex(0.15, .54, 'Evt = ' + '{:5.0f}'.format(mjj_reg_entries)) # const = 1e3 # res_fitf = TF1('res_fitf','gaus(0)') # res_fitf.SetParameters(const, pref_mean, pref_rms) # h_mjjres.Fit(res_fitf,'','', pref_mean - pref_rms, pref_mean + pref_rms) # # mjjres_reg_mean = res_fitf.GetParameter(1) # mjjres_reg_mean_e = res_fitf.GetParError(1) # mjjres_reg_sigma = res_fitf.GetParameter(2) # mjjres_reg_sigma_e = res_fitf.GetParError(2) # mjjres_reg_Chi2 = res_fitf.GetChisquare() # mjjres_reg_NDF = res_fitf.GetNDF() # # res_fitf = TF1('res_fitf','gaus') # res_fitf.SetParameters(const, pref_mean_reg, pref_mean_reg, pref_rms_reg) # h_mjjres_reg.Fit(res_fitf,'','', pref_mean_reg - pref_rms_reg, pref_mean_reg + pref_rms_reg) # # mjjres_mean = res_fitf.GetParameter(1) # mjjres_mean_e = res_fitf.GetParError(1) # mjjres_sigma = res_fitf.GetParameter(2) # mjjres_sigma_e = res_fitf.GetParError(2) # mjjres_Chi2 = res_fitf.GetChisquare() # mjjres_NDF = res_fitf.GetNDF() # stat_res.DrawLatex(0.65,.70,'#mu = ' + '{:1.3f}#pm{:1.3f}'.format(mjjres_mean, mjjres_mean_e)) # stat_res.SetTextColor(ROOT.kBlue) # stat_res.DrawLatex(0.65,.64,'#mu = ' + '{:1.3f}#pm{:1.3f}'.format(mjjres_reg_mean, mjjres_reg_mean_e)) # stat_res.SetTextColor(ROOT.kRed) # stat_res.DrawLatex(0.65,.58,'#sigma = ' + '{:1.3f}#pm{:1.3f}'.format(mjjres_sigma, mjjres_sigma_e)) # stat_res.SetTextColor(ROOT.kBlue) # stat_res.DrawLatex(0.65,.52,'#sigma = ' + '{:1.3f}#pm{:1.3f}'.format(mjjres_reg_sigma, mjjres_reg_sigma_e)) # stat_res.SetTextColor(ROOT.kRed) # stat_res.DrawLatex(0.65,.46,'#chi^{2}/NDF = ' + '{:3.1f}/{:2.0f}'.format(mjjres_Chi2,mjjres_NDF)) # stat_res.SetTextColor(ROOT.kBlue) # stat_res.DrawLatex(0.65,.40,'#chi^{2}/NDF = ' + '{:3.1f}/{:2.0f}'.format(mjjres_reg_Chi2,mjjres_reg_NDF)) text = input()
def __applyThresholdCorrection( self, refValue, sgn_hist2D, bkg_hist2D, partition_name, output_name, **kwargs): legend_position = retrieve_kw( kwargs, 'legend_position', (0.36,0.20,0.66,0.40)) useNoActivationFunctionInTheLastLayer=retrieve_kw(kwargs,'useNoActivationFunctionInTheLastLayer',False) xname = retrieve_kw( kwargs, 'xname', 'n_{vtx}' ) draw = retrieve_kw( kwargs, 'draw', False) limits = retrieve_kw( kwargs, 'limits', [0,10,20]) dovertical = retrieve_kw( kwargs, 'dovertical' , False) mumin = limits[0]; mumax=limits[-1] mubins = mumax-mumin from TrigEgammaDevelopments.helper.util import * sgn_hist2D = copy2DRegion(sgn_hist2D,1000,-12,7,mubins,mumin,mumax) bkg_hist2D = copy2DRegion(bkg_hist2D,1000,-12,7,mubins,mumin,mumax) from copy import deepcopy refValue_requested = refValue false_alarm = 1.0 false_alarm_limit = 0.20 while false_alarm > false_alarm_limit: # Calculate the original threshold b0, error = find_threshold(sgn_hist2D.ProjectionX(), refValue ) # Take eff points using uncorrection threshold discr_points, nvtx_points, error_points = calculate_dependent_discr_points(sgn_hist2D , refValue ) # Calculate eff without correction sgn_histNum, sgn_histDen, sgn_histEff, det0 = calculate_efficiency(sgn_hist2D, refValue, b0, 0, doCorrection=False) # Generate correction parameters and produce fixed plots sgn_histNum_corr, sgn_histDen_corr, sgn_histEff_corr, detection ,b, a = calculate_efficiency( sgn_hist2D, refValue, b0, 0, limits = limits, doCorretion=True) # Calculate eff without correction bkg_histNum, bkg_histDen, bkg_histEff, _ = calculate_efficiency(bkg_hist2D, refValue, b0, 0, doCorrection=False) # Calculate eff using the correction from signal bkg_histNum_corr, bkg_histDen_corr, bkg_histEff_corr, false_alarm = calculate_efficiency(bkg_hist2D, refValue, b, a, doCorrection=False) if false_alarm > false_alarm_limit: refValue-=0.025 # To np.array discr_points = np.array(discr_points) # Plot correction if draw: # Retrieve some usefull information y_max = sgn_hist2D.GetYaxis().GetXmax() y_min = sgn_hist2D.GetYaxis().GetXmin() x_min = y_min; x_max = y_max from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine from ROOT import TGraphErrors,TF1 gStyle.SetPalette(107) if dovertical: canvas = TCanvas('canvas','canvas',1600,2000) canvas.Divide(2,3) else: canvas = TCanvas('canvas','canvas',2800,1600) canvas.Divide(3,2) pad1= canvas.cd(1) sgn_histEff.SetTitle('Signal Efficiency in: '+partition_name) sgn_histEff.SetLineColor(kRed) sgn_histEff.SetMarkerColor(kRed) sgn_histEff.GetYaxis().SetTitle('#epsilon('+xname+')') sgn_histEff.GetXaxis().SetTitle(xname) sgn_histEff.GetYaxis().SetRangeUser( 0.6, 1.1 ) sgn_histEff.Draw() sgn_histEff_corr.SetLineColor(kBlack) sgn_histEff_corr.SetMarkerColor(kBlack) sgn_histEff_corr.Draw('sames') l0 = TLine(x_min,refValue_requested,x_max,refValue_requested) l0.SetLineColor(kBlack) l0.Draw() l1 = TLine(x_min,refValue,x_max,refValue) l1.SetLineColor(kBlack) l1.SetLineStyle(9) l1.Draw() leg1 = TLegend(legend_position[0],legend_position[1], legend_position[2],legend_position[3]) setLegend1(leg1) leg1.SetHeader('Signal efficiency in '+partition_name) leg1.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' ) lg1 = leg1.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' ) lg1.SetTextColor(kRed) leg1.AddEntry(l1,('Reference: %1.3f')%(refValue) ,'l') leg1.SetTextSize(0.03) leg1.SetBorderSize(0) leg1.Draw() atlas_template(pad1,**kwargs) pad2 = canvas.cd(2) if dovertical else canvas.cd(4) bkg_histEff.SetTitle('Background rejection in: '+partition_name) bkg_histEff.SetLineColor(kRed) bkg_histEff.SetMarkerColor(kRed) bkg_histEff.GetYaxis().SetTitle('#epsilon('+xname+')') bkg_histEff.GetXaxis().SetTitle(xname) bkg_histEff.Draw() bkg_histEff_corr.SetLineColor(kBlack) bkg_histEff_corr.SetMarkerColor(kBlack) bkg_histEff_corr.Draw('sames') l0.Draw() l1.Draw() leg2 = TLegend(legend_position[0],legend_position[1]+0.4, legend_position[2],legend_position[3]+0.4) setLegend1(leg2) leg2.SetHeader('Background rejection in '+partition_name) leg2.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' ) lg2 = leg2.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' ) lg2.SetTextColor(kRed) leg2.SetTextSize(0.03) leg2.SetBorderSize(0) leg2.Draw() atlas_template(pad2,**kwargs) pad3 = canvas.cd(3) if dovertical else canvas.cd(2) sgn_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name) sgn_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)') sgn_hist2D.GetYaxis().SetTitle(xname) sgn_hist2D.GetZaxis().SetTitle('') if not useNoActivationFunctionInTheLastLayer: sgn_hist2D.SetAxisRange(-1,1, 'X' ) sgn_hist2D.Draw('colz') pad3.SetLogz() # Add points g1 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape)) g1.SetLineWidth(1) g1.SetLineColor(kBlue) g1.SetMarkerColor(kBlue) g1.Draw("P same") # Old threshold line l2 = TLine(b0,y_min,b0,y_max) l2.SetLineColor(kRed) l2.SetLineWidth(2) l2.Draw() # New threshold line l3 = TLine(b,y_min, a*y_max+b, y_max) l3.SetLineColor(kBlack) l3.SetLineWidth(2) l3.Draw() atlas_template(pad3,**kwargs) pad4 = canvas.cd(4) if dovertical else canvas.cd(5) bkg_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name) bkg_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)') bkg_hist2D.GetYaxis().SetTitle(xname) bkg_hist2D.GetZaxis().SetTitle('') if not useNoActivationFunctionInTheLastLayer: bkg_hist2D.SetAxisRange(-1,1, 'X' ) #sgn_hist2D.SetAxisRange(b+y_max*a-0.2,1, 'X' ) bkg_hist2D.Draw('colz') pad4.SetLogz() # Add points g2 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape)) g2.SetLineWidth(1) g2.SetLineColor(kBlue) g2.SetMarkerColor(kBlue) g2.Draw("P same") # Old threshold line l4 = TLine(b0,y_min,b0,y_max) l4.SetLineColor(kRed) l4.SetLineWidth(2) l4.Draw() # New threshold line l5 = TLine(b,y_min, a*y_max+b, y_max) l5.SetLineColor(kBlack) l5.SetLineWidth(2) l5.Draw() atlas_template(pad4,**kwargs) from ROOT import TH1D, kAzure from TrigEgammaDevelopments.plots import AutoFixAxes pad5 = canvas.cd(5) if dovertical else canvas.cd(3) #pad5.SetLogy() h5 = TH1D(sgn_hist2D.ProjectionX()) h6 = TH1D(bkg_hist2D.ProjectionX()) if max(h5.GetMaximum(),h6.GetMaximum()) > 10*(min(h5.GetMaximum(),h6.GetMaximum())): pad5.SetLogy() h5.Rebin(10) h6.Rebin(10) h5.SetLineColor(kAzure+6) h5.SetFillColor(kAzure+6) h6.SetLineColor(kRed-7) h5.Draw() h6.Draw('sames') AutoFixAxes(pad5,False,False,1.5) atlas_template(pad5,**kwargs) pad6 = canvas.cd(6) #pad6.SetLogy() h7 = TH1D(bkg_hist2D.ProjectionX()) h8 = TH1D(sgn_hist2D.ProjectionX()) if max(h7.GetMaximum(),h8.GetMaximum()) > 10*(min(h7.GetMaximum(),h8.GetMaximum())): pad6.SetLogy() h7.Rebin(10) h8.Rebin(10) h7.SetLineColor(kRed-7) h7.SetFillColor(kRed-7) h8.SetLineColor(kAzure+6) h7.Draw() h8.Draw('sames') AutoFixAxes(pad6,False,False,1.5) atlas_template(pad6,**kwargs) canvas.SaveAs(output_name+'.pdf') return b,a,b0
class Canvas: 'Common base class for all Samples' def __init__(self, name, _format, x1, y1, x2, y2, c, ww=0, hh=0): self.name = name self.format = _format self.plotNames = [name + "." + i for i in _format.split(',')] self.plotNamesLog = [name + "_log." + i for i in _format.split(',')] self.myCanvas = TCanvas(name, name) if not ww else TCanvas( name, name, ww, hh) self.ToDraw = [] self.orderForLegend = [] self.histos = [] self.lines = [] self.arrows = [] self.latexs = [] self.bands = [] self.options = [] self.labels = [] self.labelsOption = [] self.myLegend = TLegend(x1, y1, x2, y2) self.myLegend.SetFillStyle(0) self.myLegend.SetTextFont(42) self.myLegend.SetTextSize(0.03) self.myLegend.SetLineWidth(0) self.myLegend.SetBorderSize(0) self.myLegend.SetNColumns(c) #r.gStyle.SetPadRightMargin(0.05) def changeLabelsToNames(self): newlabels = [] for il, lab in enumerate(self.labels): print 'changing label %s to %s' % (lab, self.histos[il].GetName()) newlabels.append(self.histos[il].GetName()) self.labels = newlabels def banner(self, isData, lumi, scy, inProgress=False): latex = TLatex() latex.SetNDC() latex.SetTextAngle(0) latex.SetTextColor(r.kBlack) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.06) if not scy: latex.DrawLatex(0.25, 0.93, "#bf{CMS}") else: latex.DrawLatex(0.34, 0.93, "#bf{CMS}") latexb = TLatex() latexb.SetNDC() latexb.SetTextAngle(0) latexb.SetTextColor(r.kBlack) latexb.SetTextFont(42) latexb.SetTextAlign(31) latexb.SetTextSize(0.04) if (isData): if not scy: latexb.DrawLatex(0.43, 0.93, "#it{Preliminary}") else: latexb.DrawLatex(0.52, 0.93, "#it{Preliminary}") else: if not inProgress: if not scy: latexb.DrawLatex(0.43, 0.93, "#it{Simulation}") else: latexb.DrawLatex(0.52, 0.93, "#it{Simulation}") else: if not scy: latexb.DrawLatex(0.54, 0.93, "#it{Work in progress}") else: latexb.DrawLatex(0.63, 0.93, "#it{Work in progress}") text_lumi = '' #if isData: # text_lumi = str(lumi)+" fb^{-1} (13 TeV)" if lumi: text_lumi = str(lumi) + " fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC() latexc.SetTextAngle(0) latexc.SetTextColor(r.kBlack) latexc.SetTextFont(42) latexc.SetTextAlign(31) latexc.SetTextSize(0.04) latexc.DrawLatex(0.90, 0.93, text_lumi) def banner2(self, isData, lumi, scy=False): latex = TLatex() latex.SetNDC() latex.SetTextAngle(0) latex.SetTextColor(r.kBlack) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.06) latex.DrawLatex(0.23, 0.93, "#bf{CMS}") latexb = TLatex() latexb.SetNDC() latexb.SetTextAngle(0) latexb.SetTextColor(r.kBlack) latexb.SetTextFont(42) latexb.SetTextAlign(31) latexb.SetTextSize(0.04) #if(isData): latexb.DrawLatex(0.38, 0.93, "#it{Preliminary}") #else: # latexb.DrawLatex(0.38, 0.93, "#it{Simulation}") text_lumi = str(lumi) + " fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC() latexc.SetTextAngle(0) latexc.SetTextColor(r.kBlack) latexc.SetTextFont(42) latexc.SetTextAlign(31) latexc.SetTextSize(0.05) if lumi != '': latexc.DrawLatex(0.90, 0.93, text_lumi) def banner3(self, isData, lumi): latex = TLatex() latex.SetNDC() latex.SetTextAngle(0) latex.SetTextColor(r.kBlack) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.07) latex.DrawLatex(0.1, 1.22, "#bf{CMS}") latexb = TLatex() latexb.SetNDC() latexb.SetTextAngle(0) latexb.SetTextColor(r.kBlack) latexb.SetTextFont(42) latexb.SetTextAlign(31) latexb.SetTextSize(0.05) #if(isData): # latexb.DrawLatex(0.34, 1.22, "#it{Preliminary}") #else: # latexb.DrawLatex(0.34, 1.22, "#it{Simulation}") text_lumi = str(lumi) + " fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC() latexc.SetTextAngle(0) latexc.SetTextColor(r.kBlack) latexc.SetTextFont(42) latexc.SetTextAlign(31) latexc.SetTextSize(0.05) def addBand(self, x1, y1, x2, y2, color, opacity): grshade = TGraph(4) grshade.SetPoint(0, x1, y1) grshade.SetPoint(1, x2, y1) grshade.SetPoint(2, x2, y2) grshade.SetPoint(3, x1, y2) #grshade.SetFillStyle(3001) grshade.SetFillColorAlpha(color, opacity) self.bands.append(grshade) def addLine(self, x1, y1, x2, y2, color, thickness=0.): line = TLine(x1, y1, x2, y2) line.SetLineColor(color) line.SetLineStyle(2) if thickness: line.SetLineWidth(thickness) self.lines.append(line) def addArrow(self, x1, y1, x2, y2, color, option, thickness=0.): arrow = TArrow(x1, y1, x2, y2, 0.05, option) arrow.SetLineColor(color) if thickness: arrow.SetLineWidth(thickness) self.arrows.append(arrow) def addLatex(self, x1, y1, text, font=42, size=0.04, align=11, color=r.kBlack): lat = [x1, y1, text, font, size, align, color] self.latexs.append(lat) def makeOFHisto(self, histo): nbinsx = histo.GetNbinsX() xmin = histo.GetXaxis().GetXmin() xmax = histo.GetXaxis().GetXmax() newhisto = r.TH1F(histo.GetName() + '_withOFBin', histo.GetTitle() + '_withOFBin', nbinsx + 1, xmin, xmax + (xmax - xmin) / nbinsx) newhisto.Sumw2() newhisto.SetMarkerColor(histo.GetMarkerColor()) newhisto.SetMarkerStyle(histo.GetMarkerStyle()) newhisto.SetMarkerSize(histo.GetMarkerSize()) newhisto.SetLineColor(histo.GetLineColor()) newhisto.SetLineStyle(histo.GetLineStyle()) newhisto.SetMaximum(histo.GetMaximum()) for i in range(1, nbinsx + 2): newhisto.SetBinContent(i, histo.GetBinContent(i)) newhisto.SetBinError(i, histo.GetBinError(i)) return newhisto def makeRate(self, eff, option): eff.Draw(option) self.myCanvas.Update() _h = eff.GetTotalHistogram() xmax = _h.GetXaxis().GetBinUpEdge(_h.GetNbinsX()) xmin = _h.GetXaxis().GetBinLowEdge(1) _g = eff.GetPaintedGraph() _g.SetMinimum(0.0) _g.SetMaximum(1.2) _g.GetXaxis().SetLimits(xmin, xmax) return eff def addHisto(self, h, option, label, labelOption, color, ToDraw, orderForLegend, marker=False, doOF=False, normed=False): if (color != ""): h.SetLineColor(color) h.SetMarkerColor(color) h.SetFillColorAlpha(r.kWhite, 0) if (label == ""): label = h.GetTitle() if normed: h.Scale(1.0 / h.Integral()) if marker: h.SetMarkerStyle(marker) self.histos.append(h if not doOF else self.makeOFHisto(h)) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def addRate(self, eff, option, label, labelOption, color, ToDraw, orderForLegend, marker=False): if (label == ""): label = eff.GetTitle() _eff = copy.deepcopy(eff) if marker: _eff.SetMarkerStyle(marker) else: _eff.SetMarkerStyle(21) if color: _eff.SetMarkerColor(color) _eff.SetLineWidth(2) _eff.SetLineColor(color) _eff.SetMarkerSize(1.0) self.histos.append(_eff) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def add2DRate(self, eff, option): _eff = copy.deepcopy(eff) self.histos.append(_eff) self.options.append(option) self.labels.append('') self.labelsOption.append('') self.ToDraw.append(True) self.orderForLegend.append(0) def addProf(self, prof, option, label, labelOption, color, ToDraw, orderForLegend, marker=False): if (label == ""): label = prof.GetTitle() _prof = copy.deepcopy(prof) if marker: _prof.SetMarkerStyle(marker) else: _prof.SetMarkerStyle(21) _prof.SetMarkerColor(color) _prof.SetLineWidth(2) _prof.SetLineColor(color) _prof.SetMarkerSize(1.0) self.histos.append(_prof) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def addGraph(self, h, option, label, labelOption, color, ToDraw, orderForLegend): if (color != ""): h.SetLineColor(color) h.SetMarkerColor(color) if (label == ""): label = h.GetTitle() self.histos.append(h) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def addStack(self, h, option, ToDraw, orderForLegend): legendCounter = orderForLegend if (orderForLegend < len(self.orderForLegend)): legendCounter = len(self.orderForLegend) self.addHisto(h, option, "", "", "", ToDraw, -1) for h_c in h.GetHists(): self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter) legendCounter = legendCounter + 1 def addPies(self, h, option, ToDraw, orderForLegend): legendCounter = orderForLegend if (orderForLegend < len(self.orderForLegend)): legendCounter = len(self.orderForLegend) self.addHisto(h, option, "", "", "", ToDraw, -1) for h_c in h.GetHists(): self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter) legendCounter = legendCounter + 1 def makeLegend(self): for i in range(0, len(self.histos)): for j in range(0, len(self.orderForLegend)): if (self.orderForLegend[j] != -1 and self.orderForLegend[j] == i): self.myLegend.AddEntry(self.histos[j], self.labels[j], self.labelsOption[j]) def ensurePath(self, _path): ## Enter a while loop to avoid race conditions while True: d = os.path.dirname(_path) try: if not os.path.exists(d): os.makedirs(d) break except OSError, e: if e.errno != os.errno.EEXIST: raise print("Sleeping...") time.sleep(1.0) pass
if i == 0: ts_correctmass[i].Draw("") else: ts_correctmass[i].Draw("same") leg = TLegend(0.7, 0.35, 1, 0.75) leg.SetHeader("Results for diff. top masses") ##NEEDS TO BE CHANGED if i >= 0: leg.AddEntry( ts_correctmass[0], "166v5", "l", ) if i >= 1: leg.AddEntry(ts_correctmass[1], "169v5", "l") if i >= 2: leg.AddEntry(ts_correctmass[2], "172v5", "l") if i >= 3: leg.AddEntry(ts_correctmass[3], "173v5", "l") if i >= 4: leg.AddEntry(ts_correctmass[4], "175v5", "l") if i >= 5: leg.AddEntry(ts_correctmass[5], "178v5", "l") leg.SetTextSize(0.02) leg.Draw() c.cd(4) if i == 0: ts_wrongmass[i].Draw("") else: ts_wrongmass[i].Draw("same") c11.cd() if i == 0: ts_correct[i].Draw("") else: ts_correct[i].Draw("same") leg11 = TLegend(0.7, 0.35, 1, 0.75) leg11.SetHeader("Results for diff. top masses") ##NEEDS TO BE CHANGED if i >= 0: leg11.AddEntry(ts_correct[0], "166v5", "l") if i >= 1: leg11.AddEntry(ts_correct[1], "169v5", "l") if i >= 2: leg11.AddEntry(ts_correct[2], "172v5", "l") if i >= 3: leg11.AddEntry(ts_correct[3], "173v5", "l")
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kYellow + 1) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) smoother = TGraphSmooth("normal") smoother2 = TGraphSmooth("normal") zprimeX = [] zprimeY = [] fileZPrime = open('tools/xsec_SSM.txt', 'r') for entries in fileZPrime: entry = entries.split() zprimeX.append(float(entry[0])) zprimeY.append(float(entry[1]) * 1.3 / 1928) zpX = numpy.array(zprimeX) zpY = numpy.array(zprimeY) GraphZPrime = TGraph(481, zpX, zpY) GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear") GraphZPrimeSmooth.SetLineWidth(3) GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3) GraphZPrimeSmooth.SetLineStyle(2) zprimePsiX = [] zprimePsiY = [] fileZPrimePsi = open('tools/xsec_PSI.txt', 'r') for entries in fileZPrimePsi: entry = entries.split() zprimePsiX.append(float(entry[0])) zprimePsiY.append(float(entry[1]) * 1.3 / 1928) zpPsiX = numpy.array(zprimePsiX) zpPsiY = numpy.array(zprimePsiY) GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY) GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear") GraphZPrimePsiSmooth.SetLineWidth(3) GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue) #Draw the graphs: plotPad.SetLogy() if "Moriond" in output: DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500) else: DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500) DummyGraph.GetXaxis().SetTitle("M [GeV]") if chan == "mumu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)" ) elif chan == "elel": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)" ) elif chan == "elmu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)" ) gStyle.SetOptStat(0) if "Moriond" in output: DummyGraph.GetXaxis().SetRangeUser(120, 4500) else: DummyGraph.GetXaxis().SetRangeUser(400, 4500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(4e-4) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") if not SPIN2: GraphZPrimeSmooth.Draw("lsame") GraphZPrimePsiSmooth.Draw("lsame") cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l") leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0], "l") else: leg.AddEntry(GraphObs, "Observed 95% CL limit", "l") leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f") leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f") leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC") leg1.SetTextSize(0.032) if not SPIN2: leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l") leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") else: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") plLumi.SetTextSize(0.5) plLumi.SetTextFont(42) plLumi.SetFillColor(0) plLumi.SetBorderSize(0) plLumi.Draw() plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetBorderSize(0) plPrelim.Draw() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(400, 1, 4500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") cCL.Update() printPlots(cCL, output)
def DrawRatioPlot(name, xaxis_title, yaxis_title, c, data, MC, MCUp, MCDn, logscale): c.Divide(0, 2, 0, 0) pad1 = c.cd(1) pad1.SetBottomMargin(0.02) pad1.SetTopMargin(0.18) pad1.SetLeftMargin(0.10) if logscale: pad1.SetLogy() max = 0. for bin in range(MC.GetSize() - 2): if (MC.GetBinContent(bin + 1) > max): max = MC.GetBinContent(bin + 1) MC.SetMaximum(1.4 * max) MC.SetFillColor(kOrange + 1) MC.GetYaxis().SetTitle(yaxis_title) MC.Draw("HIST") MC.GetXaxis().SetLabelSize(0) MC.GetYaxis().SetTitleSize(0.07) MC.GetYaxis().SetLabelSize(0.07) MC.GetYaxis().SetTitleOffset(0.7) data.SetLineColor(ROOT.kBlack) data.SetMarkerStyle(20) data.SetMarkerSize(0.6) data.Draw("p E1 X0 SAME") pad2 = c.cd(2) pad2.SetBottomMargin(0.20) pad2.SetTopMargin(0.02) pad2.SetLeftMargin(0.10) Ratio = TH1F("Ratio", "Ratio", MC.GetSize() - 2, MC.GetXaxis().GetXmin(), MC.GetXaxis().GetXmax()) sigma_up = TH1F("sigma_up", "sigma_up", MC.GetSize() - 2, MC.GetXaxis().GetXmin(), MC.GetXaxis().GetXmax()) sigma_dn = TH1F("sigma_dn", "sigma_dn", MC.GetSize() - 2, MC.GetXaxis().GetXmin(), MC.GetXaxis().GetXmax()) for bin in range(MC.GetSize() - 2): if (MC.GetBinContent(bin + 1) == 0): Ratio.SetBinContent(bin + 1, 0) Ratio.SetBinError(bin + 1, 0) sigma_up.SetBinContent(bin + 1, 0) sigma_dn.SetBinContent(bin + 1, 0) else: Ratio.SetBinContent( bin + 1, float(data.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1)) Ratio.SetBinError(bin + 1, 1. / (data.GetBinContent(bin + 1))**0.5) sigma_up.SetBinContent( bin + 1, float(MCUp.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1)) sigma_dn.SetBinContent( bin + 1, float(MCDn.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1)) for bin in range(Ratio.GetSize() - 2): temp = Ratio.GetBinContent(bin + 1) Ratio.SetBinContent(bin + 1, temp - 1) for bin in range(sigma_up.GetSize() - 2): temp = sigma_up.GetBinContent(bin + 1) sigma_up.SetBinContent(bin + 1, temp - 1) for bin in range(sigma_dn.GetSize() - 2): temp = sigma_dn.GetBinContent(bin + 1) sigma_dn.SetBinContent(bin + 1, temp - 1) sigma_up.SetFillColor(ROOT.kGray) sigma_up.SetLineColor(ROOT.kGray) sigma_up.SetMaximum(2.0) sigma_up.SetMinimum(-2.0) sigma_up.GetXaxis().SetTitle(xaxis_title) sigma_up.GetYaxis().SetTitle("(Data/MC)-1") sigma_up.GetYaxis().SetTitleOffset(0.6) sigma_up.Draw("HIST") sigma_up.GetXaxis().SetLabelSize(0.07) sigma_up.GetXaxis().SetTitleSize(0.07) sigma_up.GetYaxis().SetLabelSize(0.07) sigma_up.GetYaxis().SetTitleSize(0.07) sigma_dn.SetFillColor(ROOT.kGray) sigma_dn.SetLineColor(ROOT.kGray) sigma_dn.Draw("HIST SAME") gPad.RedrawAxis() Ratio.SetMarkerStyle(20) Ratio.SetMarkerSize(0.6) Ratio.Draw("p E1 X0 SAME") pad1.cd() leg = TLegend(.75, .45, .95, .75) leg.SetBorderSize(0) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.07) #leg.AddEntry(MC, "Z/t#bar{t} + jets", "f" ) leg.AddEntry(MC, "DY + t#bar{t} MC", "f") leg.AddEntry(data, "Data", "p") leg.AddEntry(sigma_up, "JEC Uncertainty", "f") leg.Draw() #draw CMS and lumi text CMS_lumi.writeExtraText = True CMS_lumi.extraText = "Preliminary" CMS_lumi.lumi_sqrtS = lumiText + " (13 TeV)" CMS_lumi.cmsTextSize = 0.6 CMS_lumi.lumiTextSize = 0.46 CMS_lumi.extraOverCmsTextSize = 0.75 CMS_lumi.relPosX = 0.12 CMS_lumi.CMS_lumi(pad1, 0, 0) c.Update() c.SaveAs(name + ".pdf") c.SaveAs(name + ".png") c.Clear()
def drawTrainingCurve(input, output): hist = pickle.load(open(input, "rb")) tr_acc = hist["acc"] tr_loss = hist["loss"] val_acc = hist["val_acc"] val_loss = hist["val_loss"] epochs = range(len(tr_acc)) c = ROOT.TCanvas("c", "c", 800, 500) ROOT.gStyle.SetOptStat(0) uppad = ROOT.TPad("u", "u", 0., 0.55, 1., 1.) downpad = ROOT.TPad("d", "d", 0., 0., 1., 0.55) uppad.Draw() downpad.Draw() uppad.cd() ROOT.gPad.SetMargin(0.15, 0.05, 0.02, 0.15) ROOT.gPad.SetGrid(1, 1) ROOT.gStyle.SetGridColor(13) gr_acc_train = ROOT.TGraph(len(epochs), array('d', epochs), array('d', tr_acc)) gr_acc_train.SetLineColor(2) gr_acc_train.SetLineWidth(2) gr_acc_test = ROOT.TGraph(len(epochs), array('d', epochs), array('d', val_acc)) gr_acc_test.SetLineColor(4) gr_acc_test.SetLineWidth(2) mgup = ROOT.TMultiGraph("mgup", ";number of epochs;accuracy") mgup.Add(gr_acc_train, "l") mgup.Add(gr_acc_test, "l") mgup.Draw("AL") mgup.GetXaxis().SetRangeUser(min(epochs), max(epochs)) mgup.GetXaxis().SetLabelSize(0) mgup.GetYaxis().CenterTitle() mgup.GetYaxis().SetTitleSize(0.12) mgup.GetYaxis().SetTitleOffset(0.5) mgup.GetYaxis().SetLabelSize(0.105) mgup.GetYaxis().SetNdivisions(8) l = TLegend(0.6, 0.15, 0.88, 0.6) l.SetTextSize(0.14) l.AddEntry(gr_acc_train, "training", "l") l.AddEntry(gr_acc_test, "validation", "l") l.Draw("same") downpad.cd() ROOT.gPad.SetMargin(0.15, 0.05, 0.25, 0.02) ROOT.gPad.SetGrid(1, 1) ROOT.gStyle.SetGridColor(13) gr_loss_train = ROOT.TGraph(len(epochs), array('d', epochs), array('d', tr_loss)) gr_loss_train.SetLineColor(2) gr_loss_train.SetLineWidth(2) gr_loss_test = ROOT.TGraph(len(epochs), array('d', epochs), array('d', val_loss)) gr_loss_test.SetLineColor(4) gr_loss_test.SetLineWidth(2) mgdown = ROOT.TMultiGraph("mgdown", ";number of epochs;loss") mgdown.Add(gr_loss_train, "l") mgdown.Add(gr_loss_test, "l") mgdown.Draw("AL") mgdown.GetXaxis().SetRangeUser(min(epochs), max(epochs)) mgdown.GetXaxis().SetLabelSize(0.085) mgdown.GetXaxis().SetTitleSize(0.11) mgdown.GetXaxis().SetTitleOffset(0.9) mgdown.GetXaxis().CenterTitle() mgdown.GetYaxis().CenterTitle() mgdown.GetYaxis().SetTitleSize(0.11) mgdown.GetYaxis().SetTitleOffset(0.55) mgdown.GetYaxis().SetLabelSize(0.085) mgdown.GetYaxis().SetNdivisions(8) c.SaveAs(output)
def doMCFit(inputfile_name, mass_chib, cuts, output_name='ChiB', plotTitle="#Chi_{b}", fittedVariable='qValue', returnOnlyFitResult=False, useOtherSignalParametrization=False, drawPulls=False, legendOnPlot=True): mass_error = 0.15 print "Creating DataSet from file " + str(inputfile_name) dataSet = makeRooDataset(inputfile_name) if (fittedVariable == 'refittedMass'): x_var = 'rf1S_chib_mass' output_suffix = '_refit' x_axis_label = 'm_{#mu^{+} #mu^{-} #gamma} [GeV]' else: x_var = 'invm1S' output_suffix = '_qValue' x_axis_label = 'm_{#gamma #mu^{+} #mu^{-}} - m_{#mu^{+} #mu^{-}} + m^{PDG}_{#Upsilon} [GeV]' cuts_str = str(cuts) #cuts_str = quality_cut +"photon_pt > 0.5 && abs(photon_eta) < 1.0 && abs(dimuon_rapidity) < 1.0 && dimuon_pt>5.0 && pi0_abs_mass > 0.025 && fabs(dz) < 0.1 "#&& numPrimaryVertices < 16" data = dataSet.reduce(RooFit.Cut(cuts_str)) print 'Creating pdf' x = RooRealVar(x_var, 'm(#mu #mu #gamma) - m(#mu #mu) + m_{#Upsilon}', 9.8, 9.96) #9.7,10.1,'GeV') numBins = 32 # define here so that if I change it also the ndof change accordingly x.setBins(numBins) # Double sided Crystal Ball mean = RooRealVar("#mu", "mean ChiB", mass_chib, mass_chib - mass_error, mass_chib + mass_error, "GeV") sigma = RooRealVar("#sigma", "sigma ChiB", 0.006, 0, 0.2, 'GeV') a1 = RooRealVar('#alpha1', '#alpha1', 0.75, 0, 3) a2 = RooRealVar('#alpha2', '#alpha2', 1.6, 0, 3) n1 = RooRealVar('n1', 'n1', 2.8) #, 1.0,4.0) # 2 per 2S n2 = RooRealVar('n2', 'n2', 3) #, 1.,4.0) # 1 per 2S parameters = RooArgSet(mean, sigma, a1, a2, n1, n2) cb_pdf = My_double_CB('chib', 'chib', x, mean, sigma, a1, n1, a2, n2) #cb_pdf = RooCBShape('chib', 'chib', x, mean, sigma, a1, n1) # ndof floatPars = parameters.selectByAttrib("Constant", ROOT.kFALSE) ndof = numBins - floatPars.getSize() - 1 if useOtherSignalParametrization: # In this case I redefine cb_pdf n1 = RooRealVar('n1', 'n1', 2) cb = RooCBShape('cb1', 'cb1', x, mean, sigma, a1, n1) # I use a2 as the sigma of my second CB a2 = RooRealVar('#alpha2', '#alpha2', 0.5, 0, 3) gauss = RooCBShape('cb2', 'cb2', x, mean, a2, a1, n1) # I use n2 as the ratio of cb1 with respect to cb2 n2 = RooRealVar('n2', 'n2', 0., 1.) cb_pdf = RooAddPdf('chib', 'chib', RooArgList(cb, gauss), RooArgList(n2)) #cb_pdf = cb print 'Fitting to data' fit_region = x.setRange("fit_region", 9.8, 9.96) result = cb_pdf.fitTo(data, RooFit.Save(), RooFit.Range("fit_region")) # a1_val = a1.getVal() # a2_val = a2.getVal() # a1 = RooRealVar('#alpha1', '#alpha1', a1_val) # a2 = RooRealVar('#alpha2', '#alpha2', a2_val) # n1 = RooRealVar('n1', 'n1', 1.7,1.0,5.) # n2 = RooRealVar('n2', 'n2', 1.7,0.,4.) # cb_pdf = My_double_CB('chib', 'chib', x, mean, sigma, a1, n1, a2, n2) # result = cb_pdf.fitTo(data, RooFit.Save()) if returnOnlyFitResult: return result # define frame frame = x.frame() frame.SetNameTitle("fit_resonance", "Fit Resonanace") frame.GetXaxis().SetTitle(x_axis_label) frame.GetYaxis().SetTitle("Events/5 MeV ") frame.GetXaxis().SetTitleSize(0.04) frame.GetYaxis().SetTitleSize(0.04) frame.GetXaxis().SetTitleOffset(1.1) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.SetLineWidth(1) frame.SetTitle(plotTitle) # plot things on frame data.plotOn(frame, RooFit.MarkerSize(0.7)) cb_pdf.plotOn(frame, RooFit.LineWidth(2)) # chiSquare legend chi2 = frame.chiSquare() probChi2 = TMath.Prob(chi2 * ndof, ndof) chi2 = round(chi2, 2) probChi2 = round(probChi2, 2) leg = TLegend(0.3, 0, .10, .10) leg.SetBorderSize(0) leg.SetFillStyle(0) cb_pdf.paramOn(frame, RooFit.Layout(0.17, 0.56, 0.93)) leg.AddEntry(0, '#chi^{2} =' + str(chi2), '') leg.AddEntry(0, 'Prob #chi^{2} = ' + str(probChi2), '') leg.SetTextSize(0.04) frame.addObject(leg) if legendOnPlot: legend = TLegend(.08, .5, .55, .7) #legend.SetTextSize(0.04) legend.SetFillStyle(0) legend.SetBorderSize(0) #legend.AddEntry(0,'CMS','') legend.AddEntry( 0, str(cuts.upsilon_pt_lcut) + ' GeV < p_{T}(#Upsilon) < ' + str(cuts.upsilon_pt_hcut) + ' GeV', '') #legend.AddEntry(0,'p_{T}(#Upsilon)<'+str(cuts.upsilon_pt_hcut),'') frame.addObject(legend) title = TLegend(.8, .75, .9, .93) title.SetTextSize(0.15) title.SetFillStyle(0) title.SetBorderSize(0) title.AddEntry(0, plotTitle, '') frame.addObject(title) # Canvas c1 = TCanvas(output_name + output_suffix, output_name + output_suffix) frame.Draw() if drawPulls: #c1=TCanvas(output_name+output_suffix,output_name+output_suffix,700, 625) hpull = frame.pullHist() framePulls = x.frame() framePulls.SetTitle(';;Pulls') framePulls.GetYaxis().SetLabelSize(0.18) framePulls.GetYaxis().SetTitle('Pulls') framePulls.GetYaxis().SetTitleSize(0.18) framePulls.GetYaxis().SetTitleOffset(0.15) framePulls.GetYaxis().SetNdivisions(005) framePulls.GetXaxis().SetLabelSize(0.16) framePulls.GetXaxis().SetTitle('') line0 = TLine(9.8, 0, 9.96, 0) line0.SetLineColor(ROOT.kBlue) line0.SetLineWidth(2) framePulls.addObject(line0) framePulls.addPlotable(hpull, "P") framePulls.SetMaximum(5) framePulls.SetMinimum(-5) pad1 = TPad("pad1", "The pad 80% of the height", 0.0, 0.2, 1.0, 1.0) pad1.cd() frame.Draw() pad2 = TPad("pad2", "The pad 20% of the height", 0.0, 0.01, 1.0, 0.2) pad2.cd() framePulls.Draw() c1.cd() pad1.Draw() pad2.Draw() #c1.SaveAs(output_name+output_suffix+'.png') print 'Chi2 = ' + str(frame.chiSquare()) pdf_parameters = CB_parameters(mean=mean.getVal(), sigma=sigma.getVal(), n1=n1.getVal(), n2=n2.getVal(), a1=a1.getVal(), a2=a2.getVal(), s_mean=mean.getError(), s_sigma=sigma.getError(), s_n1=n1.getError(), s_n2=n2.getError(), s_a1=a1.getError(), s_a2=a2.getError(), chiSquare=frame.chiSquare()) #pdf_parameters.saveToFile("CB_"+output_name+output_suffix+".txt") return pdf_parameters, c1
csign.SetCanvasSize(1500, 1500) csign.SetWindowSize(500, 500) maxplot = 25 if case == "D0pp": maxplot = 120 if case == "Dspp": maxplot = 40 csign.cd(1).DrawFrame(0, 0, 30, maxplot, ";#it{p}_{T} (GeV/#it{c});Significance %s" % name) leg = TLegend(.25, .65, .65, .85) leg.SetBorderSize(0) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) colors = [ kBlack, kRed, kGreen + 2, kBlue, kViolet - 1, kOrange + 2, kAzure + 1, kOrange - 7 ] for imult, iplot in enumerate(plotbinMB): if not iplot: continue signfhistos[imult].SetLineColor(colors[imult % len(colors)]) signfhistos[imult].SetMarkerColor(colors[imult % len(colors)]) signfhistos[imult].SetMarkerStyle(21) signfhistos[imult].Draw("same") legyieldstring = "%.1f #leq %s < %.1f (MB)" % \ (lvar2_binminMB[imult], latexbin2var, lvar2_binmaxMB[imult]) leg.AddEntry(signfhistos[imult], legyieldstring, "LEP")
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) # Some style for i, s in enumerate(data): hist[s].SetMarkerStyle(21) hist[s].SetMarkerSize(1.25) for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(data + back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow # Set Poisson error bars #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work # Poisson error bars for data if poisson: alpha = 1 - 0.6827 hist['data_obs'].SetBinErrorOption(TH1.kPoisson) data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX()) data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle()) data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize()) res_graph = data_graph.Clone() for i in range(hist['data_obs'].GetNbinsX()): N = hist['data_obs'].GetBinContent(i + 1) B = hist['BkgSum'].GetBinContent(i + 1) L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) data_graph.SetPoint( i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) data_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N) res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N / B if not B == 0 and not N == 0 else -1.e99) res_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., (N - L) / B if not B == 0 else -1.e99, (U - N) / B if not B == 0 else -1.e99) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if samples[x]['plot']]) for i, s in enumerate(sign): if 'sublabel' in samples[s]: n += 1 if 'subsublabel' in samples[s]: n += 1 #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9) leg = TLegend(0.68 - 0.05, 0.9 - 0.05 * n, 0.93, 0.9) #DCMS leg.SetTextSize(0.03) #DCMS leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("Signal x-sec=%.0f pb" % (1 * snorm)) if len(data) > 0: leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], samples[s]['label'], "f") for i, s in enumerate(sign): leg.AddEntry(hist[s], samples[s]['label'], "f") # --- Display --- c1 = TCanvas("c1", hist.values()[-1].GetXaxis().GetTitle(), 1000, 800 if ratio else 700) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() #c1.GetPad(bool(ratio)).SetLogx() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if poisson: data_graph.Draw("SAME, PE") elif len(data) > 0: hist['data_obs'].Draw("SAME, PE") for i, s in enumerate(sign): if samples[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) # Determine range if 'data_obs' in hist: bkg.SetMaximum((2.5 if log else 1.2) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min( hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) else: bkg.SetMaximum(bkg.GetMaximum() * (2.5 if log else 1.2)) bkg.SetMinimum(5.e-1 if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) leg.Draw() #drawCMS(LUMI, "Preliminary") #drawRegion(channel) #drawAnalysis("LL") setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1) if ratio: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(2) errLine.SetFillStyle(0) errLine.SetLineColor(2) #L# errLine.SetLineStyle(2) #L# #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if 'data_obs' in hist: res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) if poisson: res_graph.Draw("SAME, PE0") else: res.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawKolmogorov(hist['data_obs'], hist['BkgSum']) else: res = None c1.Update() # return list of objects created by the draw() function return [ c1, bkg, leg, err if ratio else None, errLine if ratio else None, res if ratio else None, data_graph if poisson else None, res_graph if poisson else None ]
gr1.SetLineStyle(1) gr1.SetMarkerColor(3) gr1.SetMarkerStyle(8) gr1.SetLineWidth(2) gr1.SetTitle(";Concentration(1/cm^{3}) ;# of impurities ") gr1.GetHistogram().SetMaximum(30) gr1.GetHistogram().SetMinimum(0) gr1.GetXaxis().SetLimits(math.pow(10, 10 + 0 * 0.5), math.pow(10, 10 + 16 * 0.5)) leg1 = TLegend(0.2, 0.7, 0.5, 0.9) leg1.SetFillColor(0) leg1.SetFillStyle(0) leg1.SetTextSize(0.05) leg1.SetBorderSize(0) leg1.SetTextFont(22) leg1.AddEntry("", "GeIA group", "") leg1.AddEntry("", "Avalanche region:", "") leg1.AddEntry(gr, str(Avalanche_region) + "cm(Square)", "lp") leg1.AddEntry(gr1, str(Avalanche_region1) + "cm(Circle)", "lp") line = TLine( math.pow(10, 15), 0, math.pow(10, 15), Number_of_Atom(Avalanche_region, math.pow(math.pow(10, 15), 0.33))) line1 = TLine( math.pow(10, 16), 0, math.pow(10, 16), Number_of_Atom(Avalanche_region, math.pow(math.pow(10, 16), 0.33))) line3 = TLine(math.pow(10, 15), 0, math.pow(10, 16), 0) line3.SetLineWidth(10)
SipMC[i].GetYaxis().SetLabelFont(43) SipMC[i].GetYaxis().SetLabelSize(15) SipMC[i].GetYaxis().SetTitle("Events") SipMC[i].SetTitle("") gStyle.SetOptStat(0) # legend legend = TLegend(0.74, 0.68, 0.94, 0.87) legend.AddEntry(SipDATA[i], "Data", "p") legend.AddEntry(SipMC[i], "Drell-Yan MC", "f") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() #lower plot pad canvas.cd() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetGridy() pad2.Draw() pad2.cd() #pad2 becomes the current pad #define ratio plot rp = TH1F(SipDATA[i].Clone("rp")) rp.SetLineColor(kBlack) rp.SetMinimum(0.5)
padMain.SetRightMargin(0.05) padMain.SetLeftMargin(0.17) padMain.SetBottomMargin(0.03) padMain.SetTopMargin(0.1) padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25) padRatio.SetRightMargin(0.05) padRatio.SetLeftMargin(0.17) padRatio.SetTopMargin(0.05) padRatio.SetBottomMargin(0.3) padMain.Draw() padRatio.Draw() leg = TLegend(0.65, 0.7, 0.85, 0.87) leg.SetBorderSize(0) leg.SetTextSize(0.027) padMain.cd() h_TopMatchFinal.SetFillColor(821) h_TopMatchFinal.SetLineColor(821) #923 h_TopMatchFinal.GetXaxis().SetTitle("Double b score") h_TopMatchFinal.GetXaxis().SetLabelSize(0) h_TopMatchFinal.GetYaxis().SetTitle("Events/Bin") h_TopMatchFinal.GetYaxis().SetTitleSize(0.05) h_TopMatchFinal.GetYaxis().SetLabelSize(0.05) h_TopMatchFinal.SetMaximum(totalmax) leg.AddEntry(h_TopMatchFinal, "Top (mtch.) (" + frac_match_text + "%)", "f") h_WmatchFinal.SetFillColor(822) h_WmatchFinal.SetLineColor(822)
hVarsSelNorm[f'Pt{ptmin:.0f}_{ptmax:.0f}'] = {} hVarsSelVsPt[f'Pt{ptmin:.0f}_{ptmax:.0f}'] = {} hVarsSelVsML[f'Pt{ptmin:.0f}_{ptmax:.0f}'] = {} ptbinmin = sparseReco['RecoPrompt'].GetAxis(1).FindBin(ptmin * 1.0001) ptbinmax = sparseReco['RecoPrompt'].GetAxis(1).FindBin(ptmax * 0.9999) MLbinmin = sparseReco['RecoPrompt'].GetAxis(13).FindBin(MLmin[iPt] * 1.0001) MLbinmax = sparseReco['RecoPrompt'].GetAxis(13).FindBin(MLmax[iPt] * 0.9999) sparseReco['RecoPrompt'].GetAxis(1).SetRange(ptbinmin, ptbinmax) leg = TLegend(0.18, 0.76, 0.52, 0.89) leg.SetTextSize(0.05) leg.SetFillStyle(0) leg2D = TLegend(0.18, 0.17, 0.52, 0.4) leg2D.SetTextSize(0.05) leg2D.SetFillStyle(0) for iVar, axis in enumerate(topovars): hVars[f'Pt{ptmin:.0f}_{ptmax:.0f}'][ topovars[axis]] = sparseReco['RecoPrompt'].Projection(axis) hVars[f'Pt{ptmin:.0f}_{ptmax:.0f}'][topovars[axis]].SetName( f'hVarsSel_{topovars[axis]}_Pt{ptmin:.0f}_{ptmax:.0f}') SetObjectStyle(hVars[f'Pt{ptmin:.0f}_{ptmax:.0f}'][topovars[axis]], color=kBlue, linealpha=0.25,
class Canvas: 'Common base class for all Samples' def __init__(self, name, _format, x1, y1, x2, y2, c, ww=0, hh=0): self.name = name self.format = _format self.plotNames = [name + "." + i for i in _format.split(',')] self.plotNamesLog = [name + "_log." + i for i in _format.split(',')] self.myCanvas = TCanvas(name, name) if not ww else TCanvas(name, name, ww, hh) self.ToDraw = [] self.orderForLegend = [] self.histos = [] self.lines = [] self.arrows= [] self.latexs= [] self.bands = [] self.options = [] self.labels = [] self.labelsOption = [] self.myLegend = TLegend(x1, y1, x2, y2) self.myLegend.SetFillStyle(0) self.myLegend.SetTextFont(42) self.myLegend.SetTextSize(0.03) self.myLegend.SetLineWidth(0) self.myLegend.SetBorderSize(0) self.myLegend.SetNColumns(c) r.gStyle.SetPadRightMargin(0.05) def changeLabelsToNames(self): newlabels = [] for il,lab in enumerate(self.labels): print 'changing label %s to %s'%(lab, self.histos[il].GetName()) newlabels.append(self.histos[il].GetName()) self.labels = newlabels def banner(self, isData, lumi): latex = TLatex() latex.SetNDC(); latex.SetTextAngle(0); latex.SetTextColor(r.kBlack); latex.SetTextFont(42); latex.SetTextAlign(31); latex.SetTextSize(0.06); latex.DrawLatex(0.25, 0.93, "#bf{CMS}") latexb = TLatex() latexb.SetNDC(); latexb.SetTextAngle(0); latexb.SetTextColor(r.kBlack); latexb.SetTextFont(42); latexb.SetTextAlign(31); latexb.SetTextSize(0.04); if(isData): latexb.DrawLatex(0.44, 0.93, "#it{Preliminary}") else: latexb.DrawLatex(0.44, 0.93, "#it{Simulation}") if lumi != '': text_lumi = str(lumi)+" fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC(); latexc.SetTextAngle(0); latexc.SetTextColor(r.kBlack); latexc.SetTextFont(42); latexc.SetTextAlign(31); latexc.SetTextSize(0.04); latexc.DrawLatex(0.90, 0.93, text_lumi) def banner2(self, isData, lumi): latex = TLatex() latex.SetNDC(); latex.SetTextAngle(0); latex.SetTextColor(r.kBlack); latex.SetTextFont(42); latex.SetTextAlign(31); latex.SetTextSize(0.06); latex.DrawLatex(0.23, 0.93, "#bf{CMS}") latexb = TLatex() latexb.SetNDC(); latexb.SetTextAngle(0); latexb.SetTextColor(r.kBlack); latexb.SetTextFont(42); latexb.SetTextAlign(31); latexb.SetTextSize(0.04); #if(isData): latexb.DrawLatex(0.38, 0.93, "#it{Preliminary}") #else: # latexb.DrawLatex(0.38, 0.93, "#it{Simulation}") text_lumi =str(lumi)+" fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC(); latexc.SetTextAngle(0); latexc.SetTextColor(r.kBlack); latexc.SetTextFont(42); latexc.SetTextAlign(31); latexc.SetTextSize(0.05); latexc.DrawLatex(0.90, 0.93, text_lumi) def banner3(self, isData, lumi): latex = TLatex() latex.SetNDC(); latex.SetTextAngle(0); latex.SetTextColor(r.kBlack); latex.SetTextFont(42); latex.SetTextAlign(31); latex.SetTextSize(0.07); latex.DrawLatex(0.1, 1.22, "#bf{CMS}") latexb = TLatex() latexb.SetNDC(); latexb.SetTextAngle(0); latexb.SetTextColor(r.kBlack); latexb.SetTextFont(42); latexb.SetTextAlign(31); latexb.SetTextSize(0.05); #if(isData): # latexb.DrawLatex(0.34, 1.22, "#it{Preliminary}") #else: # latexb.DrawLatex(0.34, 1.22, "#it{Simulation}") text_lumi = str(lumi) + " fb^{-1} (13 TeV)" latexc = TLatex() latexc.SetNDC(); latexc.SetTextAngle(0); latexc.SetTextColor(r.kBlack); latexc.SetTextFont(42); latexc.SetTextAlign(31); latexc.SetTextSize(0.05); def addBand(self, x1, y1, x2, y2, color, opacity): grshade = TGraph(4) grshade.SetPoint(0,x1,y1) grshade.SetPoint(1,x2,y1) grshade.SetPoint(2,x2,y2) grshade.SetPoint(3,x1,y2) #grshade.SetFillStyle(3001) grshade.SetFillColorAlpha(color, opacity) self.bands.append(grshade) def addLine(self, x1, y1, x2, y2, color, thickness = 0.): line = TLine(x1,y1,x2,y2) line.SetLineColor(color) line.SetLineStyle(2) if thickness: line.SetLineWidth(thickness) self.lines.append(line) def addArrow(self, x1, y1, x2, y2, color, option, thickness = 0.): arrow = TArrow(x1,y1,x2,y2, 0.05, option) arrow.SetLineColor(color) if thickness: arrow.SetLineWidth(thickness) self.arrows.append(arrow) def addLatex(self, x1, y1, text, font=42, size = 0.04): lat = [x1, y1, text, font, size] self.latexs.append(lat) def makeOFHisto(self, histo): nbinsx = histo.GetNbinsX() xmin = histo.GetXaxis().GetXmin(); xmax = histo.GetXaxis().GetXmax(); newhisto = r.TH1F(histo.GetName() +'_withOFBin', histo.GetTitle()+'_withOFBin', nbinsx+1, xmin, xmax+(xmax-xmin)/nbinsx) newhisto.Sumw2() newhisto.SetMarkerColor(histo.GetMarkerColor()) newhisto.SetMarkerStyle(histo.GetMarkerStyle()) newhisto.SetMarkerSize (histo.GetMarkerSize ()) newhisto.SetLineColor(histo.GetLineColor()) newhisto.SetLineStyle(histo.GetLineStyle()) newhisto.SetMaximum(histo.GetMaximum()) for i in range(1,nbinsx+2): newhisto.SetBinContent(i,histo.GetBinContent(i)) newhisto.SetBinError (i,histo.GetBinError (i)) return newhisto def addHisto(self, h, option, label, labelOption, color, ToDraw, orderForLegend, doOF = False): if(color != ""): h.SetLineColor(color) h.SetMarkerColor(color) h.SetFillColorAlpha(r.kWhite, 0) if(label == ""): label = h.GetTitle() self.histos.append(h if not doOF else self.makeOFHisto(h)) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def addGraph(self, h, option, label, labelOption, color, ToDraw, orderForLegend): if(color != ""): h.SetLineColor(color) h.SetMarkerColor(color) if(label == ""): label = h.GetTitle() self.histos.append(h) self.options.append(option) self.labels.append(label) self.labelsOption.append(labelOption) self.ToDraw.append(ToDraw) self.orderForLegend.append(orderForLegend) def addStack(self, h, option, ToDraw, orderForLegend): legendCounter = orderForLegend if(orderForLegend < len(self.orderForLegend)): legendCounter = len(self.orderForLegend) self.addHisto(h, option, "", "", "", ToDraw, -1) for h_c in h.GetHists(): self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter) legendCounter = legendCounter + 1 def addPies(self, h, option, ToDraw, orderForLegend): legendCounter = orderForLegend if(orderForLegend < len(self.orderForLegend)): legendCounter = len(self.orderForLegend) self.addHisto(h, option, "", "", "", ToDraw, -1) for h_c in h.GetHists(): self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter) legendCounter = legendCounter + 1 def makeLegend(self): for i in range(0, len(self.histos)): for j in range(0, len(self.orderForLegend)): if(self.orderForLegend[j] != -1 and self.orderForLegend[j] == i): self.myLegend.AddEntry(self.histos[j], self.labels[j], self.labelsOption[j]) def ensurePath(self, _path): d = os.path.dirname(_path) if not os.path.exists(d): os.makedirs(d) def saveRatio(self, legend, isData, log, lumi, hdata, hMC, r_ymin=0, r_ymax=2, label ="Data/Prediction", outputDir = 'plots/'): self.myCanvas.cd() pad1 = TPad("pad1", "pad1", 0, 0.25, 1, 1.0) pad1.SetBottomMargin(0.12) pad1.Draw() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.25) pad2.SetTopMargin(0.1); pad2.SetBottomMargin(0.3); pad2.Draw(); pad1.cd() if(log): pad1.SetLogy(1) for i in range(0, len(self.histos)): if(self.ToDraw[i] != 0): #self.histos[i].SetMinimum(0.00001) self.histos[i].SetMinimum(0.1) #self.histos[i].SetMinimum(0.0001) #self.histos[i].SetMaximum(0.5) self.histos[i].Draw(self.options[i]) if(legend): self.makeLegend() self.myLegend.SetTextSize(0.035) # Modify the legend size self.myLegend.Draw() for band in self.bands: band.Draw('f') for line in self.lines: line.Draw() for arrow in self.arrows: arrow.Draw() for latex in self.latexs: lat = TLatex() lat.SetNDC() lat.SetTextSize(latex[-1]) lat.SetTextFont(latex[-2]) lat.DrawLatex(latex[0], latex[1], latex[2]) if type(hMC) != list: hMClist = [hMC] else: hMClist = hMC ratios = [] for tmp_hMC in hMClist: ind = hMClist.index(tmp_hMC) tmp_ratio = hdata.Clone(tmp_hMC.GetName()+'_ratio') tmp_ratio.Divide(tmp_hMC) tmp_ratio.SetTitle("") tmp_ratio.GetYaxis().SetRangeUser(r_ymin, r_ymax); tmp_ratio.GetYaxis().SetTitle(label); tmp_ratio.GetYaxis().CenterTitle(); tmp_ratio.GetYaxis().SetLabelSize(0.12); tmp_ratio.GetXaxis().SetLabelSize(0.12); tmp_ratio.GetYaxis().SetTitleOffset(0.3); tmp_ratio.GetYaxis().SetNdivisions(4); tmp_ratio.GetYaxis().SetTitleSize(0.12); tmp_ratio.GetXaxis().SetTitleSize(0.12); tmp_ratio.GetXaxis().SetLabelOffset(0.08); tmp_ratio.GetXaxis().SetTitle(''); tmp_ratio.SetMarkerStyle(tmp_hMC.GetMarkerStyle()); tmp_ratio.SetFillColorAlpha(r.kBlue-3,0.9) tmp_ratio.SetFillStyle(3017) tmp_ratio.SetMarkerColor(r.kBlack); tmp_ratio.SetMarkerSize(0.6); #tmp_ratio.SetMarkerColor(r.kBlack if len(hMClist) == 1 else tmp_hMC.GetMarkerColor()); #tmp_ratio.SetLineColor (r.kBlack if len(hMClist) == 1 else tmp_hMC.GetLineColor ()); tmp_ratio.SetLineColor (tmp_hMC.GetLineColor()); tmp_ratio.SetLineStyle(tmp_hMC.GetLineStyle()) ratios.append(tmp_ratio) xmin = tmp_ratio.GetBinLowEdge(1) xmax = tmp_ratio.GetBinLowEdge(tmp_ratio.GetNbinsX()+1) #tmp_ratio.Draw("E,SAME"); pad2.cd(); for rat in ratios: rat.Draw('PE2,same'); line = TLine(xmin, 1, xmax, 1) line.SetLineColor(r.kGray+2); line.Draw(''); pad1.cd() self.banner2(isData, lumi) if not outputDir[-1] == '/': dirName = outputDir + '/' else: dirName = outputDir for i,plotName in enumerate(self.plotNames): pad1.cd() pad1.SetLogy(0) path = dirName+plotName pathlog = dirName+self.plotNamesLog[i] self.ensurePath(path) self.myCanvas.SaveAs(path) if not '.root' in pathlog: pad1.cd() pad1.SetLogy() self.myCanvas.SaveAs(pathlog) pad1.IsA().Destructor(pad1) pad2.IsA().Destructor(pad2) self.myLegend.IsA().Destructor(self.myLegend) self.myCanvas.IsA().Destructor(self.myCanvas) def save(self, legend, isData, log, lumi, labelx, ymin=0, ymax=0, outputDir = 'plots/', xlog = False): self.myCanvas.cd() if(log): self.myCanvas.GetPad(0).SetLogy(1) if(xlog): self.myCanvas.GetPad(0).SetLogx(1) for i in range(0, len(self.histos)): if(self.ToDraw[i] != 0): if ymin and ymax: self.histos[i].GetYaxis().SetRangeUser(ymin, ymax) self.histos[i].Draw(self.options[i]) ## Draw axis: #self.histos[0].Draw('same axis') for band in self.bands: band.Draw('f') for line in self.lines: line.Draw() for arrow in self.arrows: arrow.Draw() for latex in self.latexs: lat = TLatex() lat.SetNDC() lat.SetTextSize(latex[-1]) lat.SetTextFont(latex[-2]) lat.DrawLatex(latex[0], latex[1], latex[2]) if(legend): self.makeLegend() self.myLegend.Draw() lat = TLatex() lat.SetNDC() lat.SetTextSize(0.05) lat.SetTextFont(42) lat.DrawLatex(0.46, 0.04, labelx) self.banner(isData, lumi) if not outputDir[-1] == '/': dirName = outputDir + '/' else: dirName = outputDir for plotName in self.plotNames: path = dirName+plotName self.ensurePath(path) self.myCanvas.SaveAs(path) self.myLegend.IsA().Destructor(self.myLegend) self.myCanvas.IsA().Destructor(self.myCanvas) def savePie(self, legend, lumi, labelx): cpie = TCanvas("cpie","TPie test",700,700) pad1 = TPad("pad1", "pad1", 0.1, 0.1, 0.75, 0.75) pad1.SetBottomMargin(0.12) pad1.Draw() pad1.cd() colors = [] names = [] vals = [] for i in range(0, len(self.histos)): vals.append(self.histos[i].Integral()) colors.append(self.histos[i].GetLineColor()) names.append(self.histos[i].GetName()) v = array('d', vals) c = array('i', colors) pie4 = TPie("p4","",len(v),v,c); pie4.SetRadius(.45); pie4.SetLabelsOffset(.01); pie4.SetLabelsOffset(100); pie4.SetEntryLineWidth(1,2); pie4.SetEntryLineWidth(2,2); pie4.SetEntryLineWidth(3,2); pie4.SetEntryLineWidth(4,2); pie4.SetEntryLineWidth(5,2); pie4.SetEntryLineWidth(6,2); pie4.SetEntryLineWidth(7,2); pie4.Draw(); self.makeLegend() self.myLegend.Draw() lat = TLatex() lat.SetNDC() lat.SetTextSize(0.06) lat.SetTextFont(42) lat.DrawLatex(0.12, -0.1, "Slepton signal region, "+labelx) self.banner3(True, lumi) for plotName in self.plotNames: path = 'plots/'+plotName #self.ensurePath(path) cpie.SaveAs(path) self.myLegend.IsA().Destructor(self.myLegend)
outHist[i].Scale(BGNormalization / outHist[i].Integral()) print i, outHist[i].GetName(), outHist[i].Integral() outHist[i].SetLineColor(i + 2) outHist[i].SetLineWidth( 2) outHist[i].Draw("same") outName[i]=testFiles[i][:-5] outEst[i]=BGNormalization l = TLegend(0.35, 0.70, 0.7, 0.9, "", "brNDC") l.SetBorderSize(0) l.SetFillColor(0) l.SetTextSize(.03) l.AddEntry(hist_Data, "SS Data ", "p") l.AddEntry(outHist[i], "BG Est.(Shape from Relaxed Isolation)", "lpf") # l.AddEntry(hist_Estimation_ff, "BG Est.(both tau Iso Reverted)", "lpf") l.Draw() #Text in Histogram t = TLatex() t.SetNDC() t.SetTextFont(62) t.SetTextAlign(12) t.SetTextSize(0.03) t.DrawLatex(0.1, .92, "CMS Preliminary 2012") t.DrawLatex(0.45, .92, "#sqrt{s} = 8 TeV, L = 19.8 fb^{-1}") t.DrawLatex(0.77, .92, "lle#tau + ll#mu#tau") #
gComptonPhotMFP.SetPoint(i, hPrimaryEnergy[i].GetMean(), MFPComptonPhot) gComptonPhotMassicCS.SetPoint(i, hPrimaryEnergy[i].GetMean(), massicCSComptonPhot) # plot histograms idx_1 = 3 idx_2 = 10 idx_3 = 28 leg = TLegend(.63, .62, .97, .93) leg.SetBorderSize(0) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) leg.SetHeader("prim. photon energy", "C") leg.AddEntry(hLStep[idx_1], "40 keV") leg.AddEntry(hLStep[idx_2], "110 keV") leg.AddEntry(hLStep[idx_3], "290 keV") #step length histo c1 = TCanvas("c1", "c1", 200, 10, 1200, 500) c1.Divide(2) c1.cd(1) c1.cd(1).SetLogy() hLStep[idx_1].Draw("hist") hLStep[idx_2].Draw("hist,same") hLStep[idx_2].SetLineColor(kBlue) hLStep[idx_3].Draw("hist,same") hLStep[idx_3].SetLineColor(kRed)
matched.SetLineColor(1) matched.SetLineStyle(1) matched.SetLineWidth(3) NOmatched.SetLineColor(2) NOmatched.SetLineStyle(1) NOmatched.SetLineWidth(3) x1 = 0.15 x2 = x1 + 0.24 y2 = 0.90 y1 = 0.79 legend = TLegend(x1, y1, x2, y2) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextSize(0.041) legend.SetTextFont(42) legend.AddEntry(matched, "Signal", 'L') legend.AddEntry(NOmatched, "Background", 'L') #c.SetLogy(0) if variable in ['showlenght', 'maxlayer', 'coreshowlenght']: matched.GetXaxis().SetRangeUser(0.0, 50) NOmatched.GetXaxis().SetRangeUser(0.0, 50) if variable in ['ntc67']: matched.GetXaxis().SetRangeUser(0.0, 40) NOmatched.GetXaxis().SetRangeUser(0.0, 40) if variable in ['ntc90']: