ax.xaxis.label.set_fontsize(12) ax.set_ylabel("Dec") ax.yaxis.label.set_fontsize(12) ax.grid(True) plot_mwd(ras, decs, title="Random dipole directions on Catalogsize " + str(ncat)) plt.show() #plt.show() #plt.savefig('randdirectionsn'+str(ncat)+'.png') histdict = {} histcdict = {} legend = TLegend(0.1, 0.7, 0.48, 0.9) for ncat in ncats: histdict[ncat] = makevhist(ncat) for ncat in ncatc: histcdict[ncat] = makevhist(ncat, True) #legend.AddEntry(histdict[ncat], "Catalog size"+str(ncat)) for ncat in ncats: plt.hist(histdict[ncat], 20, normed=1, facecolor=color[ncat], label='HemiSphere : catalog size ' + str(ncat), alpha=0.5) for ncat in ncatc:
hs.Add(h_prompt) hs.Add(h_fake) gr_data_fit.SetMarkerStyle(20) gr_data_fit.SetMarkerSize(1.0) gr_data_fit.GetXaxis().SetTitle("m_{T} (GeV)") gr_data_fit.GetYaxis().SetTitle("N_{events}/bin") gr_data_fit.SetMaximum(1.2 * h_total_fit.GetMaximum()) gr_data_fit.Draw("AP") hs.Draw("HISTsame") gr_err.Draw('E2SAME') gr_data_fit.Draw("psame") ROOT.gPad.RedrawAxis() leg = TLegend(0.6, 0.65, 0.9, 0.9) leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetLineColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetTextFont(42) leg.AddEntry(gr_data_fit, "data", "lp") leg.AddEntry(h_fake, "Fake", "f") leg.AddEntry(h_prompt, "Prompt", "f") leg.AddEntry(gr_err, 'unc', 'F') leg.Draw() if not os.path.exists('plots'): os.makedirs('plots')
hVarsVsPt['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} hVarsVsML['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} hVarsSel['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} hVarsSelNorm['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} hVarsSelVsPt['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} hVarsSelVsML['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)] = {} 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['Pt{:.0f}_{:.0f}'.format( ptmin, ptmax)][topovars[axis]] = sparseReco['RecoPrompt'].Projection(axis) hVars['Pt{:.0f}_{:.0f}'.format(ptmin, ptmax)][topovars[axis]].SetName( 'hVarsSel_{:s}_Pt{:.0f}_{:.0f}'.format(topovars[axis], ptmin, ptmax)) SetObjectStyle(hVars['Pt{:.0f}_{:.0f}'.format( ptmin, ptmax)][topovars[axis]], color=kBlue, linealpha=0.25, fillalpha=0.25, markeralpha=1, markerstyle=kFullCircle, markersize=0.5, linewidth=1)
def plotSysts(): inputfile = TFile(filename,"read") if inputfile.IsZombie(): print("inputfile is Zombie") sys.exit() # loop over samples for sample in sampleName: # loop over features for feature, values in features.items(): # get nominal histograms hist_nom_name = sample+"_"+feature if not inputfile.GetListOfKeys().Contains(hist_nom_name): print ( "%s doesn't have histogram %s"%(filename, hist_nom_name)) continue hist_nom = inputfile.Get(hist_nom_name) hist_nom.SetFillColor(0) hist_nom.SetLineColor(Color["nominal"]) hist_nom.SetMarkerColor(Color["nominal"]) h_ratio = createRatio(hist_nom, hist_nom, values["xlabel"],normalization) # loop over variations for syst in systematics: file = open("%s%s_%s_%s_isNorm%s_wtStat%s.txt"%(outputdir,plotname,hist_nom_name,syst,normalization,showStats),"w") file.write(" sample %s, feature %s, nominal yield %f\n"%(sample, feature, hist_nom.Integral())) if syst=="nominal": continue # set up legend legend = TLegend(0.2,0.6,0.7,0.88) legend.SetHeader("CMS preliminary %i %s"%(year,region)) #legend.SetNColumns(3) legend.SetBorderSize(0) legend.AddEntry(hist_nom,hist_nom_name,"l") c, pad1, pad2 = createCanvasPads() hist_vars = [] hist_ratio_vars = [] for var in upDown: hist_name = sample+"_"+feature+"_"+syst+var if not inputfile.GetListOfKeys().Contains(hist_name): print ( "%s doesn't have histogram %s"%(filename, hist_name)) continue hist_var = inputfile.Get(hist_name) hist_var.SetFillColor(0) hist_var.SetLineColor(Color[var]) hist_var.SetMarkerColor(Color[var]) hist_vars.append(hist_var) file.write(" sample %s, feature %s, %s%s yield %f \n"%(sample, feature, syst, var, hist_var.Integral())) h_ratio_var = createRatio(hist_var, hist_nom,values["xlabel"], normalization) hist_ratio_vars.append(h_ratio_var) legend.AddEntry(h_ratio_var,hist_name,"l") # draw everything pad1.cd() pad1.SetGridx() pad1.SetGridy() # set bounds maximum=0 for hist in hist_vars: if normalization: hist.Scale(1./hist.Integral()) if hist.GetMaximum()>maximum: maximum = hist.GetMaximum() upperbound = 1.8*maximum lowerbound = -maximum/40. Y_name = "Events" if normalization: hist_nom.Scale(1./hist_nom.Integral()) Y_name = " Unit " if showStats: hist_nom.SetStats(1) hist_nom.SetMaximum(upperbound) hist_nom.SetMinimum(lowerbound) # Adjust y-axis settings y = hist_nom.GetYaxis() y.SetTitleSize(25) y.SetTitleFont(43) y.SetTitleOffset(1.55) y.SetLabelFont(43) y.SetLabelSize(20) y.SetTitle(Y_name) # Adjust x-axis settings x = hist_nom.GetXaxis() x.SetTitleSize(25) x.SetTitleFont(43) x.SetTitleOffset(1.55) x.SetLabelFont(43) x.SetLabelSize(20) x.SetTitle(values["xlabel"]) hist_nom.SetTitle("#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} %i at %.2f fb^{-1}(13TeV)}"%(year,luminosity[year])) hist_nom.Draw("HIST") for hist in hist_vars: hist.Draw("HISTsame") legend.Draw("same") pad2.cd() pad2.SetGridx() pad2.SetGridy() bins = h_ratio.GetNbinsX() LowEdge = h_ratio.GetBinLowEdge(1) HighEdge = h_ratio.GetBinLowEdge(bins+1) line = TLine(LowEdge,1,HighEdge,1) line.SetLineColor(kBlack) for i in range(len(hist_ratio_vars)): if i==0: hist_ratio_vars[i].Draw("hist") hist_ratio_vars[i].SetMinimum(0.5) hist_ratio_vars[i].SetMaximum(1.5) else: hist_ratio_vars[i].Draw("histsame") line.Draw("same") c.SaveAs("%s%s_%s_%s_isNorm%s_wtStat%s.png"%(outputdir,plotname,hist_nom_name,syst,normalization,showStats)) file.close()
h2_3 = h1_3.Get("Method_BDT") h3_3 = h2_3.Get("BDT") h4_3 = h3_3.Get("MVA_BDT_rejBvsS") #======================# h4_1.SetLineColor(1) h4_2.SetLineColor(7) h4_3.SetLineColor(2) gStyle.SetOptStat(0) h4_1.GetXaxis().SetRangeUser(0, 1) h4_1.GetYaxis().SetRangeUser(0, 1.1) h4_1.SetYTitle("1-Background efficiency") leg = TLegend(0.1, 0.3, 0.4, 0.5) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetBorderSize(0) leg.SetTextFont(22) leg.AddEntry("", str(Energies[i]) + "TeV", "") leg.AddEntry(h4_1, "TMVA(BDT)_dR_PT_ECAL", "l") leg.AddEntry(h4_2, "TMVA(BDT)_dR_PT_T_ECAL", "l") leg.AddEntry(h4_3, "TMVA(BDT)_dR_PT_track", "l") h4_1.Draw("L") h4_2.Draw("Lsame") h4_3.Draw("Lsame") leg.Draw()
funcRatio1 = GraphRatio1.GetFunction("pol3") funcRatio2 = GraphRatio2.GetFunction("pol3") funcRatio3 = GraphRatio3.GetFunction("pol3") funcRatio4 = GraphRatio4.GetFunction("pol3") Graph1 = histo(Histo1) Graph2 = histo(Histo2) Graph3 = histo(Histo3) Graph4 = histo(Histo4) Graph5 = histo(Histo5) Graph6 = histo(Histo6) Graph7 = histo(Histo7) Graph8 = histo(Histo8) legend2 = TLegend(.65, .60, .89, .87) legend2.SetBorderSize(0) legend2.SetFillColor(0) legend2.SetFillStyle(0) legend2.SetTextFont(42) legend2.SetTextSize(0.035) legend2.AddEntry(Graph1, "1.05 GeV nominal", "LP") legend2.AddEntry(Graph3, "2.3 GeV nominal", "LP") legend2.AddEntry(Graph5, "4.4 GeV nominal", "LP") legend2.AddEntry(Graph7, "6.6 GeV nominal", "LP") legend2.AddEntry(Graph2, "1.05 GeV L0", "LP") legend2.AddEntry(Graph4, "2.3 GeV L0", "LP") legend2.AddEntry(Graph6, "4.4 GeV L0", "LP") legend2.AddEntry(Graph8, "6.6 GeV L0", "LP") histodumb = TH1F("histodumb", "histodumb", 2, 0.015, 0.340)
#print m , s , p #) #Combined = TF1("Combined","[0]* exp(-0.5*((x-[1])/[2])^2)+[3]*exp(-[4]*x)",0.9,1.2) Combined = TF1("Combined","gaus(0)+ expo(3)",0.98,1.3) Combined.SetLineWidth(2) Combined.SetLineColor(rt.kBlack) Combined.SetParameter(1,gau.GetParameter(1)) Combined.SetParameter(2,gau.GetParameter(2)) Combined.SetParameter(4,ep.GetParameter(1)) #Combined.SetParameter(4,w) #Combined.SetParameter(3,q) #Combined.SetParameter(5,y) #Defining Legend to add Text in histograms legend = TLegend(0.4,0.7,0.9,0.9) #legend.SetHeader("The Legend Title","C") # option "C" allows to center the header #legend.AddEntry(None,{tp.GetChisquare},"f") legend.AddEntry("tp","Gaussian with exponential and Polynomical background","l") legend.AddEntry("HighPt_Mass",MassCut[0:16],"e2p") #Fitting with Combined Function HighPt_Mass.Fit("Combined","QR+") #legend.Draw() #legend.Print() #d = Combined.GetChisquare()+Combined.GetNDF() #d = c.GetChisquare()/c.GetNDF() #r = TString(" ") #r = str(d) #print r
mm2J = myTopLvl.getChannel("met/meff2Jet",["SS"]) iPop=myTopLvl.validationChannels.index("SS_metmeff2Jet") myTopLvl.validationChannels.pop(iPop) else: mm2J = myTopLvl.addChannel("met/meff2Jet",["SS"],5,0.2,0.7) mm2J.useOverflowBin=True mm2J.addSystematic(jes) pass myTopLvl.addSignalChannels([mm2J]) # Create TLegend (AK: TCanvas is needed for that, but it gets deleted afterwards) c = TCanvas() compFillStyle = 1001 # see ROOT for Fill styles leg = TLegend(0.6,0.475,0.9,0.925,"") leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetBorderSize(0) # entry = TLegendEntry() entry = leg.AddEntry("","Data 2011 (#sqrt{s}=7 TeV)","p") entry.SetMarkerColor(bkt.dataColor) entry.SetMarkerStyle(20) # entry = leg.AddEntry("","Total pdf","lf") entry.SetLineColor(bkt.totalPdfColor) entry.SetLineWidth(2) entry.SetFillColor(bkt.errorFillColor) entry.SetFillStyle(bkt.errorFillStyle) #
def plot(path, ecms, xmin, xmax, mode): try: f_data = TFile(path[0]) t_data = f_data.Get('save') entries_data = t_data.GetEntries() logging.info('data entries :' + str(entries_data)) except: logging.error(path[0] + ' path is invalid!') sys.exit() try: f_side1 = TFile(path[1]) t_side1 = f_side1.Get('save') entries_side1 = t_side1.GetEntries() logging.info('data(side1) entries :' + str(entries_side1)) except: logging.error(path[1] + ' is invalid!') sys.exit() try: f_side2 = TFile(path[2]) t_side2 = f_side2.Get('save') entries_side2 = t_side2.GetEntries() logging.info('data(side2) entries :' + str(entries_side2)) except: logging.error(path[2] + ' is invalid!') sys.exit() try: f_side3 = TFile(path[3]) t_side3 = f_side3.Get('save') entries_side3 = t_side3.GetEntries() logging.info('data(side3) entries :' + str(entries_side3)) except: logging.error(path[3] + ' is invalid!') sys.exit() try: f_side4 = TFile(path[4]) t_side4 = f_side4.Get('save') entries_side4 = t_side4.GetEntries() logging.info('data(side4) entries :' + str(entries_side4)) except: logging.error(path[4] + ' is invalid!') sys.exit() mbc = TCanvas('mbc', 'mbc', 800, 600) set_canvas_style(mbc) xbins = 140 content = int((xmax - xmin) / xbins * 1000) ytitle = 'Eentries/%.1f MeV' % content xtitle = 'M(#pi_{0}^{+}#pi_{0}^{-}) (GeV)' h_data = TH1F('data', 'data', xbins, xmin, xmax) set_histo_style(h_data, xtitle, ytitle, 1, -1) m_pipi_fill(t_data, h_data, mode) h_side1 = TH1F('side1', 'side1', xbins, xmin, xmax) set_histo_style(h_side1, xtitle, ytitle, 3, 3004) m_pipi_fill(t_side1, h_side1, mode) h_side2 = TH1F('side2', 'side2', xbins, xmin, xmax) set_histo_style(h_side2, xtitle, ytitle, 3, 3004) m_pipi_fill(t_side2, h_side2, mode) h_side3 = TH1F('side3', 'side3', xbins, xmin, xmax) set_histo_style(h_side3, xtitle, ytitle, 3, 3004) m_pipi_fill(t_side3, h_side3, mode) h_side4 = TH1F('side4', 'side4', xbins, xmin, xmax) set_histo_style(h_side4, xtitle, ytitle, 3, 3004) m_pipi_fill(t_side4, h_side4, mode) h_side1.Add(h_side2) h_side1.Scale(0.5) h_side3.Add(h_side4) h_side3.Scale(0.25) h_side1.Add(h_side3, -1) h_data.Draw('E1') hs = THStack('hs', 'Stacked') hs.Add(h_side1) hs.Draw('same') h_data.Draw('sameE1') legend = TLegend(0.55, 0.65, 0.8, 0.85) leg_title = str(ecms) + ' MeV' set_legend(legend, h_data, h_side1, leg_title) legend.Draw() if not os.path.exists('./figs/'): os.makedirs('./figs/') mbc.SaveAs('./figs/m_pipi_' + str(ecms) + '_' + mode + '.pdf') raw_input('Enter anything to end...')
def main(): looks_minos() a = Analyzer("raw") ######## Question 1 ######## #Part A a.a() #Part B a.b() samples = [a.content()[i].samples() for i in xrange(len(a.content()))] cans_B = [TCanvas() for t in xrange(5)] tl = [TLegend(0.6, 0.4, 0.9, 0.8) for t in xrange(5)] title = [ TPaveText(0.549569, 0.8241525, 0.950431, 0.8983051, "nbNDC") for t in xrange(5) ] b1k = [TH1D("N1k_set_%d" % (t + 1), "", 100, 0, 10) for t in xrange(5)] b10k = [TH1D("N10k_set_%d" % (t + 1), "", 100, 0, 10) for t in xrange(5)] means1k = [] means10k = [] tt = [] for i in xrange(5): for j in xrange(len(samples[0][1000])): tt.append(samples[i][1000][j].first) b1k[i].Fill(samples[i][1000][j].first) means1k.append(tt) tt = [] for j in xrange(len(samples[0][10000])): tt.append(samples[i][10000][j].first) b10k[i].Fill(samples[i][10000][j].first) means10k.append(tt) tt = [] cans_B[i].cd() b1k[i].GetXaxis().SetTitle("Sample Mean") b1k[i].GetYaxis().SetTitle("Count") b1k[i].GetXaxis().CenterTitle() b1k[i].GetYaxis().CenterTitle() b1k[i].SetFillColor(4) b1k[i].SetFillStyle(3345) b10k[i].SetFillColor(2) b10k[i].SetFillStyle(3354) title[i].SetFillColor(0) title[i].SetFillStyle(0) title[i].SetLineColor(0) title[i].AddText("File v%d" % (i + 1)) tl[i].AddEntry(b1k[i], "1k", "f") tl[i].AddEntry(0, "Mean: %0.2f" % b1k[i].GetMean(), "") tl[i].AddEntry(0, "STD : %0.2f" % b1k[i].GetRMS(), "") tl[i].AddEntry(b10k[i], "10k", "f") tl[i].AddEntry(0, "Mean: %0.2f" % b10k[i].GetMean(), "") tl[i].AddEntry(0, "STD : %0.2f" % b10k[i].GetRMS(), "") b1k[i].Draw() b10k[i].Draw("SAMES") tl[i].Draw() title[i].Draw() # Calculate the standard deviations of the sample means for i in xrange(5): print "File v%d: 1k ~ %f 10k ~ %f ratio ~ %f" % ( i, n.std(means1k[i], ddof=1), n.std( means10k[i], ddof=1), n.std(means1k[i]) / n.std(means10k[i])) ###### Part C (3.) ###### nn = int(300) a.c(nn) tcc = [TCanvas() for i in xrange(5)] tgc = [TGraph() for i in xrange(5)] corrs = [a.content()[i].correlation() for i in xrange(len(a.content()))] for x in xrange(5): tcc[x].cd() for j in xrange(len(corrs[x])): tgc[x].SetPoint(j, j, corrs[x][j] / corrs[x][0]) tgc[x].GetXaxis().SetTitle("n") tgc[x].GetYaxis().SetTitle("C_{v%i}(n)/C_{v%i}(0)" % (x + 1, x + 1)) tgc[x].GetXaxis().CenterTitle() tgc[x].GetYaxis().CenterTitle() tgc[x].SetLineWidth(2) tgc[x].Draw("AL") title[x].Draw() tcc[x].Update() tcc[x].Modified() ###### Part D (4.) ###### a.d() for x in xrange(5): print "File v%d: integrated corr ~ %f " % ( x, a.content()[x].integrated_correlation()) ##### Part E (5.) ##### a.e() cc = TCanvas() cc.cd() cc2 = TCanvas() cc.cd() gStyle.SetPalette(55) th2 = TH2D("basedgod", "", 5, 1, 6, 5, 1, 6) for x in xrange(5): for y in xrange(5): v = a.crosscorrelation()[x][y] print "file: %d with file: %d is %f" % (x, y, v) th2.SetBinContent(x + 1, y + 1, v) th2.GetXaxis().SetTitle("Data v_a") th2.GetYaxis().SetTitle("Data v_a") th2.GetXaxis().CenterTitle() th2.GetYaxis().CenterTitle() th2.Draw("COLZ") cc.Update() cc.Modified() cc2.cd() th2.Draw("SURF1") cc2.Update() cc2.Modified() raw_input('')
def makeCSGraph(ctype, startGammaEE=None): data = loadCrossSection(ctype) c = TCanvas('c_%s' % ctype, '', 1280, 720) g = data.makeGraph('g_%s' % ctype, '#sqrt{s} / GeV', '#sigma / nb') g.Draw('AP') if not startGammaEE: fit = Fitter( 'fit_%s' % ctype, '(12*pi / [0]^2) * (x^2 * [1]^2) / ((x^2-[0]^2)^2 + x^4 * [2]^2 / [0]^2) * 0.3894*10^6' ) # GeV^-2 = 0.3894 mb fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{%s}^{2}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[ 0] else: fit = Fitter( 'fit_%s' % ctype, '(12*pi / [0]^2) * (x^2 * [1] * [2]) / ((x^2-[0]^2)^2 + x^4 * [3]^2 / [0]^2) * 0.3894*10^6' ) fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{m} #Gamma_{%s}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[ 0] fit.setParam(0, 'M_{Z}', 91.2) fit.setParamLimits(0, 0, 1000) if not startGammaEE: fit.setParam(1, '#Gamma_{%s}' % ctype[0], 0.08) fit.setParamLimits(1, 0, 1000) fit.setParam(2, '#Gamma_{Z}', 2.5) fit.setParamLimits(2, 0, 1000) else: fit.setParam(1, '#Gamma_{m}', startGammaEE, True) fit.setParam(2, '#Gamma_{%s}' % ctype[0], 1.5) fit.setParam(3, '#Gamma_{Z}', 2.5) fit.setParamLimits(2, 0, 1000) fit.fit(g, 88, 94, '') fit.saveData('../fit/crosssections_%s.txt' % ctype) l = TLegend(0.625, 0.6, 0.98, 0.975) l.SetTextSize(0.03) l.AddEntry(g, "%s Wirkungsquerschnitte" % ctype, 'p') l.AddEntry(fit.function, "Fit mit #sigma(s) = %s" % fitfuncstring, 'l') l.AddEntry(None, "", '') if not startGammaEE: fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.4f', '%.4f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['GeV / c^{2}', 'GeV', 'GeV']) else: fit.addParamsToLegend(l, [('%.3f', '%.3f'), '%.4f', ('%.3f', '%.3f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['GeV/c^{2}', 'GeV', 'GeV', 'GeV']) l.Draw() c.Update() if not DEBUG: c.Print('../img/crosssections_%s.pdf' % ctype, 'pdf') if not startGammaEE: result = [(fit.params[0]['value'], fit.params[0]['error']), (fit.params[1]['value'], fit.params[1]['error']), (fit.params[2]['value'], fit.params[2]['error'])] else: result = [(fit.params[0]['value'], fit.params[0]['error']), (fit.params[2]['value'], fit.params[2]['error']), (fit.params[3]['value'], fit.params[3]['error'])] return result
def plot1(key, xsection1, xsection2, histo1, histo2, name1, name2, LogY, weight1, weight2, outputDIR): c1 = TCanvas(key, key, 800, 600) pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99) pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20) pad1.SetGridx() pad1.SetGridy() pad2.SetGridy() pad1.SetFillColor(0) pad1.SetLineColor(0) pad2.SetFillColor(0) pad2.SetLineColor(0) pad1.SetBottomMargin(0.03) pad2.SetTopMargin(0.15) pad2.SetBottomMargin(0.3) pad1.Draw() pad2.Draw() leg1 = TLegend(0.65, 0.75, 0.86, 0.86) histo1.Scale(xsection1 / weight1) histo1.SetMaximum(1.2 * histo1.GetMaximum()) histo1.SetLineColor(kRed) histo1.SetLineWidth(2) histo1.GetXaxis().SetLabelSize(0) histo2.Scale(xsection2 / weight2) histo2.SetLineColor(kBlack) histo2.SetLineWidth(2) pad1.cd() if LogY: pad1.SetLogy() histo_ratio = histo2.Clone() histo_ratio.SetTitle('') histo_ratio.Divide(histo1) histo_ratio.SetMaximum(1.5) histo_ratio.SetMinimum(0.5) histo_ratio.GetYaxis().SetNdivisions(4, kFALSE) histo_ratio.GetXaxis().SetTitle(key) histo_ratio.GetXaxis().SetTitleSize(0.15) histo_ratio.GetXaxis().SetTitleOffset(0.75) histo_ratio.GetXaxis().SetLabelSize(0.13) histo_ratio.GetYaxis().SetTitle(name1 + '/' + name2) histo_ratio.GetYaxis().SetTitleSize(0.1) histo_ratio.GetYaxis().SetTitleOffset(0.3) histo_ratio.GetYaxis().SetLabelSize(0.13) histo_ratio.SetLineWidth(2) histo1.Draw('pe') histo2.Draw('same pe') leg1.AddEntry(histo1, name1) leg1.AddEntry(histo2, name2) leg1.SetFillStyle(0) leg1.SetBorderSize(0) leg1.Draw() c1.Update() pad2.cd() histo_ratio.Draw() if LogY: c1.SaveAs(outputDIR + '/' + key + '_log.png') c1.SaveAs(outputDIR + '/' + key + '_log.pdf') else: c1.SaveAs(outputDIR + '/' + key + '.png') c1.SaveAs(outputDIR + '/' + key + '.pdf') # renew histo1.Scale(weight1 / xsection1) histo2.Scale(weight2 / xsection2)
def plot2(key, xsections, histos, names, LogY, weights, outputDIR): c1 = TCanvas(key, key, 800, 600) pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99) pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20) pad1.SetGridx() pad1.SetGridy() pad2.SetGridy() pad1.SetFillColor(0) pad1.SetLineColor(0) pad2.SetFillColor(0) pad2.SetLineColor(0) pad1.SetBottomMargin(0.03) pad2.SetTopMargin(0.15) pad2.SetBottomMargin(0.3) pad1.Draw() pad2.Draw() leg1 = TLegend(0.68, 0.55, 0.86, 0.86) histos[0].GetXaxis().SetLabelSize(0) histos[0].SetMarkerStyle(20) for i in range(0, len(histos)): #if histos[i].Integral()==0: continue histos[i].Scale(xsections[i] / weights[i]) histos[i].SetLineColor(i + 1) histos[i].SetLineWidth(2) histo_ratio = histos[1].Clone() for i in range(2, len(histos)): histo_ratio.Add(histos[i]) histo_ratio.SetLineWidth(2) histo_sum = histo_ratio.Clone() histo_sum.SetLineColor(49) histo_sum.SetLineWidth(2) histo_ratio.SetTitle('') histo_ratio.Divide(histos[0]) histo_ratio.SetLineColor(49) histo_ratio.SetMaximum(1.5) histo_ratio.SetMinimum(0.5) histo_ratio.GetYaxis().SetNdivisions(4, kFALSE) histo_ratio.GetXaxis().SetTitle(key) histo_ratio.GetXaxis().SetTitleSize(0.15) histo_ratio.GetXaxis().SetTitleOffset(0.75) histo_ratio.GetXaxis().SetLabelSize(0.13) histo_ratio.GetYaxis().SetTitle('summed/inc') histo_ratio.GetYaxis().SetTitleSize(0.1) histo_ratio.GetYaxis().SetTitleOffset(0.3) histo_ratio.GetYaxis().SetLabelSize(0.13) pad1.cd() if LogY: pad1.SetLogy() histos[0].SetMaximum(1.2 * histos[0].GetMaximum()) histos[0].Draw('pe') for i in range(1, len(histos)): histos[i].Draw('same h') histo_sum.Draw('same h') leg1.AddEntry(histos[0], names[0]) leg1.AddEntry(histo_sum, 'MGsummed') for i in range(1, len(histos)): leg1.AddEntry(histos[i], names[i]) leg1.SetFillStyle(0) leg1.SetBorderSize(0) leg1.Draw() c1.Update() pad2.cd() histo_ratio.Draw() if LogY: c1.SaveAs(outputDIR + '/' + key + '_log.png') c1.SaveAs(outputDIR + '/' + key + '_log.pdf') else: c1.SaveAs(outputDIR + '/' + key + '.png') c1.SaveAs(outputDIR + '/' + key + '.pdf') for i in range(0, len(histos)): histos[i].Scale(weights[i] / xsections[i])
properites["NrecP"] = h_ntot.GetBinContent(4) / h_ntot.GetBinContent(1) if (process == "bppp"): properites["NtruE"] = h_ntot.GetBinContent(5) / h_ntot.GetBinContent(1) properites["NaccE"] = h_ntot.GetBinContent(6) / h_ntot.GetBinContent(1) properites["NrecE"] = h_ntot.GetBinContent(7) / h_ntot.GetBinContent(1) histos.update({spotsize + "_ntot": h_ntot}) histos.update({spotsize + "_tru_E": h_tru_E}) histos.update({spotsize + "_rec_E": h_rec_E}) histos.update({spotsize + "_tru_ntrks": h_tru_ntrks}) histos.update({spotsize + "_rec_ntrks": h_rec_ntrks}) print(spotsizes) ############################################################### leg_kin = TLegend(0.50, 0.70, 0.87, 0.87) leg_kin.SetFillStyle(4000) # will be transparent leg_kin.SetFillColor(0) leg_kin.SetTextFont(42) leg_kin.SetBorderSize(0) key = "w0_8000nm" if ("w0_8000nm" in signals[prefix]) else "w0_11000nm" leg_kin.AddEntry(histos[key + "_tru_E"], "Truth signal", "l") ### I assume this spot is always used leg_kin.AddEntry(histos[key + "_rec_E"], "Emul. Recon.", "lp") ### I assume this spot is always used ############################################################### xis = [] chis = [] NtruPs = []
tau_frWeight =1.0 else: tau_frWeight =tree.tau_fake_prob evtWeight = evtWeight*lep1_frWeight*lep2_frWeight*lep3_frWeight*tau_frWeight mvaValue = reader.EvaluateMVA("testmva") hist_bkg.Fill(mvaValue, evtWeight) hist_signal.SetLineColor(2) hist_bkg.SetLineColor(4) hist_signal.SetFillColor(2) hist_bkg.SetFillColor(4) hist_signal.SetFillStyle(3004) hist_bkg.SetFillStyle(3005) leg = TLegend(0.2, 0.65, 0.5, 0.9) leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetLineColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetTextFont(42) leg.AddEntry(hist_signal, "loose selection", "l") leg.AddEntry(hist_bkg, "tight selection", "l") hist_signal.DrawNormalized("histsame") hist_bkg.DrawNormalized("histsame") leg.Draw() c1.SaveAs("plots/bdt_score_sklearn_3l1t_ttV_12Var_wfrWt_loose_vs_tight_"+process+".png")
if "withJEC" in baseDir: calib = "calibrated" else: calib = "uncalibrated" if baseDir == baseDirOld: legend.AddEntry(myGraph, "#splitline{Old params, %s.}{Events: %i}" % (calib, entriesToRun), "p") elif baseDir == baseDirNewMode: legend.AddEntry(myGraph, "#splitline{New params (mode), %s.}{Events: %i}" % (calib, entriesToRun), "p") elif baseDir == baseDirNewMean: legend.AddEntry(myGraph, "#splitline{New params (mean), %s.}{Events: %i}" % (calib, entriesToRun), "p") return multiGraph multiGraph = TMultiGraph() myLeg = TLegend(0.65, 0.7, 0.9, 0.9) # After calibrations #baseDirOld = "/hdfs/L1JEC/CMSSW_9_2_0/crab_qcdSpring17FlatPU0to70genSimRaw_qcdSpring17_genEmu_19Jun2017_920v95p13_withJEC_1bf1ede0b/pairs/" #baseDirNewMode = "/hdfs/L1JEC/CMSSW_9_2_8/crab_qcdSummer17FlatPU28to62genSimRaw_qcdSummer17_genEmu_03Nov2017_928v96p49_withJEC_79eea6f204/pairs/" #baseDirNewMean = "/hdfs/L1JEC/CMSSW_9_2_8/crab_qcdSummer17FlatPU28to62genSimRaw_qcdSummer17_genEmu_14Nov2017_928v96p49_withJEC_meanParams_3ae18f21/pairs/" # Before calibrations baseDirOld = "/hdfs/L1JEC/CMSSW_9_2_0/crab_qcdSpring17FlatPU0to70genSimRaw_qcdSpring17_genEmu_13Jun2017_920v95p13_withoutJEC_43041fdb/pairs/" baseDirNewMode = "/hdfs/L1JEC/CMSSW_9_2_8/crab_qcdSummer17FlatPU28to62genSimRaw_qcdSummer17_genEmu_27Oct2017_928v96p49_noJEC_46c34f99b37a/pairs/" baseDirNewMean = "/hdfs/L1JEC/CMSSW_9_2_8/crab_qcdSummer17FlatPU28to62genSimRaw_qcdSummer17_genEmu_11Nov2017_928v96p49_noJEC_meanParams_3ae18f21/pairs/" initialisePlots(baseDir = baseDirOld, multiGraph = multiGraph, MarkerColour = 2, legend = myLeg) # colour = red initialisePlots(baseDir = baseDirNewMode, multiGraph = multiGraph, MarkerColour = 4, legend = myLeg) # colour = blue initialisePlots(baseDir = baseDirNewMean, multiGraph = multiGraph, MarkerColour = 3, legend = myLeg) # colour = green
def make_plot(histo_0, histo_1, suffix, stacked, classifier_parent_dir): c1 = ROOT.TCanvas('c1',',1000,700') p1 = ROOT.TPad('p1','p1',0.0,0.0,1.0,1.0) p1.Draw() p1.SetRightMargin(0.1) p1.SetLeftMargin(0.1) p1.SetBottomMargin(0.1) p1.SetTopMargin(0.1) p1.SetGridx(True) p1.SetGridy(True) p1.cd() ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptTitle(0) histo_0.GetYaxis().SetTitle('(1/N)dN/dX') histo_0.GetXaxis().SetTitle('Response') dx_ttH = (histo_0.GetXaxis().GetXmax() - histo_0.GetXaxis().GetXmin()) / histo_0.GetNbinsX() ttH_norm = 1./histo_0.GetSumOfWeights()/dx_ttH histo_0.Scale(ttH_norm) dx_bckg = (histo_1.GetXaxis().GetXmax() - histo_1.GetXaxis().GetXmin()) / histo_1.GetNbinsX() bckg_norm = 1./histo_1.GetSumOfWeights()/dx_bckg histo_1.Scale(bckg_norm) sig_bckg_sep = GetSeparation(histo_0, histo_1) maxyaxis = max(histo_0.GetMaximum(), histo_1.GetMaximum()) histo_0.SetAxisRange(0.,maxyaxis+1.,"Y") histo_0.SetLineColor(2) histo_0.SetMarkerColor(2) histo_0.SetMarkerStyle(20) histo_0.SetFillColor(2) histo_0.SetFillStyle(3001) if 'ttV' in suffix: color = 3 elif 'ttJets' in suffix: color = 4 histo_1.SetLineColor(color) histo_1.SetMarkerColor(color) histo_1.SetMarkerStyle(20) histo_1.SetFillColor(color) histo_1.SetFillStyle(3001) histo_0.Draw("HIST") histo_1.Draw("HISTSAME") legend = TLegend(0.85, 0.85, 1., 1.) legend.AddEntry(histo_0,"ttH") if 'ttV' in suffix: legend.AddEntry(histo_1,"ttV") if 'ttJets' in suffix: legend.AddEntry(histo_1,"ttJets") legend.Draw("same") classifier_plots_dir = classifier_parent_dir+"/plots" if not os.path.exists(classifier_plots_dir): os.makedirs(classifier_plots_dir) # Add custom title l1=ROOT.TLatex() l1.SetNDC() latex_title = "BDTG Response: %s" % suffix l1.DrawLatex(0.25,0.94,latex_title) l2=ROOT.TLatex() l2.SetNDC() latex_separation = '#scale[0.5]{Separation = %.5f}' % sig_bckg_sep l2.DrawLatex(0.7,0.8,latex_separation) outfile_name = 'BDTG_Response_Applied_%s.pdf'%suffix output_fullpath = classifier_plots_dir + '/' + outfile_name c1.Print(output_fullpath,'pdf')
def main(): usage = 'usage: %prog [options]' parser = optparse.OptionParser(usage) parser.add_option('-s', '--suffix', dest='input_suffix' , help='suffix used to identify which network training directory to get inputs from', default=None, type='string') parser.add_option('-d', '--data', dest='data_flag' , help='1 = include data from plots, 0 = exclude data from plots', default=0, type='int') (opt, args) = parser.parse_args() if opt.input_suffix == None: print 'Input files suffix not defined!' sys.exit(1) data_flag = opt.data_flag classifier_suffix = opt.input_suffix classifier_parent_dir = 'V7-DNN_%s' % (classifier_suffix) classifier_samples_dir = classifier_parent_dir+"/outputs-newbinning" print 'Reading samples from: ', classifier_samples_dir sample_name = ['Conv','EWK','Fakes','Flips','Rares','TTH_hww','TTH_htt','TTH_hot','TTW','TTZ','TTWW','TTH_hmm','Data'] channel_name = ['2L'] input_name_Conv = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[0],channel_name[0]) input_file_Conv = TFile.Open(input_name_Conv) input_name_EWK = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[1],channel_name[0]) input_file_EWK = TFile.Open(input_name_EWK) input_name_Fakes = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[2],channel_name[0]) input_file_Fakes = TFile.Open(input_name_Fakes) input_name_Flips = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[3],channel_name[0]) input_file_Flips = TFile.Open(input_name_Flips) input_name_Rares = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[4],channel_name[0]) input_file_Rares = TFile.Open(input_name_Rares) input_name_TTH_hww = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[5],channel_name[0]) input_file_TTH_hww = TFile.Open(input_name_TTH_hww) input_name_TTH_htt = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[6],channel_name[0]) input_file_TTH_htt = TFile.Open(input_name_TTH_htt) input_name_TTH_hot = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[7],channel_name[0]) input_file_TTH_hot = TFile.Open(input_name_TTH_hot) input_name_TTW = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[8],channel_name[0]) input_file_TTW = TFile.Open(input_name_TTW) input_name_TTZ = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[9],channel_name[0]) input_file_TTZ = TFile.Open(input_name_TTZ) input_name_TTWW = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[10],channel_name[0]) input_file_TTWW = TFile.Open(input_name_TTWW) input_name_TTH_hmm = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[11],channel_name[0]) input_file_TTH_hmm = TFile.Open(input_name_TTH_hmm) input_name_data = '%s/%s/Evaluated_%s_%s_%s.root' % (classifier_samples_dir,channel_name[0],classifier_suffix,sample_name[12],channel_name[0]) input_file_data = TFile.Open(input_name_data) categories = ['ee','em_ttHCategory','em_ttVCategory','em_ttJCategory','mm_ttHCategory','mm_ttVCategory','mm_ttJCategory'] #categories = ['mm_ttHCategory'] for cat in categories: print 'category: ' , cat process_list = { "Conv" : 5, "EWK" : 6, "Fakes" : 13, "Flips" : 17, "Rares" : 38, "TTW" : 8, "TTZ" : 9, "TTWW" : 3, "TTH_hww" : 2, "TTH_htt" : 2, "TTH_hot" : 2, "TTH_hmm" : 2, "Data":1 } histo_Conv_name = 'histo_%s_events_Conv_%s' % (cat,channel_name[0]) histo_EWK_name = 'histo_%s_events_EWK_%s' % (cat,channel_name[0]) histo_Fakes_name = 'histo_%s_events_Fakes_%s' % (cat,channel_name[0]) histo_Flips_name = 'histo_%s_events_Flips_%s' % (cat,channel_name[0]) histo_Rares_name = 'histo_%s_events_Rares_%s' % (cat,channel_name[0]) histo_TTH_hww_name = 'histo_%s_events_TTH_hww_%s' % (cat,channel_name[0]) histo_TTH_htt_name = 'histo_%s_events_TTH_htt_%s' % (cat,channel_name[0]) histo_TTH_hot_name = 'histo_%s_events_TTH_hot_%s' % (cat,channel_name[0]) histo_TTH_hmm_name = 'histo_%s_events_TTH_hmm_%s' % (cat,channel_name[0]) histo_TTW_name = 'histo_%s_events_TTW_%s' % (cat,channel_name[0]) histo_TTZ_name = 'histo_%s_events_TTZ_%s' % (cat,channel_name[0]) histo_TTWW_name = 'histo_%s_events_TTWW_%s' % (cat,channel_name[0]) histo_data_name = 'histo_%s_events_Data' % (cat) histo_Conv_sample = input_file_Conv.Get(histo_Conv_name) histo_EWK_sample = input_file_EWK.Get(histo_EWK_name) histo_Fakes_sample = input_file_Fakes.Get(histo_Fakes_name) histo_Flips_sample = input_file_Flips.Get(histo_Flips_name) histo_Rares_sample = input_file_Rares.Get(histo_Rares_name) histo_TTH_hww_sample = input_file_TTH_hww.Get(histo_TTH_hww_name) histo_TTH_htt_sample = input_file_TTH_htt.Get(histo_TTH_htt_name) histo_TTH_hot_sample = input_file_TTH_hot.Get(histo_TTH_hot_name) histo_TTH_hmm_sample = input_file_TTH_hmm.Get(histo_TTH_hmm_name) histo_TTW_sample = input_file_TTW.Get(histo_TTW_name) histo_TTZ_sample = input_file_TTZ.Get(histo_TTZ_name) histo_TTWW_sample = input_file_TTWW.Get(histo_TTWW_name) histo_data_sample = input_file_data.Get(histo_data_name) # Turn this into dictionary hist_list = OrderedDict([ ("Conv" , histo_Conv_sample), ("EWK" , histo_EWK_sample), ("Fakes" , histo_Fakes_sample), ("Flips" , histo_Flips_sample), ("Rares" , histo_Rares_sample), ("TTW" , histo_TTW_sample), ("TTZ" , histo_TTZ_sample), ("TTWW" , histo_TTWW_sample), ("TTH_hww" , histo_TTH_hww_sample), ("TTH_htt" , histo_TTH_htt_sample), ("TTH_hot" , histo_TTH_hot_sample), ("TTH_hmm" , histo_TTH_hmm_sample) ]) # Rebin Histograms so > 0 total background entries per bin. # Returns array of histograms in same order as was passed to the function. rebinned_histograms = rebinHistograms(hist_list, histo_data_sample) hist_stack = ROOT.THStack() legend = TLegend(0.7, 0.7, 0.9, 0.9) legend.SetNColumns(2) for rebinned_hist_name, rebinned_hist in rebinned_histograms.iteritems(): print 'rebinned_hist_name = ', rebinned_hist_name rebinned_hist.SetMarkerColor(process_list[rebinned_hist_name]) rebinned_hist.SetLineColor(process_list[rebinned_hist_name]) rebinned_hist.GetYaxis().SetTitle("Events/bin") rebinned_hist.SetMarkerStyle(20) rebinned_hist.Sumw2() if 'Data' in rebinned_hist_name: legend.AddEntry(rebinned_hist,rebinned_hist_name,'p') continue else: legend.AddEntry(rebinned_hist,rebinned_hist_name,'f') rebinned_hist.SetMarkerStyle(20) if 'TTH_hww' in rebinned_hist_name: rebinned_hist.SetFillStyle(2001) if 'TTH_hmm' in rebinned_hist_name: rebinned_hist.SetFillStyle(1001) if 'TTH_htt' in rebinned_hist_name: rebinned_hist.SetFillStyle(4001) if 'TTH_hot' in rebinned_hist_name: rebinned_hist.SetFillStyle(5001) else: rebinned_hist.SetFillStyle(3001) rebinned_hist.SetFillColor(process_list[rebinned_hist_name]) print 'Adding hist' hist_stack.Add(rebinned_hist) hist_stack.SetMaximum(hist_stack.GetStack().Last().GetMaximum() + (hist_stack.GetStack().Last().GetMaximum()/2)) hist_stack.SetMinimum(0.) # Get Data/MC agreement # Ensure to pass data histogram as last argument. if data_flag: dataOverMC = GetDataOverMC(hist_stack,rebinned_histograms['Data']) # Create histograms. make_plot(hist_stack, cat, classifier_parent_dir, False, legend, rebinned_histograms['Data'] , dataOverMC) else: make_plot(hist_stack, cat, classifier_parent_dir, False, legend)
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3) parser.add_option("-x", "--exclusive", action="store_true",\ dest="isExclusive", default=False) parser.add_option("-l", "--label", dest="label", type="string", default="") parser.add_option("-z", "--zeyneplabel", action="store_true", dest="zeynep", default=True) (options, args) = parser.parse_args() N = options.N isExclusive = options.isExclusive label_text = options.label zeynep = options.zeynep if isExclusive and not (N == 2 or N == 3): parser.error("Exclusive plot only for N =2 or 3") import configurations as config from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath from ModelParser import ModelKey gStyle.SetPadTopMargin(0.05) gStyle.SetPadRightMargin(0.05) gStyle.SetPadBottomMargin(0.20) gStyle.SetErrorX(0.) suffix = "" if not isExclusive: suffix = "up" sm_files = [] for model in config.sm_models: f = TFile("%s/%s.root" % (config.sm_dir, model), "READ") sm_files.append(f) bh_weights = [] bh_files = [] from BHXsec import BHXsec xsec = BHXsec() for model in config.bh_showcase: f = TFile("%s/%s.root" % (config.bh_dir, model), "READ") bh_files.append(f) h = f.Get("plotsNoCut/ST") nEvents = h.GetEntries() bh_weights.append( xsec.get(model) / nEvents * config.integrated_luminosity) c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500, 600) hs = THStack() hs1 = THStack() infile = TFile(options.inputfile, "READ") hBkg = infile.Get("Background_N%d%s" % (N, suffix)) #hnewBkg = infile.Get("histoTemplateN3_0") hnewBkg = infile.Get("ReferenceTemplateN3_0") gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix)) hData = infile.Get("Data_N%d%s" % (N, suffix)) hBkg = infile.Get("Background_N%d%s" % (N, suffix)) hBkg.SetMarkerSize(0) hBkg_ = hBkg.Clone("BkgLine") hBkg.SetFillColor(33) hBkg.SetLineColor(33) hBkg_.SetLineWidth(3) hBkg_.SetLineColor(862) hs.Add(hBkg, "e3") hnewBkg.SetLineWidth(3) hnewBkg.Scale(10 * 3.407) hs.Add(hnewBkg, "l") legend = TLegend(0.2826613, 0.4819492, 0.6094355, 0.9416102) # - only for N >= 2 and 3 #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919... #legend.SetTextSize(0.041); #was 0.02966102 legend.SetTextSize(0.037) legend.SetTextFont(42) legend.SetFillColor(0) legend.SetLineColor(0) if isExclusive: legend.SetHeader("Multiplicity N = %d" % N) else: legend.SetHeader("Multiplicity N #geq %d" % N) legend.AddEntry(hData, "Data", "lep") #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l") legend.AddEntry(hBkg_, "Background", "l") legend.AddEntry(hBkg, "Uncertainty", "f") legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186) # legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186) # legend_sm.SetTextSize(0.037); legend_sm.SetTextSize(0.037) legend_sm.SetTextFont(42) legend_sm.SetFillColor(0) legend_sm.SetLineColor(0) for i, f in enumerate(bh_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(bh_weights[i]) # Add background for ibin in range(h.GetNbinsX()): h.SetBinContent(ibin+1,\ h.GetBinContent(ibin+1)\ + hBkg.GetBinContent(ibin+1)) h.SetLineWidth(3) #h.SetLineColor(i+2) h.SetLineStyle(i + 2) #if i == 0: #h.SetLineColor(814) if i == 0: h.SetLineStyle(5) h.SetLineColor(899) if i == 1: h.SetLineStyle(9) h.SetLineColor(4) if i == 2: h.SetLineStyle(3) h.SetLineColor(614) hs.Add(h, "hist") model = ModelKey(config.bh_showcase[i]) bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\ model.parameter["MD"], model.parameter["M"], model.parameter["n"]) if i == 3: bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4" legend.AddEntry(h, bh_legend, "l") # qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5" # legend.AddEntry(h, qbh_legend, "l") #if isExclusive: zeynep = True if zeynep: for i, f in enumerate(sm_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(config.integrated_luminosity) h.SetFillColor(config.sm_colors[i]) h.SetLineColor(config.sm_colors[i]) hs1.Add(h, "hist") legend_sm.AddEntry(h, config.sm_models[i], "f") #hs.Add(hData, "e") hs.Draw("nostack") hs1.Draw("same") c.SetLogy(1) hs.GetXaxis().SetTitle("S_{T} (GeV)") hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle()) hs.GetYaxis().SetTitleOffset(1.25) hs.GetYaxis().SetTitleSize(0.04) hs.GetYaxis().SetLabelSize(0.04) hs.GetXaxis().SetTitleSize(0.01) hs.GetXaxis().SetLabelSize(0.01) ibin = 0 #if isExclusive: # hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST) # ibin = hData.FindBin(config.fit_range[0]) #else: # hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST) # ibin = hData.FindBin(config.norm_range[0]) if isExclusive: hs.GetXaxis().SetRangeUser(1800, config.maxST) ibin = hData.FindBin(1800) else: hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST) ibin = hData.FindBin(config.norm_range[0]) from Styles import formatUncertainty formatUncertainty(gBkg) gBkg.Draw("LX") hData.Draw("sameex0") hs.SetMinimum(5e-1) if isExclusive: hs.SetMaximum(1e7) # hs.SetMaximum(hData.GetBinContent(ibin) * 40) else: #hs.SetMaximum(1e8) hs.SetMaximum(hData.GetBinContent(ibin) * 20) # or 1e7 for N>=3 and use 4 models legend.Draw("plain") #if isExclusive: if zeynep: legend_sm.Draw("plain") if isExclusive: cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC") else: cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC") cmslabel.AddText(config.cmsTitle) #cmslabel.AddText(config.cmsSubtitle) cmslabel.SetFillColor(0) cmslabel.SetTextSize(0.041) cmslabel.Draw("plain") label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC") label.SetFillColor(0) #label.SetTextSize(0.0529661); label.SetTextSize(0.0529661) label.AddText(label_text) label.Draw("plain") c.RedrawAxis() #Divide ibin = hData.FindBin(config.norm_range[0]) #print ibin fbin = hData.FindBin(config.maxST) #print fbin hData.Sumw2() hBkg_.Sumw2() Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100) Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100) Ratio = hData.Clone() Ratio.Add(hBkg_, -1) #Ratio.Divide(hBkg_) Band = TGraphAsymmErrors(fbin - ibin + 1) for i in range(ibin - 1, fbin + 1): i += 1 if hData.GetBinContent(i) != 0: value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) * hBkg_.GetBinError(i)) #print Ratio.GetBinError(i), value**(0.5) #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i) Pull.SetBinContent( i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) / Ratio.GetBinError(i)) #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05 #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i)) #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i))) Pull.SetBinError(i - 19, Ratio.GetBinError(i)) #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i)) if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)): #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05 Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) / (hBkg_.GetBinContent(i) * 0.05)) else: Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) / hBkg_.GetBinError(i)) #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05 #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i) else: Pull.SetBinContent(i - 19, 0) Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) / hBkg_.GetBinError(i)) Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0) #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i) up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) / hBkg_.GetBinContent(i))) down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) / hBkg_.GetBinContent(i))) Band.SetPointError(i, 0., 0., down, up) #Band.Print() pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0) pad.SetTopMargin(0.799999) pad.SetRightMargin(0.05) pad.SetBottomMargin(0.09) pad.SetFillColor(0) #pad.SetGridy(1) pad.SetFillStyle(0) pad.Draw("same") pad.cd(0) Ratio.SetMarkerStyle(20) Pull.SetMarkerStyle(20) Pull.SetLineColor(1) Pull.SetMarkerSize(0.9) #Pull.SetMaximum(3) #Pull.SetMinimum(-1) Pull.SetMaximum(2.5) Pull.SetMinimum(-2.5) Pull.GetYaxis().SetNdivisions(5, 1) Pull.GetXaxis().SetTitle('S_{T} (GeV)') Pull.GetXaxis().SetLabelSize(0.04) Pull.GetYaxis().SetTitleOffset(1.05) Pull.GetYaxis().SetLabelSize(0.02) Pull.GetYaxis().SetTitleSize(0.025) Pull.GetYaxis().CenterTitle(1) Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)') Pull.SetFillColor(2) Pull.Draw("HIST") Pull2.SetLineColor(862) Pull2.SetLineWidth(3) Pull2.SetLineStyle(2) #Pull2.Draw("SAME") formatUncertainty(Band) Band.SetFillStyle(3001) # Band.Draw("le3") # Pull.Draw("ex0same") pad.RedrawAxis() gStyle.SetOptStat(0) #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC"); #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC") #FOR n=3 only block1.SetFillColor(0) block1.Draw("plain") #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC"); #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC") #FOR n=3 only block2.SetFillColor(0) block2.Draw("plain") if isExclusive: c.Print("ST_Mul%d.pdf" % N) c.Print("ST_Mul%d.png" % N) else: c.Print("ST_Mul%dup.pdf" % N) c.Print("ST_Mul%dup.png" % N) c.Update() raw_input("Press Enter to continue...")
backhistos[imult].SetBinContent(ipt + 1, rootback) backhistos[imult].SetBinError(ipt + 1, rooteback) #Significance fit plot csign = TCanvas('cSign', 'The Fit Canvas') 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)])
def train_and_apply(): np.random.seed(1) ROOT.gROOT.SetBatch() #Extract data from root file tree = uproot.open("out_all.root")["outA/Tevts"] branch_mc = [ "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta", "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi", "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta", "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi", "MC_pis_pt", "MC_q2" ] branch_rec = [ "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt", "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P", "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt", "q2" ] nvariable = len(branch_mc) x_train = tree.array(branch_mc[0], entrystop=options.maxevents) for i in range(1, nvariable): x_train = np.vstack( (x_train, tree.array(branch_mc[i], entrystop=options.maxevents))) x_test = tree.array(branch_rec[0], entrystop=options.maxevents) for i in range(1, nvariable): x_test = np.vstack( (x_test, tree.array(branch_rec[i], entrystop=options.maxevents))) x_train = x_train.T x_test = x_test.T x_test = array2D_float(x_test) #Different type of reconstruction variables #BN normalization gamma = 0 beta = 0.2 ar = np.array(x_train) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_train = np.vstack((x_train, a)) x_train = x_train.T ar = np.array(x_test) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_test = np.vstack((x_test, a)) x_test = x_test.T #Add noise, remain to be improved noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape) x_train_noisy = x_train + noise noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape) x_test_noisy = x_test + noise x_train = np.clip(x_train, -1., 1.) x_test = np.clip(x_test, -1., 1.) x_train_noisy = np.clip(x_train_noisy, -1., 1.) x_test_noisy = np.clip(x_test_noisy, -1., 1.) # Network parameters input_shape = (x_train.shape[1], ) batch_size = 128 latent_dim = 2 # Build the Autoencoder Model # First build the Encoder Model inputs = Input(shape=input_shape, name='encoder_input') x = inputs # Shape info needed to build Decoder Model shape = K.int_shape(x) # Generate the latent vector latent = Dense(latent_dim, name='latent_vector')(x) # Instantiate Encoder Model encoder = Model(inputs, latent, name='encoder') encoder.summary() # Build the Decoder Model latent_inputs = Input(shape=(latent_dim, ), name='decoder_input') x = Dense(shape[1])(latent_inputs) x = Reshape((shape[1], ))(x) outputs = Activation('tanh', name='decoder_output')(x) # Instantiate Decoder Model decoder = Model(latent_inputs, outputs, name='decoder') decoder.summary() # Autoencoder = Encoder + Decoder # Instantiate Autoencoder Model autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder') autoencoder.summary() autoencoder.compile(loss='mse', optimizer='adam') # Train the autoencoder autoencoder.fit(x_train_noisy, x_train, validation_data=(x_test_noisy, x_test), epochs=options.epochs, batch_size=batch_size) # Predict the Autoencoder output from corrupted test imformation x_decoded = autoencoder.predict(x_test_noisy) # Draw Comparision Plots c = TCanvas("c", "c", 700, 700) fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00) fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29) fPads1.SetBottomMargin(0.007) fPads1.SetLeftMargin(0.10) fPads1.SetRightMargin(0.03) fPads2.SetLeftMargin(0.10) fPads2.SetRightMargin(0.03) fPads2.SetBottomMargin(0.25) fPads1.Draw() fPads2.Draw() fPads1.cd() nbin = 50 min = -1. max = 1. variable = "P^{B}" lbin = (max - min) / nbin lbin = str(float((max - min) / nbin)) xtitle = branch_rec[options.branch - 1] ytitle = "Events/" + lbin + "GeV" h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_rec.Sumw2() h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_pre.Sumw2() for i in range(x_test_noisy.shape[0]): h_rec.Fill(x_test_noisy[i][options.branch - 1]) h_pre.Fill(x_decoded[i][options.branch - 1]) h_rec = UnderOverFlow1D(h_rec) h_pre = UnderOverFlow1D(h_pre) maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum()) h_rec.SetLineColor(2) h_rec.SetFillStyle(0) h_rec.SetLineWidth(2) h_rec.SetLineStyle(1) h_pre.SetLineColor(3) h_pre.SetFillStyle(0) h_pre.SetLineWidth(2) h_pre.SetLineStyle(1) h_rec.SetStats(0) h_pre.SetStats(0) h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1) h_rec.Draw("HIST") h_pre.Draw("same HIST") h_rec.GetYaxis().SetTitleSize(0.06) h_rec.GetYaxis().SetTitleOffset(0.78) theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC") theLeg.SetName("theLegend") theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.05) theLeg.AddEntry(h_rec, "Reconstruction", "L") theLeg.AddEntry(h_pre, "Prediction", "L") theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) fPads1.cd() theLeg.Draw() title = TLatex( 0.91, 0.93, "AE prediction compare with reconstruction, epochs=" + str(options.epochs)) title.SetNDC() title.SetTextSize(0.05) title.SetTextFont(42) title.SetTextAlign(31) title.SetLineWidth(2) title.Draw() fPads2.cd() h_Ratio = h_pre.Clone("h_Ratio") h_Ratio.Divide(h_rec) h_Ratio.SetLineColor(1) h_Ratio.SetLineWidth(2) h_Ratio.SetMarkerStyle(8) h_Ratio.SetMarkerSize(0.7) h_Ratio.GetYaxis().SetRangeUser(0, 2) h_Ratio.GetYaxis().SetNdivisions(504, 0) h_Ratio.GetYaxis().SetTitle("Pre/Rec") h_Ratio.GetYaxis().SetTitleOffset(0.35) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetLabelSize(0.11) h_Ratio.GetXaxis().SetLabelSize(0.1) h_Ratio.GetXaxis().SetTitleOffset(0.8) h_Ratio.GetXaxis().SetTitleSize(0.14) h_Ratio.SetStats(0) axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L") axis1.SetLineColor(1) axis1.SetLineWidth(1) for i in range(1, h_Ratio.GetNbinsX() + 1, 1): D = h_rec.GetBinContent(i) eD = h_rec.GetBinError(i) if D == 0: eD = 0.92 B = h_pre.GetBinContent(i) eB = h_pre.GetBinError(i) if B < 0.1 and eB >= B: eB = 0.92 Err = 0. if B != 0.: Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) / (B * B * B * B)) h_Ratio.SetBinContent(i, D / B) h_Ratio.SetBinError(i, Err) if B == 0.: Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) / (eB * eB * eB * eB)) h_Ratio.SetBinContent(i, D / 0.92) h_Ratio.SetBinError(i, Err) if D == 0 and B == 0: h_Ratio.SetBinContent(i, -1) h_Ratio.SetBinError(i, 0) h_Ratio.Draw("e0") axis1.Draw() c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
X1=tps1.GetX1NDC() Y1=tps1.GetY1NDC() X2=tps1.GetX2NDC() Y2=tps1.GetY2NDC() tps2=TPaveStats() h14.FindObject("stats") tps2.SetTextColor(kRed) tps2.SetLineColor(kRed) tps2.SetX1NDC(X1) tps2.SetX2NDC(X2) tps2.SetY1NDC(Y1-(Y2-Y1)) tps2.SetY2NDC(Y1) ''' legend = TLegend(0.75, 0.75, 0.89, 0.89) legend.AddEntry(h1_l1, "h1aa_h2bb", "l") legend.AddEntry(h1_l2, "h1bb_h2aa", "l") h1_l1.SetXTitle("M_h1[GeV]") h1_l1.SetYTitle("Events") h1_l1.SetLineColor(6) h1_l2.SetXTitle("M_h1[GeV]") h1_l2.SetYTitle("events") h1_l2.SetLineColor(4) h1_l1.DrawNormalized("hist") h1_l2.DrawNormalized("hist&SAMES") legend.Draw() c.SaveAs("Mass_combine_h1.png") c.SaveAs("Mass_combine_h1.root")
atlxpt = [] alegends = [] alegendsSD = [] atlxSD = [] atlxSDpt = [] comparisons = [] for x in range(0, nptbins): datalistSD.append(f.Get('pythia8_massSD' + str(x))) datalist.append(f.Get('pythia8_mass' + str(x))) MCtruth.append(f.Get('genmass' + str(x))) MCtruthSD.append(f.Get('genmassSD' + str(x))) atlx.append(ROOT.TLatex()) atlxpt.append(ROOT.TLatex()) atlxSD.append(ROOT.TLatex()) atlxSDpt.append(ROOT.TLatex()) alegends.append(TLegend(.2, .6, .89, .80)) alegendsSD.append(TLegend(.2, .6, .89, .80)) datacanvases[x].SetLeftMargin(0.15) datacanvasesSD[x].SetLeftMargin(0.15) ################################################################################################################# Get Parton Showering Unc. ps_differences = [] ps_differences_softdrop = [] for i in range(0, nptbins): temp_diff = [] temp_softdrop_diff = [] ps.append(parton_shower.Get('pythia8_unfolded_by_herwig' + str(i))) ps_softdrop.append( parton_shower.Get('pythia8_unfolded_by_herwig_softdrop' + str(i))) temp_unc = (ps[i] - datalist[i]) temp_softdrop_unc = (ps_softdrop[i] - datalistSD[i])
def limit(): method = '' channel = "bb" if INCLUDEACC: particleP = "X" else: particleP = "Z'" particle = 'b#bar{b}' multF = ZPTOBB THEORY = ['A1', 'B3'] if INCLUDEACC: THEORY.append('SSM') suffix = "_" + BTAGGING if ISMC: suffix += "_MC" if SY: suffix += "_comb" #if method=="cls": suffix="_CLs" if INCLUDEACC: suffix += "_acc" if SY: filename = "./combine/limits/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt" else: filename = "./combine/limits/" + BTAGGING + "/" + YEAR + "_M%d.txt" if CATEGORY != "": if SY: if CATEGORY == 'bb_bq': filename = filename.replace( BTAGGING + "/combined_run2/", BTAGGING + "/combined_run2/" + CATEGORY + "_combined_") else: filename = filename.replace( BTAGGING + "/combined_run2/", BTAGGING + "/single_category/combined_run2/" + CATEGORY + "_") else: filename = filename.replace( BTAGGING + "/", BTAGGING + "/single_category/" + CATEGORY + "_") suffix += "_" + CATEGORY if ISMC: filename = filename.replace(".txt", "_MC.txt") mass, val = fillValues(filename) #print "mass =",mass #print "val =", val Obs0s = TGraph() Exp0s = TGraph() Exp1s = TGraphAsymmErrors() Exp2s = TGraphAsymmErrors() Sign = TGraph() pVal = TGraph() Best = TGraphAsymmErrors() Theory = {} for i, m in enumerate(mass): if not m in val: print "Key Error:", m, "not in value map" continue if INCLUDEACC: acc_factor = ACCEPTANCE[m] else: acc_factor = 1. n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor) Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp1s.SetPointError(n, 0., 0., (val[m][3] - val[m][2]) * multF * acc_factor, (val[m][4] - val[m][3]) * multF * acc_factor) Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp2s.SetPointError(n, 0., 0., (val[m][3] - val[m][1]) * multF * acc_factor, (val[m][5] - val[m][3]) * multF * acc_factor) if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6]) if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7]) if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8]) if len(val[m]) > 10: Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10]) #print "m =", m, " --> Xsec*Br =", val[m][3] for t in THEORY: Theory[t] = TGraphAsymmErrors() Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z'] for m in sorted(Xs_dict.keys()): if INCLUDEACC and t != 'SSM': acc_factor = ACCEPTANCE[m] else: acc_factor = 1. if m < SIGNALS[0] or m > SIGNALS[-1]: continue #if m < mass[0] or m > mass[-1]: continue #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs if m > 4500: continue XsZ, XsZ_Up, XsZ_Down = 0., 0., 0. if t != 'SSM': XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][ m] #assuming the same BR as the SSM Z' one XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1., HVT[t]['Z']['PDF'][m][0] - 1.)) XsZ_Down = XsZ * (1. - math.hypot(1. - HVT[t]['Z']['QCD'][m][0], 1. - HVT[t]['Z']['PDF'][m][0])) else: XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m] XsZ_Up = XsZ * (1. + math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1., HVT['A1']['Z']['PDF'][m][0] - 1.)) XsZ_Down = XsZ * (1. - math.hypot(1. - HVT['A1']['Z']['QCD'][m][0], 1. - HVT['A1']['Z']['PDF'][m][0])) n = Theory[t].GetN() Theory[t].SetPoint(n, m, XsZ * acc_factor) Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor, (XsZ_Up - XsZ) * acc_factor) Theory[t].SetLineColor(theoryLineColor[t]) Theory[t].SetFillColor(theoryFillColor[t]) Theory[t].SetFillStyle(theoryFillStyle[t]) Theory[t].SetLineWidth(2) #Theory[t].SetLineStyle(7) Exp2s.SetLineWidth(2) Exp2s.SetLineStyle(1) Obs0s.SetLineWidth(3) Obs0s.SetMarkerStyle(0) Obs0s.SetLineColor(1) Exp0s.SetLineStyle(2) Exp0s.SetLineWidth(3) Exp1s.SetFillColor(417) #kGreen+1 Exp1s.SetLineColor(417) #kGreen+1 Exp2s.SetFillColor(800) #kOrange Exp2s.SetLineColor(800) #kOrange Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25) Exp2s.GetXaxis().SetNoExponent(True) Exp2s.GetXaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetTitle( "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP + " #rightarrow " + particle + "){} (fb)".format(" #times #Alpha" if INCLUDEACC else "")) Exp2s.GetYaxis().SetTitleOffset(1.5) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetMoreLogLabels() Sign.SetLineWidth(2) Sign.SetLineColor(629) Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1) Sign.GetYaxis().SetTitle("Significance") pVal.SetLineWidth(2) pVal.SetLineColor(629) pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1) pVal.GetYaxis().SetTitle("local p-Value") Best.SetLineWidth(2) Best.SetLineColor(629) Best.SetFillColor(629) Best.SetFillStyle(3003) Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1) Best.GetYaxis().SetTitle("Best Fit (pb)") c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetLeftMargin(0.12) c1.GetPad(0).SetTicks(1, 1) #c1.GetPad(0).SetGridx() #c1.GetPad(0).SetGridy() c1.GetPad(0).SetLogy() Exp2s.Draw("A3") Exp1s.Draw("SAME, 3") for t in THEORY: Theory[t].Draw("SAME, L3") Theory[t].Draw("SAME, L3X0Y0") Exp0s.Draw("SAME, L") if not options.blind: Obs0s.Draw("SAME, L") #setHistStyle(Exp2s) Exp2s.GetXaxis().SetTitleSize(0.050) Exp2s.GetYaxis().SetTitleSize(0.050) Exp2s.GetXaxis().SetLabelSize(0.045) Exp2s.GetYaxis().SetLabelSize(0.045) Exp2s.GetXaxis().SetTitleOffset(0.90) Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetYaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetNoExponent(True) if INCLUDEACC: Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3) else: Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3) #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2) #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6)) Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1]) #drawAnalysis(channel) drawAnalysis("") #drawRegion(channel, True) drawRegion("", True) #drawCMS(LUMI, "Simulation Preliminary") #Preliminary if CATEGORY == "": #drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawCMS(LUMI, "Preliminary") #drawCMS(LUMI, "", suppressCMS=True) else: #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True) drawCMS(LUMI, "Preliminary " + CAT_LABELS[CATEGORY]) #drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True) # legend top = 0.9 nitems = 4 + len(THEORY) leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top) #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL upper limits") leg.AddEntry(Obs0s, "Observed", "l") leg.AddEntry(Exp0s, "Expected", "l") leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f") leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f") for t in THEORY: leg.AddEntry(Theory[t], theoryLabel[t], "fl") leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.045) latex.SetTextFont(42) #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h") leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225) leg2.SetBorderSize(0) leg2.SetFillStyle(0) #1001 leg2.SetFillColor(0) c1.GetPad(0).RedrawAxis() leg2.Draw() if not options.blind: Obs0s.Draw("SAME, L") c1.GetPad(0).Update() if not gROOT.IsBatch(): raw_input("Press Enter to continue...") c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".png") c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C") c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".root") for t in THEORY: print "Model", t, ":", for m in range(mass[0], mass[-1], 1): if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == ( Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)): print m, "(obs)", if not (Theory[t].Eval(m) > Exp0s.Eval(m)) == ( Theory[t].Eval(m + 1) > Exp0s.Eval(m + 1)): print m, "(exp)", print "" return ##FIXME # ---------- Significance ---------- c2 = TCanvas("c2", "Significance", 800, 600) c2.cd() c2.GetPad(0).SetTopMargin(0.06) c2.GetPad(0).SetRightMargin(0.05) c2.GetPad(0).SetTicks(1, 1) c2.GetPad(0).SetGridx() c2.GetPad(0).SetGridy() Sign.GetYaxis().SetRangeUser(0., 5.) Sign.Draw("AL3") drawCMS(LUMI, "Preliminary") #drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png") c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf") # c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root") # c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C") # ---------- p-Value ---------- c3 = TCanvas("c3", "p-Value", 800, 600) c3.cd() c3.GetPad(0).SetTopMargin(0.06) c3.GetPad(0).SetRightMargin(0.05) c3.GetPad(0).SetTicks(1, 1) c3.GetPad(0).SetGridx() c3.GetPad(0).SetGridy() c3.GetPad(0).SetLogy() pVal.Draw("AL3") pVal.GetYaxis().SetRangeUser(2.e-7, 0.5) ci = [ 1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303, 0.000000001973 ] line = TLine() line.SetLineColor(922) line.SetLineStyle(7) text = TLatex() text.SetTextColor(922) text.SetTextSize(0.025) text.SetTextAlign(12) for i in range(1, len(ci) - 1): line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2, pVal.GetXaxis().GetXmax(), ci[i] / 2) text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2, "%d #sigma" % i) drawCMS(LUMI, "Preliminary") #drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png") c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf") # c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root") # c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C") # --------- Best Fit ---------- c4 = TCanvas("c4", "Best Fit", 800, 600) c4.cd() c4.GetPad(0).SetTopMargin(0.06) c4.GetPad(0).SetRightMargin(0.05) c4.GetPad(0).SetTicks(1, 1) c4.GetPad(0).SetGridx() c4.GetPad(0).SetGridy() Best.Draw("AL3") drawCMS(LUMI, "Preliminary") #drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png") c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf") # c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root") # c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C") if not gROOT.IsBatch(): raw_input("Press Enter to continue...") if 'ah' in channel: outFile = TFile("bands.root", "RECREATE") outFile.cd() pVal.Write("graph") Best.Write("best") outFile.Close()
def plotEfficiency(effs, outName, outFile): cv = TCanvas(outName, outName, 800, 600) leg = TLegend(0.65, 0.2, 0.95, 0.4) gr_effs = [] mg = TMultiGraph() cv.cd() cv.SetGridx() cv.SetGridy() cv.SetLeftMargin(0.13) cv.SetRightMargin(0.04) cv.SetBottomMargin(0.15) cv.SetTopMargin(0.085) effs[0].Draw("AP") cv.Update() gr_effs.append(effs[0].GetPaintedGraph()) for i in range(1, len(effs)): effs[i].Draw("same") cv.Update() gr_effs.append(effs[i].GetPaintedGraph()) cv.Update() chopcolor = int(len(gr_effs)) chopmarker = int(len(gr_effs) / 2) for i in range(len(gr_effs)): gr_effs[i].SetMarkerSize(1.5) gr_effs[i].SetLineWidth(2) gr_effs[i].GetYaxis().SetRangeUser(0.0, 1.0) if int(i / chopmarker) == 0: gr_effs[i].SetMarkerStyle(22) #triangle elif int(i / chopmarker) == 1: gr_effs[i].SetMarkerStyle(21) #square elif int(i / chopmarker) == 2: gr_effs[i].SetMarkerStyle(20) #circle if int(i % chopcolor) == 0: gr_effs[i].SetMarkerColor(632 - 7) gr_effs[i].SetLineColor(632 - 7) elif int(i % chopcolor) == 1: gr_effs[i].SetMarkerColor(600 - 7) gr_effs[i].SetLineColor(600 - 7) elif int(i % chopcolor) == 2: gr_effs[i].SetMarkerColor(416 - 7) gr_effs[i].SetLineColor(416 - 7) else: gr_effs[i].SetMarkerColor(432 - 7) gr_effs[i].SetLineColor(432 - 7) leg.AddEntry(gr_effs[i]) for i, gr in enumerate(gr_effs): mg.Add(copy.deepcopy(gr_effs[i])) leg.SetTextFont(132) leg.SetTextSize(0.03) leg.SetFillColor(0) leg.SetLineColor(0) leg.SetShadowColor(0) mg.Draw("AP") leg.Draw("SAME") cv.Update() g_PlotTitle = outName mg.GetXaxis().SetTitle('Muon pT (GeV)') mg.GetYaxis().SetTitle("#epsilon") l = TLatex() l.SetTextFont(132) l.SetNDC() l.SetTextSize(0.035) l.SetTextFont(42) l.SetTextSize(0.03) l.SetTextFont(61) l.DrawLatex(0.16, 0.92, "CMS") l.SetTextFont(52) l.DrawLatex(0.21, 0.92, "Preliminary") l.SetTextFont(132) l.SetNDC() l.SetTextSize(0.05) l.SetTextFont(132) l.DrawLatex(0.40, 0.92, g_PlotTitle) cv.Update() outFile.cd() outFile.WriteTObject(cv) cv.Close()
def limit2HDM(): global signals signals = range(800, 2000 + 1, 50) multF = HTOBB THEORY = ['T1', 'T2'] mass, val = fillValues("./combine/AZh/AZh_M%d.txt") Obs0s = TGraph() Exp0s = TGraph() Exp1s = TGraphAsymmErrors() Exp2s = TGraphAsymmErrors() massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt") Obs0sB = TGraph() Exp0sB = TGraph() Exp1sB = TGraphAsymmErrors() Exp2sB = TGraphAsymmErrors() for i, m in enumerate(mass): if not m in val: print "Key Error:", m, "not in value map" continue n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF) Exp0s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF, val[m][4] * multF - val[m][3] * multF) Exp2s.SetPoint(n, m, val[m][3] * multF) Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF, val[m][5] * multF - val[m][3] * multF) Obs0sB.SetPoint(n, m, valB[m][0] * multF) Exp0sB.SetPoint(n, m, valB[m][3] * multF) Exp1sB.SetPoint(n, m, valB[m][3] * multF) Exp1sB.SetPointError(n, 0., 0., valB[m][3] * multF - valB[m][2] * multF, valB[m][4] * multF - valB[m][3] * multF) Exp2sB.SetPoint(n, m, valB[m][3] * multF) Exp2sB.SetPointError(n, 0., 0., valB[m][3] * multF - valB[m][1] * multF, valB[m][5] * multF - valB[m][3] * multF) col = 629 Exp2s.SetLineWidth(2) Exp2s.SetLineStyle(1) Obs0s.SetLineWidth(3) Obs0s.SetMarkerStyle(0) Obs0s.SetLineColor(1) Exp0s.SetLineStyle(2) Exp0s.SetLineWidth(3) Exp0s.SetLineColor(1) # Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1 # Exp1s.SetLineColorAlpha(col, 0.4) # Exp2s.SetFillColorAlpha(col, 0.2) #kOrange # Exp2s.SetLineColorAlpha(col, 0.2) Exp1s.SetFillColor(417) Exp1s.SetLineColor(417) Exp2s.SetFillColor(800) Exp2s.SetLineColor(800) colB = 922 Exp2sB.SetLineWidth(2) Obs0sB.SetLineStyle(9) Obs0sB.SetLineWidth(3) Obs0sB.SetMarkerStyle(0) Obs0sB.SetLineColor(colB) Exp0sB.SetLineStyle(8) Exp0sB.SetLineWidth(3) Exp0sB.SetLineColor(colB) Exp1sB.SetFillColorAlpha(colB, 0.4) #kGreen+1 Exp1sB.SetLineColorAlpha(colB, 0.4) Exp2sB.SetFillColorAlpha(colB, 0.2) #kOrange Exp2sB.SetLineColorAlpha(colB, 0.2) Exp2s.GetXaxis().SetTitle("m_{A} (GeV)") Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25) Exp2s.GetXaxis().SetNoExponent(True) Exp2s.GetXaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetTitle( "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)" ) Exp2s.GetYaxis().SetTitleOffset(1.5) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetMoreLogLabels() Theory = {} #for t in THEORY: # Theory[t] = TGraphAsymmErrors() # for m in sorted(THDM[t]['ggA'].keys()): # if m < mass[0] or m > mass[-1]: continue # Xs, Xs_Up, Xs_Down = 0., 0., 0. # Xs = THDM[t]['ggA'][m] # Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2)) # Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2)) # n = Theory[t].GetN() # Theory[t].SetPoint(n, m, Xs) # Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs)) # Theory[t].SetLineColor(theoryLineColor[t]) # Theory[t].SetFillColor(theoryFillColor[t]) # Theory[t].SetFillStyle(theoryFillStyle[t]) # Theory[t].SetLineWidth(2) # #Theory[t].SetLineStyle(7) c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetLeftMargin(0.12) c1.GetPad(0).SetTicks(1, 1) c1.GetPad(0).SetLogy() Exp2s.Draw("A3") Exp1s.Draw("SAME, 3") Exp0s.Draw("SAME, L") # Exp2sB.Draw("SAME, 3") # Exp1sB.Draw("SAME, 3") Exp0sB.Draw("SAME, L") if not options.blind: Obs0s.Draw("SAME, L") Obs0sB.Draw("SAME, L") for t in THEORY: Theory[t].Draw("SAME, L3") Theory[t].Draw("SAME, L3X0Y0") #setHistStyle(Exp2s) # Exp2s.GetXaxis().SetTitleSize(0.045) # Exp2s.GetYaxis().SetTitleSize(0.04) # Exp2s.GetXaxis().SetLabelSize(0.04) # Exp2s.GetYaxis().SetLabelSize(0.04) # Exp2s.GetXaxis().SetTitleOffset(1) # Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetXaxis().SetTitleSize(0.050) Exp2s.GetYaxis().SetTitleSize(0.050) Exp2s.GetXaxis().SetLabelSize(0.045) Exp2s.GetYaxis().SetLabelSize(0.045) Exp2s.GetXaxis().SetTitleOffset(0.90) Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetYaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3) Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1]) drawAnalysis('AZh') drawRegion('AZHsl', True) drawCMS(LUMI, "") #Preliminary #drawCMS(LUMI, "Work in Progress", suppressCMS=True) # legend leg = TLegend(0.6, 0.90, 0.99, 0.90) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL upper limits") leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh", "") #"95% CL upper limits" leg.AddEntry(Obs0s, "Observed", "l") leg.AddEntry(Exp0s, "Expected", "l") leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f") leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f") leg.AddEntry(None, "", "") leg.AddEntry(None, "bbA #rightarrow Zh", "") leg.AddEntry(Obs0sB, "Observed", "l") leg.AddEntry(Exp0sB, "Expected", "l") leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045) leg.Draw() # latex = TLatex() # latex.SetNDC() # latex.SetTextSize(0.040) # latex.SetTextFont(42) # latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1") # legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4) legB = TLegend(0.15, 0.27, 0.68, 0.27) legB.SetBorderSize(0) legB.SetFillStyle(0) #1001 legB.SetFillColor(0) for t in THEORY: legB.AddEntry(Theory[t], theoryLabel[t], "fl") legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "") legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045) legB.Draw() c1.GetPad(0).RedrawAxis() leg.Draw() c1.Update() if not gROOT.IsBatch(): raw_input("Press Enter to continue...") c1.Print("plotsLimit/Exclusion/THDM.png") c1.Print("plotsLimit/Exclusion/THDM.pdf")
def __init__(self): tk.Frame.__init__(self, master=master) ROOT.gROOT.SetBatch(ROOT.kFALSE) #ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.gStyle.SetOptStat(0) da = TDatime(2010, 3, 30, 13, 10, 00) c = TCanvas("Luminosity", "", 1) c.SetHighLightColor(2) c.Range(-125.6732, -0.1364721, 1123.878, 1.178117) c.SetFillColor(0) c.SetBorderMode(0) c.SetBorderSize(2) c.SetGridx() c.SetGridy() c.SetFrameFillColor(19) c.SetFrameBorderMode(0) c.SetFrameBorderMode(0) h1f = TH1F("Luminposity", "", 1000, 0., 1000) h1f.GetXaxis().SetNdivisions(-503) h1f.GetXaxis().SetTimeDisplay(1) h1f.GetXaxis().SetTimeFormat("%d\/%m %H:%M") h1f.GetXaxis().SetTimeOffset(da.Convert()) h1f.GetXaxis().SetLabelFont(32) h1f.GetXaxis().SetLabelSize(0.03) h1f.GetXaxis().SetTitleFont(32) h1f.GetXaxis().SetTitle("Date") h1f.GetYaxis().SetLabelFont(32) h1f.GetYaxis().SetLabelSize(0.03) h1f.GetYaxis().SetTitleFont(32) h1f.GetYaxis().SetTitle("L (#mub^{-1})") for i in range(0, 1000): #h1f.GetXaxis().FindBin() ## Ricordati di calcolare il bin corretto per il tuo tempo h1f.SetBinContent(i, 20.2 + i) h1f.Draw() h1f2 = TH1F("Luminposity 2", "", 1000, 0., 1000) h1f2.GetXaxis().SetNdivisions(-503) h1f2.GetXaxis().SetTimeDisplay(1) h1f2.GetXaxis().SetTimeFormat("%d\/%m %H:%M") h1f2.GetXaxis().SetTimeOffset(da.Convert()) h1f2.GetXaxis().SetLabelSize(0.03) for i in range(0, 1000): h1f2.SetBinContent(i, 20.2 - i) h1f2.SetLineColor(ROOT.kRed) h1f2.Draw("same") leg = TLegend(0.1537356, 0.6631356, 0.5344828, 0.875) leg.SetTextFont(32) leg.SetFillColor(0) leg.SetFillStyle(1001) leg.AddEntry(h1f, "Delibvered 1.54 nb^{-1}", "l") leg.AddEntry(h1f2, "Delibvered 1.59 nb^{-1}", "l") leg.Draw() #c.Modified(); #c.cd(); #c.SetSelected(h1f); #c.SaveAs("Zhen.jpg") self.pack() button = tk.Button(master=master, text='Quit', command=sys.exit) button.pack(side=tk.BOTTOM) tk.mainloop()
def limitCompare(method): signal, particle, particleP = "XVH", "V", "V'" channels = [ "ah", "wrhpbb", "wrhpb", "wrlpbb", "wrlpb", "zrhpbb", "zrhpb", "zrlpbb", "zrlpb" ] colors = [ 1, 610 + 4, 632, 800 + 7, 800, 416 + 1, 860 + 10, 600, 616, 921, 922 ] masses, vals, graphs = {}, {}, {} for j, c in enumerate(channels): masses[c], vals[c] = fillValues("./combine/" + method + "/" + signal + c + "_M%d.txt") graphs[c] = TGraph() n = 0 #print vals[c] for i, m in enumerate(masses[c]): #if not signals[i] >= 1000: continue graphs[c].SetPoint(n, m, vals[c][m][3]) n = n + 1 graphs[c].SetLineColor(colors[j]) graphs[c].SetLineWidth(3) graphs[c].Draw("SAME, L") c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetTicks(1, 1) c1.GetPad(0).SetLogy() for c in channels: graphs[c].Draw("AL" if 'ah' in c else "SAME, L") graphs[channels[0]].GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1]) graphs[channels[0]].GetYaxis().SetRangeUser(0.25, 2.5e4) graphs[channels[0]].GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") graphs[channels[0]].GetYaxis().SetTitle( "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP + " #rightarrow " + particle + "H) #bf{#it{#Beta}}(H #rightarrow bb) (fb)") drawAnalysis(signal) #drawRegion(signal, True) drawCMS(LUMI, "Preliminary") #drawCMS(LUMI, "Work in Progress", suppressCMS=True) # legend top = 0.9 leg = TLegend(0.4, top - len(channels) * 0.2 / 5., 0.99, top) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL expected limits") for c in channels: leg.AddEntry(graphs[c], getChannel(c), "l") leg.Draw() c1.Update() c1.Print("plotsLimit/Multi.png") c1.Print("plotsLimit/Multi.pdf")
def readHists(postfix=""): hstack = THStack("hstack","hstack") hstack.SetTitle("#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} 41.53 fb^{-1}(13TeV)}") inputfile = read_rootfile(postfix) gROOT.cd() dirName = "ttH_"+region+"_"+Channels[0] h0 = inputfile.Get("shapes_"+fit_type+"/"+dirName+"/total") h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray+3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") h_totalmc.SetMinimum(0.8) h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) latexString ="" expString =" SM Exp" dataString =" Data Obs" latexString += ("\\begin{frame}\n\\frametitle{"+POI.replace("_","\_")+" "+fit_type.replace("_","\_")+"}\n\\begin{table}[]\n\scalebox{0.38}{\n\\begin{tabular}{"+"l"*(2+len(Channels))+"}\n") for channel in Channels: FitDir = inputfile.Get("shapes_"+fit_type) directory = "shapes_"+fit_type+"/ttH_"+region+"_"+channel+"/" SkipChannel = False if not FitDir.GetListOfKeys().Contains("ttH_"+region+"_"+channel): print " skip " + directory SkipChannel = True else: h_bkg = inputfile.Get(directory+"total_background").Clone(directory+"total_background") h_totalbkg.Add(h_bkg) h_sig = inputfile.Get(directory+"total_signal").Clone(directory+"total_signal") h_totalsig.Add(h_sig) h_total = inputfile.Get(directory+"total").Clone(directory+"total") h_totalmc.Add(h_total) g_data = inputfile.Get(directory+"data").Clone(directory+"data") h_data = h_total.Clone("h_data") h_data.Reset() TGraphToTH1(h_data, g_data) h_dataobs.Add(h_data) if not SkipChannel: SM_error = ROOT.Double(0) h_total.IntegralAndError(0,h_total.GetNbinsX(),SM_error) expString += " & $ "+str(round(h_total.Integral(),2))+" \\pm "+str(round(SM_error,2))+"$" data_error = ROOT.Double(0) h_data.IntegralAndError(0,h_data.GetNbinsX(),data_error) dataString += " & $ "+str(round(h_data.Integral(),2))+" \\pm "+str(round(data_error,2))+"$" else: expString += " & - " dataString += " & - " latexString += ("& "+channel.replace("_","\_")+" ") totMC_error = ROOT.Double(0) h_totalmc.IntegralAndError(0,h_totalmc.GetNbinsX(),totMC_error) expString += " & $ "+str(round(h_totalmc.Integral(),2))+" \\pm "+str(round(totMC_error,2))+"$ \\\\ \n" totdata_error = ROOT.Double(0) h_dataobs.IntegralAndError(0,h_dataobs.GetNbinsX(),totdata_error) dataString += " & $ "+str(round(h_dataobs.Integral(),2))+" \\pm "+str(round(totdata_error,2))+"$ \n" latexString += "& total "+ region +" \\\\ \n" legend = TLegend(0.2,0.6,0.8,0.88) #legend.SetHeader("2017 "+fit_type+", 2lss l^{#pm}l^{#pm} #mu(ttH)=#hat#mu") legend.SetHeader("2017 "+fit_type+", "+header_postfix) legend.SetNColumns(3) legend.SetBorderSize(0) Samples.reverse() for sample in Samples: hist=h_totalsig.Clone(sample) hist.Reset() latexString += sample for channel in Channels: h_sample =hist.Clone(sample+"_sample") h_sample.Reset() latexString += " & " for p in Process[sample]: histname = "shapes_"+fit_type+"/ttH_"+region+"_"+channel+"/"+p h1 = inputfile.Get(histname) if h1: #print h1.Integral() hist.Add(h1) h_sample.Add(h1) if h_sample.Integral()>0.05: error = ROOT.Double(0) h_sample.IntegralAndError(0,h_sample.GetNbinsX(),error) latexString += "$ "+str(round(h_sample.Integral(),2))+" \\pm "+str(round(error,2))+"$" elif h_sample.Integral()>0: latexString += " \\textless{}0.05" else: latexString += " - " if hist.Integral()>0: hist.SetDirectory(0) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist,sample,"f") if hist.Integral()>0.05: IntegralError = ROOT.Double(0) hist.IntegralAndError(0,hist.GetNbinsX(),IntegralError) latexString += " & $ "+str(round(hist.Integral(),2))+" \\pm "+str(round(IntegralError,2))+" $ \\\\ \n" else: latexString += " & \\textless{}0.05 \\\\ \n" else: latexString += " & - \\\\ \n" latexString += (expString + dataString) latexString += ("\\end{tabular}\n}\n\\end{table}\n\\end{frame}\n \\end{document}\n") if LATEX==1 : latexfile = file(DirOfRootplas+SubCat+"/"+POI+"/"+SubCat+"_"+POI+"_"+region+"_"+fit_type+"_"+SPLIT+"_"+Expected+"_yield.tex","w") latexfile.write("\\documentclass{beamer}\n\\usetheme{Warsaw}\n\n\\usepackage{graphicx}\n\\useoutertheme{infolines}\n\\setbeamertemplate{headline}{}\n\n\\begin{document}\n\n") latexfile.write(latexString) inputfile.Close() return h_totalsig, h_totalbkg, h_totalmc, h_dataobs, hstack, legend
def show(self, outDir, genPseudoData): if len(self.mc) == 0: print '%s is empty' % self.name return canvas = TCanvas('c_' + self.name, 'C', 600, 600) canvas.cd() t1 = TPad("t1", "t1", 0.0, 0.20, 1.0, 1.0) t1.SetBottomMargin(0) t1.Draw() t1.cd() self.garbageList.append(t1) frame = None # leg = TLegend(0.15,0.9,0.9,0.95) leg = TLegend(0.6, 0.7, 0.92, 0.89) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.04) nlegCols = 0 maxY = 1.0 if self.data is not None: leg.AddEntry(self.data, self.data.GetTitle(), 'p') frame = self.data.Clone('frame') self.garbageList.append(frame) maxY = self.data.GetMaximum() * 1.1 frame.Reset('ICE') elif genPseudoData: leg.AddEntry('pseudodata', 'Pseudo-data', 'p') totalMC = None stack = THStack('mc', 'mc') for h in self.mc: stack.Add(h, 'hist') leg.AddEntry(h, h.GetTitle(), 'f') nlegCols = nlegCols + 1 if totalMC is None: totalMC = h.Clone('totalmc') self.garbageList.append(totalMC) totalMC.SetDirectory(0) else: totalMC.Add(h) if totalMC is not None: maxY = max(totalMC.GetMaximum(), maxY) if frame is None: frame = totalMC.Clone('frame') frame.Reset('ICE') self.garbageList.append(frame) if genPseudoData and self.data is None and totalMC.ClassName( ).find('TH1') >= 0: self.data = totalMC.Clone('pseudodata') self.data.Sumw2() self.data.SetLineColor(1) self.data.SetMarkerStyle(20) self.data.SetMarkerColor(1) self.data.SetFillStyle(0) self.data.SetFillColor(0) if self.name.find('flow') < 0: self.data.Reset('ICE') for i in xrange(0, int(totalMC.Integral())): self.data.Fill(totalMC.GetRandom()) if self.data is not None: nlegCols = nlegCols + 1 if nlegCols == 0: print '%s is empty' % self.name return frame.GetYaxis().SetRangeUser(1e-2, 1.2 * maxY) frame.SetDirectory(0) frame.Draw() frame.GetYaxis().SetTitleOffset(1.6) stack.Draw('hist same') if self.data is not None: self.data.Draw('P same') # leg.SetNColumns(nlegCols) leg.SetNColumns(2) leg.Draw() ## Draw CMS Preliminary label tlat = TLatex() tlat.SetNDC() tlat.SetTextFont(62) tlat.SetTextSize(0.04) tlat.SetTextAlign(31) # prelim_text = 'CMS Preliminary, #sqrt{s} = 8 TeV' prelim_text = 'CMS Preliminary, #sqrt{s} = 13 TeV' tlat.DrawLatex(0.92, 0.95, prelim_text) if totalMC is None or self.data is None: t1.SetPad(0, 0, 1, 1) t1.SetBottomMargin(0.12) else: canvas.cd() t2 = TPad("t2", "t2", 0.0, 0.0, 1.0, 0.2) self.garbageList.append(t2) t2.SetTopMargin(0) t2.SetBottomMargin(0.4) t2.SetGridy() t2.Draw() t2.cd() ratio = self.data.Clone('ratio') self.garbageList.append(ratio) ratio.Divide(totalMC) ratio.SetDirectory(0) ratio.Draw('e1') ratio.GetYaxis().SetRangeUser(0.62, 1.38) ratio.GetYaxis().SetTitle('Data/#SigmaBkg') ratio.GetYaxis().SetNdivisions(5) ratio.GetYaxis().SetLabelSize(0.15) ratio.GetYaxis().SetTitleSize(0.18) ratio.GetXaxis().SetLabelSize(0.18) ratio.GetXaxis().SetTitleSize(0.2) ratio.GetYaxis().SetTitleOffset(0.3) ratio.GetXaxis().SetTitleOffset(0.8) canvas.cd() canvas.Modified() canvas.Update() for ext in ['pdf', 'png']: canvas.SaveAs(outDir + '/' + self.name + '.' + ext)