def getEff(name, den_input, num_input, rebin=0, xtitle='', ytitle=''): c = TCanvas(name + '_Canvas') legend = TLegend(0.8, 0.1, 0.999, 0.6) legend.SetFillColor(kWhite) den = den_input.Clone() num = num_input.Clone() if rebin != 0: den.Rebin(rebin) num.Rebin(rebin) error_bars = TGraphAsymmErrors() error_bars.Divide(num, den, "cl=0.683 b(1,1) mode") error_bars.SetLineWidth(3) if xtitle == '': error_bars.GetXaxis().SetTitle(num.GetXaxis().GetTitle()) else: error_bars.GetXaxis().SetTitle(xtitle) if ytitle == '': error_bars.GetYaxis().SetTitle(num.GetYaxis().GetTitle()) else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.GetXaxis().SetRangeUser(400, 2000) error_bars.SetLineColor(kBlack) error_bars.SetMaximum(1.01) error_bars.SetMinimum(0.) if ytitle == '': error_bars.GetYaxis().SetTitle("Trigger rate") else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.SetTitle('') error_bars.Draw('AP') c.SaveAs('pdf/' + name + '.pdf') c.Write(name + '_Canvas') error_bars.Write(name)
def createAssymSFFile(filename, sftable, name): """Create histogram from table.""" print(">>> Creating '%s'..." % filename) file = TFile(filename, 'RECREATE') file.cd() x = [float(i) + 0.5 for i in range(len(sftable.keys()))] ex = [0.0] * len(sftable.keys()) x_names = sorted(sftable.keys()) y = [sftable[k]['val'] for k in x_names] eyl = [sftable[k]['down'] for k in x_names] eyh = [sftable[k]['up'] for k in x_names] g = TGraphAsymmErrors(len(x), np.array(x), np.array(y), np.array(ex), np.array(ex), np.array(eyl), np.array(eyh)) g.GetXaxis().SetNdivisions(len(x) * 2) g.GetXaxis().ChangeLabel(0, -1, 0, -1, -1, -1, "") for i in x: print(1 + int(i), x_names[int(i)]) g.GetXaxis().ChangeLabel(2 + int(i) * 2, -1, 0) g.GetXaxis().ChangeLabel(1 + int(i) * 2, -1, -1, -1, -1, -1, x_names[int(i)]) g.Write(name) # file.ls() ; g.Draw("A*") ; raw_input() file.Close() return file
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = TCanvas() c.SetLogy() #Draw input histograms hists = ['h_frac_recoil_', 'h_full_recoil_'] label = ['recoil with MET triggers', 'recoil without MET triggers'] combineHist(hists, label, leg) #leg.Draw() #c.SaveAs("Combinehists_D.pdf") ratio = [] h1 = f.Get('h_frac_recoil_') #h1=setHistStyle(h1,bins) h2 = f.Get('h_full_recoil_') #h2=setHistStyle(h2,bins) h3 = createRatio(h1, h2) gr = TGraphAsymmErrors(h1, h2) gr.GetXaxis().SetRangeUser(0, 1500) gr.GetYaxis().SetRangeUser(0, 1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(0.5) gr.SetLineColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("Recoil [GeV]") gr.SetTitle("") # print ("ratio",ratio ) # c, pad1, pad2 = createCanvasPads() # # # draw everything # pad1.cd() # h1.Draw() # h2.Draw("same") # to avoid clipping the bottom zero, redraw a small axis # h1.GetYaxis().SetLabelSize(0.0) # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") # axis.SetLabelFont(43) # axis.SetLabelSize(15) # axis.Draw() # pad2.cd() gr.Draw() latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() #h3.Draw('pl') c.SaveAs("test.pdf")
def eff(wrps, option='cl=0.683 b(1,1) mode'): """ Applies to HistoWrappers only. Returns GraphWrapper. Takes lumi from first. >>> from ROOT import TH1I >>> h1 = TH1I("h1", "", 2, .5, 2.5) >>> h1.Fill(1) 1 >>> h1.Fill(1) 1 >>> w1 = wrappers.HistoWrapper(h1, lumi=2) >>> h2 = TH1I("h2", "", 2, .5, 2.5) >>> h2.Sumw2() >>> h2.Fill(1) 1 >>> h2.Fill(1) 1 >>> h2.Fill(1) 1 >>> h2.Fill(2) 2 >>> w2 = wrappers.HistoWrapper(h2, lumi=3) >>> w3 = eff([w1, w2]) >>> w3.graph.GetN() 2 >>> hi = w3.graph.GetErrorYhigh(0) >>> lo = w3.graph.GetErrorYlow(0) >>> abs(hi - 0.189572034007) < 1e-10 True >>> abs(lo - 0.236650832868) < 1e-10 True """ wrps = iterableize(wrps) wrps = iter(wrps) try: nominator = next(wrps) denominator = next(wrps) except StopIteration: raise TooFewWrpsError("eff needs exactly two Wrappers.") try: wrps.next() raise TooManyWrpsError("eff needs exactly two Wrappers.") except StopIteration: pass if not isinstance(nominator, wrappers.HistoWrapper): raise WrongInputError( "eff needs nominator to be of type HistoWrapper. nominator: " + str(nominator) ) if not isinstance(denominator, wrappers.HistoWrapper): raise WrongInputError( "eff needs denominator to be of type HistoWrapper. denominator: " + str(denominator) ) graph = TGraphAsymmErrors(nominator.histo, denominator.histo, option) graph.GetXaxis().SetTitle(nominator.histo.GetXaxis().GetTitle()) graph.GetYaxis().SetTitle('efficiency') info = nominator.all_info() return wrappers.GraphWrapper(graph, **info)
def readDataIntoGraph(): f = open('HESSj1745_290.dat', "r") lines = f.readlines() x, y, yHigh, yLow = array('d'), array('d'), array('d'), array('d') # yScale = 10e12 yScale = 1 xScale = 1000 for iLine in lines: if iLine.isspace() == True or iLine[0] == '#': continue tmpList = iLine.split() tmpX = xScale * float(tmpList[0]) * float(tmpList[0]) x.append(xScale * float(tmpList[0])) y.append(yScale * float(tmpList[1]) * tmpX) yLow.append(yScale * (float(tmpList[1]) - float(tmpList[2])) * tmpX) yHigh.append(yScale * (float(tmpList[3]) - float(tmpList[1])) * tmpX) f.close() listOfZeros = array("d", [0] * len(x)) gr = TGraphAsymmErrors(len(x), x, y, listOfZeros, listOfZeros, yLow, yHigh) # gr.SetLineColor( color ) gr.SetLineWidth(2) # gr.SetMarkerColor( color ) gr.SetMarkerStyle(21) gr.GetXaxis().SetTitle('Energy [GeV]') gr.GetYaxis().SetTitle('E^{2} x Flux [GeV cm^{-2}s^{-1}]') gr.SetTitle('') return gr
def HistToAsymmErrs(name,hist) : X = [] EXlow = [] EXhigh = [] Y = [] EYlow = [] EYhigh = [] for i in range(hist.GetNbinsX()) : X .append(hist.GetBinCenter (i+1)) EXlow .append(hist.GetBinWidth (i+1)/2.) EXhigh.append(hist.GetBinWidth (i+1)/2.) Y .append(hist.GetBinContent(i+1)) EYlow .append(hist.GetBinError (i+1)) EYhigh.append(hist.GetBinError (i+1)) a_X = array('d',X ) a_EXlow = array('d',EXlow ) a_EXhigh = array('d',EXhigh ) a_Y = array('d',Y ) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) asymm = TGraphAsymmErrors(len(a_X),a_X,a_Y,a_EXlow,a_EXhigh,a_EYlow,a_EYhigh) asymm.GetXaxis().SetTitle(hist.GetXaxis().GetTitle()) asymm.GetYaxis().SetTitle(hist.GetYaxis().GetTitle()) asymm.SetLineWidth(2) asymm.SetName(name) return asymm
def QuadratureUpDown(asymlist, hists=[], doFlatUnc=False, FlatUp=0.0, FlatDown=0.0): # These are TGraphAsymmErrors total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(asymlist[0].GetN()): total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(asymlist[0].GetN()): for j in range(len(asymlist)): E_up = asymlist[j].GetEYhigh()[i] E_dn = asymlist[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # hists # for i in range(len(total_unc_up_sq)): for j in range(len(hists)): E_up = hists[j].GetBinError(i + 1) E_dn = hists[j].GetBinError(i + 1) total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # flat uncertainty # if doFlatUnc: for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] += math.pow(FlatUp * asymlist[0].GetY()[i], 2) total_unc_dn_sq[i] += math.pow(FlatDown * asymlist[0].GetY()[i], 2) # # sqrt # for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) #print 'Setting up unc to ',total_unc_up_sq[i] #print 'Setting dn unc to ',total_unc_dn_sq[i] #print total_unc_up_sq #print total_unc_dn_sq yup = array('d', total_unc_up_sq) ydn = array('d', total_unc_dn_sq) #print yup #print ydn result = TGraphAsymmErrors(asymlist[0].GetN(), asymlist[0].GetX(), asymlist[0].GetY(), asymlist[0].GetEXlow(), asymlist[0].GetEXhigh(), ydn, yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(asymlist[0].GetName() + ' Total Error') return result
def envelope(thedict, thelist, nominal): # # Takes the nominal and makes an envelope around it # diff_up = nominal.Clone() key = 'diff_up' diff_up.SetNameTitle(key, key) diff_dn = nominal.Clone() key = 'diff_dn' diff_dn.SetNameTitle(key, key) for i in range(diff_up.GetNbinsX()): diff_up.SetBinContent(i + 1, 0) diff_dn.SetBinContent(i + 1, 0) # for var in thelist: if var == 'dummy': continue for i in range(nominal.GetNbinsX()): curr_diff_up = diff_up.GetBinContent(i + 1) curr_diff_dn = diff_dn.GetBinContent(i + 1) nominal_bc = nominal.GetBinContent(i + 1) thisvar_bc = thedict[var].GetBinContent(i + 1) diff_up.SetBinContent(i + 1, max(curr_diff_up, thisvar_bc - nominal_bc)) diff_dn.SetBinContent(i + 1, min(curr_diff_dn, thisvar_bc - nominal_bc)) nbins = nominal.GetNbinsX() x = array( 'd', list(nominal.GetBinCenter(a + 1) for a in range(nominal.GetNbinsX()))) xup = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) xdn = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) y = array( 'd', list(nominal.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) yup = array( 'd', list(diff_up.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) ydn = array( 'd', list( diff_dn.GetBinContent(a + 1) * -1. for a in range(nominal.GetNbinsX()))) result = TGraphAsymmErrors(nbins, x, y, xdn, xup, ydn, yup) result.GetXaxis().SetTitle(nominal.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nominal.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(nominal.GetName() + ' Envelope') return result
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20): binning = [20, 30, 40, 50, 60, 70, 80, 100, 150, 200] c = TCanvas() if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) elif option == 'nvtx': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(vbinning) - 1, array('d', vbinning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(vbinning) - 1, array('d', vbinning)) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.BayesDivide(_ahist_, _hist_) g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return copy.deepcopy(g_efficiency)
def QuadratureUpDown(name,asymlist=[],hists=[],AddHists=False) : # These are TGraphAsymmErrors asymlist1 = [] for i in asymlist : asymlist1.append(i) for i in range(len(hists)) : asymlist1.append(HistToAsymmErrs(hists[i].GetName()+' QuadratureUpDown Asymm',hists[i])) nbins = asymlist1[0].GetN() total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(nbins) : total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist1)) : E_up = asymlist1[j].GetEYhigh()[i] E_dn = asymlist1[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up,2) total_unc_dn_sq[i] += math.pow(E_dn,2) # # # # hists # # # for i in range(nbins) : # for j in range(len(hists)) : # E_up = hists[j].GetBinError(i+1) # E_dn = hists[j].GetBinError(i+1) # total_unc_up_sq[i] += math.pow(E_up,2) # total_unc_dn_sq[i] += math.pow(E_dn,2) # # sqrt # for i in range(nbins) : total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) y = [] for i in range(nbins) : y.append(asymlist1[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist1)) : y[-1] += asymlist1[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up_sq) ydn = array('d',total_unc_dn_sq) result = TGraphAsymmErrors(asymlist1[0].GetN(),asymlist1[0].GetX(),ybincontent ,asymlist1[0].GetEXlow(),asymlist1[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist1[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist1[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20, col=1): binning = [20, 200] if args.onebin else [ 20, 30, 40, 50, 60, 70, 80, 100, 150, 200 ] if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.Divide(_ahist_, _hist_, "cl=0.683 b(1,1) mode") g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.SetMarkerColor(col) g_efficiency.SetLineColor(col) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return g_efficiency
def FlatErrorToAsymmErrs(name,nomhist,up_frac=0.,dn_frac=0.) : nom_2_asymm = HistToAsymmErrs(nomhist.GetName()+' FlatErrorToAsymmErrs Asymm',nomhist) EYlow = [] EYhigh = [] for i in range(nom_2_asymm.GetN()) : EYlow.append(nom_2_asymm.GetY()[i]*dn_frac) EYhigh.append(nom_2_asymm.GetY()[i]*up_frac) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) result = TGraphAsymmErrors(nom_2_asymm.GetN(),nom_2_asymm.GetX(),nom_2_asymm.GetY() ,nom_2_asymm.GetEXlow(),nom_2_asymm.GetEXhigh() ,a_EYlow,a_EYhigh) result.GetXaxis().SetTitle(nom_2_asymm.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nom_2_asymm.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
def GetTGraphAsymmErrors(histo, offset): graph_in = TGraphAsymmErrors(histo) graph_in.SetName(histo.GetName() + '_tmp') graph_out = TGraphAsymmErrors(histo) graph_out.SetName(histo.GetName() + '_offset') for i in range(graph_in.GetN()): graph_out.GetX()[i] = graph_in.GetX()[i] + offset graph_out.GetEXlow()[i] = graph_in.GetEXlow()[i] + offset graph_out.GetEXhigh()[i] = graph_in.GetEXhigh()[i] - offset x_min = graph_out.GetX()[0] - graph_out.GetEXlow()[0] if (x_min > 0): x_min = 0 x_max = graph_out.GetX()[graph_out.GetN() - 1] + graph_out.GetEXhigh()[graph_out.GetN() - 1] graph_out.GetXaxis().SetLimits(x_min, x_max) return graph_out
def LinearUpDown(name,asymlist=[],hists=[],AddHists=False) : for i in range(len(hists)) : asymlist.append(HistToAsymmErrs(hists[i].GetName()+' LinearUpDown Asymm',hists[i])) nbins = asymlist[0].GetN() total_unc_up = [] total_unc_dn = [] for i in range(nbins) : total_unc_up.append(0) total_unc_dn.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist)) : total_unc_up[i] += asymlist[j].GetEYhigh()[i] total_unc_dn[i] += asymlist[j].GetEYlow()[i] y = [] for i in range(nbins) : y.append(asymlist[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist)) : y[-1] += asymlist[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up) ydn = array('d',total_unc_dn) result = TGraphAsymmErrors(asymlist[0].GetN(),asymlist[0].GetX(),ybincontent ,asymlist[0].GetEXlow(),asymlist[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result return
def makeEffPlotsVars(tree, varx, numeratorAddSelection, baseSelection, binning, xtitle='', header='', addon='', marker=20, col=1): _denomHist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, binning) _nominatorHist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, binning) tree.Draw(varx + ' >> ' + _denomHist_.GetName(), baseSelection) tree.Draw(varx + ' >> ' + _nominatorHist_.GetName(), baseSelection + ' && ' + numeratorAddSelection) g_eff = TGraphAsymmErrors() g_eff.Divide(_nominatorHist_, _denomHist_, "cl=0.683 b(1,1) mode") g_eff.GetXaxis().SetTitle(xtitle) g_eff.GetYaxis().SetTitle('efficiency') g_eff.GetYaxis().SetNdivisions(507) g_eff.SetLineWidth(3) g_eff.SetName(header) g_eff.SetMinimum(0.) g_eff.GetYaxis().SetTitleOffset(1.3) g_eff.SetMarkerStyle(marker) g_eff.SetMarkerSize(1) g_eff.SetMarkerColor(col) g_eff.SetLineColor(col) g_eff.Draw('ap') return g_eff
grRatio.SetPoint(i, x, y_ratio) grRatio.SetPointEXlow(i, ex_lo) grRatio.SetPointEXhigh(i, ex_hi) grRatio.SetPointEYlow(i, ey_lo_ratio) grRatio.SetPointEYhigh(i, ey_hi_ratio) if True: grRatio.SetMarkerStyle(20) grRatio.SetMarkerSize(1.5) grRatio.SetMarkerColor(1) grRatio.SetLineStyle(1) grRatio.SetLineColor(1) grRatio.SetLineWidth(1) grRatio.GetXaxis().SetLabelSize(0.04) grRatio.GetXaxis().SetTitleSize(0.04) grRatio.GetXaxis().SetTitleOffset(1.25) grRatio.GetYaxis().SetLabelSize(0.04) grRatio.GetYaxis().SetTitleSize(0.04) grRatio.GetYaxis().SetTitleOffset(1.5) # grRatio.GetYaxis().SetRangeUser(ylo, yhi) grRatio.Draw("ALP") fOutput = TFile('durp.root', 'recreate') grRatio.Write('durp') canvas.Write('canv') fOutput.Close()
gr_LC = GAE(1, x_c, y_c, exl_c, exh_c, eyl_c, eyh_c) gr_c = gr.Clone() gr_sc = gr_s.Clone() gr.SetTitle('ROC(zoomed in)') #gr.SetMarkerColor(8) #gr.SetMarkerStyle(21) gr.SetFillColor(632 - 9) gr_s.SetTitle('ROC') gr_s.SetFillColor(632 - 9) gr_sc.SetLineColor(4) c1.cd(1) gr.GetXaxis().SetRangeUser(0, 0.5) gr.GetYaxis().SetRangeUser(0.00001, 0.01) gr_c.GetXaxis().SetRangeUser(0, 0.5) gr_c.GetXaxis().SetRangeUser(0.00001, 0.01) gr_LC.GetXaxis().SetRangeUser(0, 0.5) gr_LC.GetYaxis().SetRangeUser(0.00001, 0.01) gr_c.SetLineColor(4) gr.Draw('SAME 3A') gr_c.Draw('SAME XLP') gr_LC.Draw('SAME A') c1.cd(2)
def makePlot(finname,foutname,plottitle='',masstitle='',scale=False): xsecs = resonantXsecs if 'resonant' in finname else fcncXsecs points = {} if BLIND: cls = [2.5, 16, 50, 84, 97.5] else: cls = [2.5, 16, 50, 84, 97.5,'Observed'] xaxis = [] for cl in cls: points[cl] = [] xsec=1 for l in open(finname): try: if l.strip()[0]=='#': continue if 'MASS' in l: if scale: xsec = xsecs[int(l.split()[1])] if VERBOSE: print '' stdout.write('$%6s$ & $%7.3g$'%(l.split()[1],xsec/(0.667))) xaxis.append(float(l.split()[1])) else: cl,val = parseLine(l) points[cl].append(val/xsec) if VERBOSE and (cl==50 or cl=='Observed'): stdout.write(' & $%10.4g$'%(val/xsec)) except: pass if VERBOSE: print '' N = len(xaxis) up1Sigma=[]; up2Sigma=[] down1Sigma=[]; down2Sigma=[] for iM in xrange(N): up1Sigma.append(points[84][iM]-points[50][iM]) up2Sigma.append(points[97.5][iM]-points[50][iM]) down1Sigma.append(-points[16][iM]+points[50][iM]) down2Sigma.append(-points[2.5][iM]+points[50][iM]) up1Sigma = array('f',up1Sigma) up2Sigma = array('f',up2Sigma) down1Sigma = array('f',down1Sigma) down2Sigma = array('f',down2Sigma) cent = array('f',points[50]) if not BLIND: obs = array('f',points['Observed']) xarray = array('f',xaxis) xsecarray = array('f',[xsecs[xx] for xx in xaxis]) xsecarrayLow = array('f',[0.0625*xsecs[xx] for xx in xaxis]) onearray = array('f',[1 for xx in xaxis]) graphXsec = TGraph(N,xarray,xsecarray) graphXsecLow = TGraph(N,xarray,xsecarrayLow) graphOne = TGraph(N,xarray,onearray) zeros = array('f',[0 for i in xrange(N)]) graphCent = TGraph(N,xarray,cent) if not BLIND: graphObs = TGraph(N,xarray,obs) graph1Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down1Sigma,up1Sigma) graph2Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down2Sigma,up2Sigma) c = TCanvas('c','c',700,600) c.SetLogy() c.SetLeftMargin(.15) graph2Sigma.GetXaxis().SetTitle(masstitle+' [GeV]') if scale: graph2Sigma.GetYaxis().SetTitle('Upper limit [#sigma/#sigma_{theory}]') else: graph2Sigma.GetYaxis().SetTitle("Upper limit [#sigma] [pb]") graph2Sigma.SetLineColor(5) graph1Sigma.SetLineColor(3) graph2Sigma.SetFillColor(5) graph1Sigma.SetFillColor(3) graph2Sigma.SetMinimum(0.5*min(points[2.5])) if scale: graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray),4)) else: graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray))) graphCent.SetLineWidth(2) graphCent.SetLineStyle(2) if not BLIND: graphObs.SetLineColor(1) graphObs.SetLineWidth(3) graph1Sigma.SetLineStyle(0) graph2Sigma.SetLineStyle(0) leg = TLegend(0.55,0.7,0.9,0.9) leg.AddEntry(graphCent,'Expected','L') if not BLIND: leg.AddEntry(graphObs,'Observed','L') leg.AddEntry(graph1Sigma,'1 #sigma','F') leg.AddEntry(graph2Sigma,'2 #sigma','F') leg.SetFillStyle(0) leg.SetBorderSize(0) graph2Sigma.Draw('A3') graph1Sigma.Draw('3 same') graphCent.Draw('same L') if not BLIND: graphObs.Draw('same L') if scale: graphOne.SetLineColor(2) graphOne.SetLineWidth(2) graphOne.SetLineStyle(2) graphOne.Draw('same L') else: graphXsec.SetLineColor(2) graphXsecLow.SetLineColor(4) subscript = 'SR' if 'Resonant' in plottitle else 'FC' if 'Resonant' in plottitle: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=0.1}{m_{#chi}=100 GeV}'%(subscript,subscript),'l') else: leg.AddEntry(graphXsec,'Theory a_{%s}=b_{%s}=0.1'%(subscript,subscript),'l') # leg.AddEntry(graphXsecLow,'Theory a_{%s}=b_{%s}=0.025'%(subscript,subscript),'l') for g in [graphXsec]: g.SetLineWidth(2) g.SetLineStyle(2) g.Draw('same L') leg.Draw() label = TLatex() label.SetNDC() label.SetTextFont(62) label.SetTextAlign(11) label.DrawLatex(0.19,0.85,"CMS") label.SetTextFont(52) label.DrawLatex(0.28,0.85,"Preliminary") label.SetTextFont(42) label.SetTextSize(0.6*c.GetTopMargin()) label.DrawLatex(0.19,0.77,plottitle) if scale: if 'Resonant' in plottitle: label.DrawLatex(0.19,0.7,"a_{SR} = b_{SR} = 0.1") label.DrawLatex(0.19,0.64,"m_{#chi}=100 GeV") else: label.DrawLatex(0.19,0.7,"a_{FC} = b_{FC} = 0.1") label.SetTextSize(0.5*c.GetTopMargin()) label.SetTextFont(42) label.SetTextAlign(31) # align right label.DrawLatex(0.9, 0.94,"%.1f fb^{-1} (13 TeV)"%(plotConfig.lumi)) c.SaveAs(foutname+'.pdf') c.SaveAs(foutname+'.png')
def limit(): method = '' channel = "bb" particleP = "Z'" particle = channel multF = ZPTOBB THEORY = ['A1', 'B3'] suffix = "_" + BTAGGING if ISMC: suffix += "_MC" if SY: suffix += "_comb" #if method=="cls": suffix="_CLs" if SY: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt" else: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/" + YEAR + "_M%d.txt" if CATEGORY != "": 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 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) 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]) for t in THEORY: Theory[t] = TGraphAsymmErrors() addXZH = True for m in sorted(HVT[t]['W']['XS'].keys()): if m < mass[0] or m > mass[-1]: continue if m > 4500: continue ## for now because I don't have the higher mass xs FIXME XsZ, XsZ_Up, XsZ_Down = 0., 0., 0. if addXZH: XsZ = 1000. * HVT[t]['Z']['XS'][ m] * 0.12 #temporary BR value set to 0.12 FIXME 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])) n = Theory[t].GetN() Theory[t].SetPoint(n, m, XsZ) Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down), (XsZ_Up - XsZ)) 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)") 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) 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 drawCMS(LUMI, "Work in Progress", 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/MANtag_study/" + YEAR + suffix + ".png") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".C") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + 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, print "" return
n=0 for a in sorted(threshold_scan): #for a in sorted(run_parameters): ##Fill the TGraph with threshold (x-axis) and rate (y-axis) #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1'])) graph.SetPoint(n,int(a),float(threshold_scan[a])) n = n+1 graph.SetMarkerSize(1.) graph.SetMarkerStyle(21) graph.SetMarkerColor(862) graph.SetFillColor(868) graph.SetFillStyle(3844) graph.SetLineColor(868) graph.SetLineWidth(2) graph.SetLineStyle(2) graph.GetXaxis().SetTitle("threshold [mV]") graph.GetYaxis().SetTitleOffset(1.2) graph.GetYaxis().SetTitle("rate [kHz]") graph.Draw("APL") latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextColor(1) latex.SetTextFont(42) latex.SetTextAlign(33) latex.SetTextSize(0.04) latex.SetTextFont(62) latex.DrawLatex(0.30, 0.96, "GIF++") etichetta = TLatex() etichetta.SetNDC() etichetta.SetTextSize(0.04)
def RootifyCrossBR(self): for processname in self.processnames: outfilename_cross = self.crosssecfolder+'/Crosssections_%s%s.root' % (processname, self.tag) cross_module = importlib.import_module('crosssections.ChiPsi.Crosssections_%s' % (processname)) crosssections = cross_module.crosssection if self.submit: outfile = TFile(outfilename_cross, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_cross)) print green('--> Now at sample %s' % (processname)) for lamb in self.lambdas: if not lamb in crosssections: continue print green(' --> Now at lambda: %s' % (get_lambdastring(lamb))) xsecs_per_mref = crosssections[lamb] graph2d = TGraph2D() npoints2d=0 set_points ={} all_combinations = get_all_combinations(preferred_configurations=preferred_configurations) for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = False for mref in xsecs_per_mref: xsecs = xsecs_per_mref[mref] final_xsecs = [] mdeps = array('d') sigmas = array('d') tot_los = array('d') tot_his = array('d') mdeps_lo = array('d') mdeps_hi = array('d') for tuple in xsecs: mdep, sigma, q_lo, q_hi, pdf = tuple tot_lo = XsecTotErr(sigma, q_lo, pdf) tot_hi = XsecTotErr(sigma, q_hi, pdf) final_xsecs.append((mdep, sigma, tot_lo, tot_hi)) mdeps.append(mdep) sigmas.append(sigma) tot_los.append(tot_lo) tot_his.append(tot_hi) mdeps_lo.append(0.) mdeps_hi.append(0.) if 'LQLQ' in processname or 'LQTChannel' in processname: graph2d.SetPoint(npoints2d, mdep, mref, sigma) set_points[mdep][mref] = True elif 'PsiPsi' in processname: graph2d.SetPoint(npoints2d, mref, mdep, sigma) set_points[mref][mdep] = True else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') npoints2d += 1 # make TGraph out of it graph = TGraphAsymmErrors(len(mdeps), mdeps, sigmas, mdeps_lo, mdeps_hi, tot_los, tot_his) xaxistitle = 'M_{LQ} [GeV]' if ('LQLQ' in processname or 'LQTChannel' in processname) else 'M_{#chi_{1}} [GeV]' graph.GetXaxis().SetTitle('M_{LQ} [GeV]') graph.GetYaxis().SetTitle('#sigma [pb]') graphname = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphname += '_MC1%i' % (mref) elif 'PsiPsi' in processname: graphname += '_MLQ%i' % (mref) else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') graphname += '_L%s' % (get_lambdastring(lamb)) graph.SetName(graphname) # print 'graphname: %s' % (graphname) graphtitle = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphtitle += ', M_{#chi_{1}} = %i GeV' % (mref) elif 'PsiPsi' in processname: graphtitle += ', M_{LQ} = %i GeV' % (mref) graphtitle += ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.')) # print 'graphtitle: %s' % (graphtitle) graph.SetTitle(graphtitle) if self.submit: outfile.cd() graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: if not set_points[mlq][mch]: graph2d.SetPoint(npoints2d, mlq, mch, 0.) npoints2d += 1 graph2d.SetName(processname + '_L%s' % (get_lambdastring(lamb))) graph2d.GetXaxis().SetTitle('M_{LQ} [GeV]') graph2d.GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') graph2d.GetZaxis().SetTitle('#sigma [pb]') graph2d.SetTitle(processname + ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.'))) if self.submit: graph2d.Write() else: print yellow(' --> Would have written 2d-graph to outfile') if self.submit: outfile.Close() # also rootify BRs if we are looking at the LQLQ process without decays (just for fun, could also be any other LQLQ process) if processname == 'LQLQ': outfilename_br = self.crosssecfolder+'/Branchingratios_%s%s.root' % (processname, self.tag) if self.submit: outfile = TFile(outfilename_br, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_br)) br_module = importlib.import_module('crosssections.ChiPsi.Branchingratios_%s' % (processname)) allbrs = br_module.branchingratio for lamb in allbrs.keys(): brs = allbrs[lamb] brs2d = {} npoints2d = {} set_points ={} for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = {} for decaymode in decaymode_dict.keys(): set_points[mlq][mch][decaymode] = False decaymodes_present = [] for mlq in sorted(brs): mchs_per_decaymode = {} brs_per_decaymode = {} for mch in sorted(brs[mlq]): for decaymode in brs[mlq][mch]: if not decaymode in decaymodes_present: decaymodes_present.append(decaymode) if not decaymode in mchs_per_decaymode.keys(): mchs_per_decaymode[decaymode] = array('d') if not decaymode in brs_per_decaymode.keys(): brs_per_decaymode[decaymode] = array('d') # if not decaymode in set_points[mlq][mch].keys(): # # print mlq, mch, decaymode # set_points[mlq][mch][decaymode] = False if not decaymode in brs2d.keys(): graphname2d = processname + ('_L%s_%i_%i' % (get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) # print graphname2d npoints2d[decaymode] = 0 brs2d[decaymode] = TGraph2D() brs2d[decaymode].SetName(graphname2d) brs2d[decaymode].GetXaxis().SetTitle('M_{LQ} [GeV]') brs2d[decaymode].GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') brs2d[decaymode].GetZaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) brs2d[decaymode].SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) mchs_per_decaymode[decaymode].append(mch) brs_per_decaymode[decaymode].append(brs[mlq][mch][decaymode][0]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, brs[mlq][mch][decaymode][0]) set_points[mlq][mch][decaymode] = True npoints2d[decaymode] += 1 for decaymode in mchs_per_decaymode.keys(): graph = TGraph(len(mchs_per_decaymode[decaymode]), mchs_per_decaymode[decaymode], brs_per_decaymode[decaymode]) graphname = processname + ('_MLQ%i_L%s_%i_%i' % (mlq, get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) graph.SetName(graphname) graph.GetXaxis().SetTitle('M_{#chi_{1}} [GeV]') graph.GetYaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) graph.SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) if self.submit: graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: for decaymode in set_points[mlq][mch]: if not set_points[mlq][mch][decaymode] and decaymode in decaymodes_present: # print decaymode # print brs2d.keys() # print npoints2d.keys() # print 'Setting BR for MLQ=%i, MCH=%i, decay=(%i, %i) to 0' % (mlq, mch, decaymode[0], decaymode[1]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, 0) npoints2d[decaymode] += 1 if self.submit: for decaymode in brs2d: brs2d[decaymode].Write() else: print yellow(' --> Would have written 2d-graphs to outfile') outfile.Close()
expected68.SetFillColor(ROOT.kGreen) expected95 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp95Lv, exp95Hv) expected95.SetFillColor(ROOT.kYellow) c4 = TCanvas("c4", "Diphoton c = 01 Limits", 1000, 800) c4.SetBottomMargin(0.15) c4.SetRightMargin(0.06) #c4.SetLogy(1) #expected95.SetMinimum(0.0001); expected95.SetMaximum(0.0057) expected95.Draw("a3") expected95.GetXaxis().SetTitle("Diphoton Mass [GeV/c^{2}]") expected95.GetYaxis().SetTitle("#sigma(G_{RS} #rightarrow #gamma #gamma)[pb]") expected68.Draw("3same") expected_p.Draw("csame") observed_p.Draw("cpsame") theory.Draw("same") latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextAlign(31) # align right latex.DrawLatex(0.45, 0.95, "CMS Preliminary") latex2 = TLatex() latex2.SetNDC() latex2.SetTextSize(0.04)
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")
gObs.SetLineWidth(2) gObs.SetLineStyle(1) gObs.SetLineColor(ROOT.kBlue+1) gObs.SetMarkerColor(ROOT.kBlue+1) gObs.SetMarkerStyle(21) gObs.SetMarkerSize(1.5) gxs.SetLineStyle(5) gxs.SetLineWidth(3) gxs.SetLineColor(ROOT.kRed) canvasName = 'Limits' if useSub: canvasName = 'Limits_Sub' can = TCanvas(canvasName,canvasName,900,600) gPad.SetLogy() g2.GetXaxis().SetTitle(' qg resonance Mass (TeV)') g2.GetYaxis().SetTitle('#sigma #times A #times BR (q*#rightarrow jj) (pb)') #g2.GetYaxis().SetTitle('#sigma #times BR (q*#rightarrow jj) (pb)') g2.GetYaxis().CenterTitle(ROOT.kTRUE) g2.GetYaxis().SetNdivisions(510) g2.GetYaxis().SetRangeUser(1e-3,10) g2.Draw('AE3') g1.Draw('sameE3') gExp.Draw('sameL') gObs.Draw('sameLP') gxs.Draw('sameL') if superimpose: gExpDinko.Draw('sameL') leg = TLegend(0.65,0.65,0.9,0.9) if useSub:
C = TCanvas() C.Print("PUWeights.pdf[") # Loop over json content # for name, path in dict_files.items(): print("Looking at %s" % name) # Load json content # with open(path, "r") as handle: data = json.load(handle) # Get binning content # bins = data['data'] # List of dict (1 dict per bin) g = TGraphAsymmErrors(len(bins)) # Loop over bins # for i, b in enumerate(bins): val = b['value'] up = b['error_high'] down = b['error_low'] bincenter = (b['bin'][0] + b['bin'][1]) / 2 g.SetPoint(i, bincenter, val) g.SetPointError(i, 0, 0, up, down) g.GetHistogram().SetMinimum(0.) g.GetHistogram().SetMaximum(2.) g.SetTitle("Sample : %s" % name) g.GetXaxis().SetTitle("nTrueInt") g.GetYaxis().SetTitle("PU weight") C.Clear() g.Draw() C.Print("PUWeights.pdf", "Title:%s" % name) C.Print("PUWeights.pdf]")
def makeplot_single( h1_sig=None, h1_bkg=None, h1_data=None, sig_legends_=None, bkg_legends_=None, sig_colors_=None, bkg_colors_=None, hist_name_=None, sig_scale_=1.0, dir_name_="plots", output_name_=None, extraoptions=None ): if h1_sig == None or h1_bkg == None: print("nothing to plot...") return os.system("mkdir -p "+dir_name_) os.system("cp index.php "+dir_name_) s_color = [632, 617, 839, 800, 1] b_color = [920, 2007, 2005, 2003, 2001, 2011] if sig_colors_: s_color = sig_colors_ if bkg_colors_: b_color = bkg_colors_ for idx in range(len(h1_sig)): h1_sig[idx].SetLineWidth(3) h1_sig[idx].SetLineColor(s_color[idx]) for idx in range(len(h1_bkg)): h1_bkg[idx].SetLineWidth(2) h1_bkg[idx].SetLineColor(b_color[idx]) h1_bkg[idx].SetFillColorAlpha(b_color[idx], 1) if h1_data: h1_data.SetBinErrorOption(1) h1_data.SetLineColor(1) h1_data.SetLineWidth(2) h1_data.SetMarkerColor(1) h1_data.SetMarkerStyle(20) myC = r.TCanvas("myC","myC", 600, 600) myC.SetTicky(1) pad1 = r.TPad("pad1","pad1", 0.05, 0.33,0.95, 0.97) pad1.SetBottomMargin(0.027) pad1.SetRightMargin( rightMargin ) pad1.SetLeftMargin( leftMargin ) pad2 = r.TPad("pad2","pad2", 0.05, 0.04, 0.95, 0.31) pad2.SetBottomMargin(0.4) pad2.SetTopMargin(0.05) pad2.SetRightMargin( rightMargin ) pad2.SetLeftMargin( leftMargin ) pad2.Draw() pad1.Draw() pad1.cd() for idx in range(len(h1_sig)): print("before signal scaling",h1_sig[idx].Integral()) h1_sig[idx].Scale(sig_scale_) print("after signal scaling",h1_sig[idx].Integral()) stack = r.THStack("stack", "stack") nS = np.zeros(h1_bkg[0].GetNbinsX()) eS = np.zeros(h1_bkg[0].GetNbinsX()) #hist_all is used to make the data/mc ratio. remove signal for the moment due to signal is scaled right now hist_all = h1_sig[0].Clone("hist_all") hist_all.Scale(0.0) hist_s = h1_sig[0].Clone("hist_s") hist_b = h1_bkg[0].Clone("hist_b") for idx in range(len(h1_bkg)): stack.Add(h1_bkg[idx]) for ib in range(h1_bkg[0].GetNbinsX()): nS[ib] += h1_bkg[idx].GetBinContent(ib+1) eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_bkg[idx].GetBinError(ib+1)*h1_bkg[idx].GetBinError(ib+1)) hist_all.Add(h1_bkg[idx]) if idx > 0: hist_b.Add(h1_bkg[idx]) for idx in range(len(h1_sig)): print("ggH signal yield: ", hist_s.Integral()) if idx > 0: hist_temp = h1_sig[idx].Clone(h1_sig[idx].GetName()+"_temp") #hist_all.Add(hist_temp) hist_s.Add(h1_sig[idx]) print("all signal yield: ", hist_s.Integral()) stack.SetTitle("") maxY = 0.0 if "stack_signal" in extraoptions and extraoptions["stack_signal"]: for idx in range(len(h1_sig)): h1_sig[idx].SetFillColorAlpha(s_color[idx], 1) stack.Add(h1_sig[idx]) for ib in range(h1_bkg[0].GetNbinsX()): nS[ib] += h1_sig[idx].GetBinContent(ib+1) eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_sig[idx].GetBinError(ib+1)*h1_sig[idx].GetBinError(ib+1)) if stack.GetMaximum() > maxY: maxY = stack.GetMaximum() #if "SR" in h.GetTitle(): stack.Draw("hist") else: stack.Draw("hist") if stack.GetMaximum() > maxY: maxY = stack.GetMaximum() for idx in range(len(h1_sig)): if h1_sig[idx].GetMaximum() > maxY: maxY = h1_sig[idx].GetMaximum() if "SR" in h1_bkg[0].GetTitle(): #h1_sig[idx].Draw("samehist") hist_s.Draw("samehist") ##draw stack total unc on top of total histogram box = r.TBox(0,0,1,1,) box.SetFillStyle(3002) box.SetLineWidth(0) box.SetFillColor(r.kBlack) for idx in range(h1_bkg[0].GetNbinsX()): box.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]-eS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]+eS[idx]) if h1_data: if h1_data.GetMaximum() > maxY: maxY = h1_data.GetMaximum()+np.sqrt(h1_data.GetMaximum()) #if not "SR" in h1_data.GetTitle() or "fail" in h1_data.GetTitle(): if True: #print("debug h1_data.GetName()",h1_data.GetName(), h1_data.GetTitle()) TGraph_data = TGraphAsymmErrors(h1_data) for i in range(TGraph_data.GetN()): #data point var_x, var_y = Double(0.), Double(0.) TGraph_data.GetPoint(i,var_x,var_y) if np.fabs(var_y) < 1e-5: TGraph_data.SetPoint(i,var_x,-1.0) TGraph_data.SetPointEYlow(i,-1) TGraph_data.SetPointEYhigh(i,-1) #print("zero bins in the data TGraph: bin",i+1) else: TGraph_data.SetPoint(i,var_x,var_y) err_low = var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)) TGraph_data.SetPointEYlow(i, var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y))) TGraph_data.SetPointEYhigh(i, (0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y) TGraph_data.SetMarkerColor(1) TGraph_data.SetMarkerSize(1) TGraph_data.SetMarkerStyle(20) TGraph_data.Draw("same P") stack.GetYaxis().SetTitle("Events") stack.GetYaxis().SetTitleOffset(1.05) stack.GetYaxis().SetTitleSize(0.08) stack.GetYaxis().SetLabelSize(0.06) #stack.GetYaxis().CenterTitle() stack.GetXaxis().SetLabelSize(0.) #stack.GetXaxis().SetLabelOffset(0.013) #if "xaxis_range" in extraoptions: # stack.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1])) leg = r.TLegend(0.2, 0.60, 0.9, 0.88) leg.SetNColumns(3) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetTextFont(42) leg.SetTextSize(0.05) for idx in range(len(h1_bkg)): leg.AddEntry(h1_bkg[idx], bkg_legends_[idx], "F") if "SR" in hist_s.GetTitle(): leg.AddEntry(hist_s, 'HH #times {:1.2}'.format(sig_scale_), "L") leg.AddEntry(box, "Total unc", "F") if h1_data: leg.AddEntry(h1_data, "Data", "ep") leg.Draw() pad2.cd() pad2.SetGridy(1) ratio = None ratio_Low = 0.0 ratio_High = 4 if h1_data: ratio = TGraphAsymmErrors(h1_data) for i in range(ratio.GetN()): #bkg prediction imc = Double(hist_all.GetBinContent(i+1)) #data point var_x, var_y = Double(0.), Double(0.) if not ("SR" in h1_data.GetTitle() and (i>5 and i<9)): ratio.GetPoint(i,var_x,var_y) if var_y == 0.: ratio.SetPoint(i,var_x,-1.0) ratio.SetPointEYlow(i,-1) ratio.SetPointEYhigh(i,-1) continue ratio.SetPoint(i,var_x,var_y/imc) err_low = (var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))/imc err_high = ((0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)/imc ratio.SetPointEYlow(i, err_low) ratio.SetPointEYhigh(i, err_high) ratio.SetMarkerColor(1) ratio.SetMarkerSize(1) ratio.SetMarkerStyle(20) ratio.GetXaxis().SetTitle("j_{2} regressed mass [GeV]") #myC.Update() if "ratio_range" in extraoptions: ratio_Low = extraoptions["ratio_range"][0] ratio_High = extraoptions["ratio_range"][1] ratio.GetYaxis().SetTitle("data/mc") ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High) ratio.GetXaxis().SetRangeUser(50, 220) ratio.SetTitle("") ratio.Draw("same AP") pad2.Update() print(ratio.GetTitle(),ratio.GetName(),"debug") else: ratio = h1_sig[0].Clone("ratio") ratio_High = 0.0 for ibin in range(1,ratio.GetNbinsX()+1): s = hist_s.GetBinContent(ibin) b = hist_b.GetBinContent(ibin) L = 0.0 if b > 0.0: L = s/math.sqrt(b) if L > ratio_High: ratio_High = L ratio.SetBinContent(ibin, L) if ratio_High > 1.0: ratio_High = 1.0 ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High*1.2) ratio.GetYaxis().SetTitle("S/#sqrt{B}") ratio.Draw("samehist") ratio.SetLineColor(1) ratio.SetLineWidth(2) ratio.SetMarkerStyle(20) ratio.SetMarkerColor(1) ratio.SetFillColorAlpha(1, 0) ratio.GetXaxis().SetTitleOffset(0.94) ratio.GetXaxis().SetTitleSize(0.18) ratio.GetXaxis().SetLabelSize(0.12) ratio.GetXaxis().SetLabelOffset(0.013) ratio.GetYaxis().SetTitleOffset(0.40) ratio.GetYaxis().SetTitleSize(0.17) ratio.GetYaxis().SetLabelSize(0.13) ratio.GetYaxis().SetTickLength(0.01) ratio.GetYaxis().SetNdivisions(505) #if "xaxis_range" in extraoptions: # ratio.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1])) #draw stack total unc on the ratio plot to present the background uncertainty box_ratio = r.TBox(0,0,1,1,) box_ratio.SetFillStyle(3002) box_ratio.SetLineWidth(0) box_ratio.SetFillColor(r.kBlack) for idx in range(h1_bkg[0].GetNbinsX()): if np.fabs(nS[idx])> 1e-06: box_ratio.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]-eS[idx])/nS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]+eS[idx])/nS[idx]) else: print("blinded Higgs peak region") if "xaxis_label" in extraoptions and extraoptions["xaxis_label"] != None: x_title = extraoptions["xaxis_label"] ratio.GetXaxis().SetTitle(x_title) ratio.GetYaxis().CenterTitle() ##########draw CMS preliminary pad1.cd() tex1 = r.TLatex(leftMargin, 0.91, "CMS") tex1.SetNDC() tex1.SetTextFont(61) tex1.SetTextSize(0.070) tex1.SetLineWidth(2) tex1.Draw() tex2 = r.TLatex(leftMargin+0.12,0.912,"Internal") tex2.SetNDC() tex2.SetTextFont(52) tex2.SetTextSize(0.055) tex2.SetLineWidth(2) tex2.Draw() lumi_value = 137 if "lumi_value" in extraoptions: lumi_value = extraoptions["lumi_value"] tex3 = r.TLatex(0.72,0.912,"%d"%lumi_value+" fb^{-1} (13 TeV)") tex3.SetNDC() tex3.SetTextFont(42) tex3.SetTextSize(0.055) tex3.SetLineWidth(2) tex3.Draw() outFile = dir_name_ if output_name_: outFile = outFile + "/" +output_name_ else: outFile = outFile + "/" + hist_name_ #print("maxY = "+str(maxY)) stack.SetMaximum(maxY*1.7) #print everything into txt file text_file = open(outFile+"_linY.txt", "w") text_file.write("bin | x ") for idx in range(len(h1_bkg)): text_file.write(" | %21s"%bkg_legends_[idx]) text_file.write(" | %21s"%("total B")) for idx in range(len(sig_legends_)): text_file.write(" | %25s"%sig_legends_[idx]) if h1_data: text_file.write(" | data | data/mc") text_file.write("\n-------------") for idx in range(24*(len(h1_bkg) + 1)+ 29*len(sig_legends_)): text_file.write("-") if h1_data: text_file.write("-------") text_file.write("\n") for ibin in range(0,h1_sig[0].GetNbinsX()+1): text_file.write("%3d"%ibin+" ") text_file.write(" | %6.3f"%h1_data.GetBinCenter(ibin)+" ") for idx in range(len(h1_bkg)): text_file.write(" | %7.3f "%h1_bkg[idx].GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%h1_bkg[idx].GetBinError(ibin)) text_file.write(" | %7.3f "%hist_b.GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%hist_b.GetBinError(ibin)) for idx in range(len(sig_legends_)): text_file.write(" | %9.3f "%h1_sig[idx].GetBinContent(ibin)+"$\\pm$"+ " %9.3f"%h1_sig[idx].GetBinError(ibin)) if h1_data: text_file.write(" | %d"%h1_data.GetBinContent(ibin) + " | %7.3f "%h1_data.GetBinContent(ibin) +"$\\pm$"+ " %7.3f"%h1_data.GetBinError(ibin)) text_file.write("\n\n") #print yield table for AN text_file.write("print yield table for AN\n") bkg_all = 0 bkg_all_errsq = 0 for idx in range(len(h1_bkg)): bkg_tmp = h1_bkg[idx].GetBinContent(7)+h1_bkg[idx].GetBinContent(8)+h1_bkg[idx].GetBinContent(9) bkg_errsq_tmp = h1_bkg[idx].GetBinError(7)*h1_bkg[idx].GetBinError(7)+h1_bkg[idx].GetBinError(8)*h1_bkg[idx].GetBinError(8)+h1_bkg[idx].GetBinError(9)*h1_bkg[idx].GetBinError(9) bkg_all += bkg_tmp bkg_all_errsq += bkg_errsq_tmp text_file.write("%s"%(bkg_legends_[idx])+"& %7.2f"%(bkg_tmp)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_errsq_tmp)+"\n") text_file.write("total background & %7.2f"%(bkg_all)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_all_errsq)+"\n") text_file.write("\ggHH SM ($\kapl=1$) & %7.2f"%((h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9)))+"\n") text_file.write("\VBFHH SM ($\kapl=1$) & %7.2f"%((h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9)))+"\n") text_file.write("HH bin 8 value %s"%h1_sig[0].GetBinContent(8)+"\n") text_file.write("HH bin 9 value %s"%h1_sig[0].GetBinContent(9)+"\n") text_file.write("HH bin 7 value %s"%h1_sig[0].GetBinContent(7)+"\n") text_file.write("HH bin 8 error %s"%h1_sig[0].GetBinError(8)+"\n") text_file.write("HH bin 9 error %s"%h1_sig[0].GetBinError(9)+"\n") text_file.write("HH bin 7 error %s"%h1_sig[0].GetBinError(7)+"\n") text_file.write("total & %7.2f"%(bkg_all+(h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9)+h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.2f"%(np.sqrt((h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9))/(sig_scale_*sig_scale_)+(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9))/(sig_scale_*sig_scale_)+bkg_all_errsq))+"\n") text_file.close() os.system("cp "+outFile+"_linY.txt "+outFile+"_logY.txt") pad1.RedrawAxis() myC.SaveAs(outFile+"_linY.png") myC.SaveAs(outFile+"_linY.pdf") myC.SaveAs(outFile+"_linY.C") pad1.cd() stack.SetMaximum(maxY*100.0) stack.SetMinimum(0.5) pad1.SetLogy() pad1.RedrawAxis() myC.SaveAs(outFile+"_logY.png") myC.SaveAs(outFile+"_logY.pdf") myC.SaveAs(outFile+"_logY.C") #save histogram and ratio to root file outFile_root = r.TFile(outFile+".root", "recreate") outFile_root.cd() for idx in range(len(h1_bkg)): h1_bkg[idx].Write() for idx in range(len(sig_legends_)): h1_sig[idx].Write() if h1_data: h1_data.Write() ratio.Write() #outFile_root.Write() outFile_root.Close()
import math from ROOT import TFile, TCanvas, TGraph, TGraphAsymmErrors import array Binning_PT = array.array("d", [0, 30, 35, 40, 50, 60, 75, 95, 120, 150, 200]) OutFile = TFile("OutPutFR.root") HistoNum = OutFile.Get("histoLooseNumerator") HistoNum = HistoNum.Rebin(len(Binning_PT) - 1, "", Binning_PT) HistoDeNum = OutFile.Get("histoDenominator") HistoDeNum = HistoDeNum.Rebin(len(Binning_PT) - 1, "", Binning_PT) fakeRate = TGraphAsymmErrors(HistoNum, HistoDeNum, "") canv = TCanvas("canv", "histograms", 0, 0, 600, 600) canv.SetLogy() fakeRate.GetXaxis().SetRangeUser(0, 200) fakeRate.GetXaxis().SetTitle("#tau p_{T} [GeV]") fakeRate.GetYaxis().SetRangeUser(0.01, 0.5) fakeRate.SetTitle('Jet to Tau Fake Rate') fakeRate.SetMarkerStyle(20) fakeRate.Draw() canv.SaveAs("jetToTauFR.pdf")
def makePlot1D(filepath, foutname, plottitle='', masstitle=''): br = 1 if 'Resonant' in plottitle else 0.68 limits = parseLimitFiles2D(filepath, br) xaxis = [] xseclist = [] xsecerr = [] cent = [] obs = [] up1 = [] up2 = [] down1 = [] down2 = [] maxval = 0 minval = 999 for m in sorted(limits): l = limits[m] xaxis.append(m) xseclist.append(l.xsec) xsecerr.append(l.xsec * .2) cent.append(l.cent) up1.append(l.up1 - l.cent) up2.append(l.up2 - l.cent) down1.append(l.cent - l.down1) down2.append(l.cent - l.down2) obs.append(l.obs) maxval = max(maxval, l.up2) minval = min(minval, l.down2) N = len(xaxis) up1Sigma = array('f', up1) up2Sigma = array('f', up2) down1Sigma = array('f', down1) down2Sigma = array('f', down2) cent = array('f', cent) obs = array('f', obs) xarray = array('f', xaxis) xsecarray = array('f', xseclist) xsecerrarray = array('f', xsecerr) zeros = array('f', [0 for i in xrange(N)]) graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray) graphCent = TGraph(N, xarray, cent) graphObs = TGraph(N, xarray, obs) graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma, up1Sigma) graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma, up2Sigma) c = TCanvas('c', 'c', 700, 600) c.SetLogy() c.SetLeftMargin(.15) graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]') graph2Sigma.GetYaxis().SetTitle( '95% C.L. upper limit [#sigma/#sigma_{theory}]') c2 = root.kOrange c1 = root.kGreen + 1 graph2Sigma.SetLineColor(c2) graph1Sigma.SetLineColor(c1) graph2Sigma.SetFillColor(c2) graph1Sigma.SetFillColor(c1) graph2Sigma.SetMinimum(0.5 * minval) graph2Sigma.SetMaximum(10 * maxval) graphCent.SetLineWidth(2) graphCent.SetLineStyle(2) graphObs.SetLineColor(1) graphObs.SetLineWidth(3) graphObs.SetMarkerStyle(20) graphObs.SetMarkerSize(1) graphObs.SetMarkerColor(1) graph1Sigma.SetLineStyle(0) graph2Sigma.SetLineStyle(0) leg = TLegend(0.55, 0.7, 0.9, 0.9) leg.AddEntry(graphCent, 'Expected', 'L') if not BLIND: leg.AddEntry(graphObs, 'Observed', 'Lp') leg.AddEntry(graph1Sigma, '1 std. dev.', 'F') leg.AddEntry(graph2Sigma, '2 std. dev.', 'F') leg.SetFillStyle(0) leg.SetBorderSize(0) graph2Sigma.Draw('A3') graph1Sigma.Draw('3 same') graphCent.Draw('same L') if not BLIND: graphObs.Draw('same Lp') subscript = 'SR' if 'Resonant' in plottitle else 'FC' coupling = '0.1' if 'Resonant' in plottitle else '0.25' graphXsec.SetLineColor(2) graphXsec.SetLineWidth(2) graphXsec.SetLineStyle(2) graphXsec.SetFillColor(2) graphXsec.SetFillStyle(3005) graphXsec.Draw('same L3') ''' if not scale: if 'Resonant' in plottitle: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l') else: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l') ''' if not BLIND: findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1]) findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1]) leg.Draw() label = TLatex() label.SetNDC() label.SetTextSize(0.8 * c.GetTopMargin()) label.SetTextFont(62) label.SetTextAlign(11) label.DrawLatex(0.15, 0.94, "CMS") label.SetTextFont(52) label.SetTextSize(0.6 * c.GetTopMargin()) # label.DrawLatex(0.25,0.94,"Preliminary") label.SetTextFont(42) label.SetTextSize(0.7 * c.GetTopMargin()) label.DrawLatex(0.19, 0.83, plottitle) if 'Resonant' in plottitle: label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling) label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV") else: label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25") label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV") label.SetTextSize(0.6 * c.GetTopMargin()) label.SetTextFont(42) label.SetTextAlign(31) # align right label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi)) c.SaveAs(foutname + '.pdf') c.SaveAs(foutname + '.png')
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = SetCanvas() #c.SetLogy() #c = TCanvas() #c.SetLogy() h1 = f.Get('h_num_calo_') #'calo',pf h1 = setHistStyle(h1, bins) h2 = f.Get('h_den_calo_') h2 = setHistStyle(h2, bins) h11 = f2.Get('h_num_calo_') h11 = setHistStyle(h11, bins) h21 = f2.Get('h_den_calo_') h21 = setHistStyle(h21, bins) gr = TGraphAsymmErrors(30) #gr.Divide(h1,h2) gr = TGraphAsymmErrors(h1, h2) gr2 = TGraphAsymmErrors(h11, h21) gr2.SetMarkerStyle(20) gr2.GetXaxis().SetRangeUser(0, 1000) gr2.SetMarkerSize(1.5) gr2.SetLineColor(2) gr2.SetLineWidth(1) gr2.SetMarkerColor(2) gr.GetXaxis().SetRangeUser(0, 1000) # gr.GetYaxis().SetRangeUser(0.0001,1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(1.5) gr.SetLineColor(1) gr.SetLineWidth(1) gr.SetMarkerColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("MET [GeV]") gr.SetTitle("") #base histogram histogram_base = TH1F("histogram_base", "", 1000, 0, 1000.) histogram_base.SetTitle("") histogram_base.SetStats(0) histogram_base.SetMarkerSize(2) #histogram_base.SetMinimum(0.0) histogram_base.SetMaximum(1.2) histogram_base.GetXaxis().SetTitle("Online E_{T}^{miss} (GeV)") histogram_base.GetYaxis().SetTitle("Efficiency") histogram_base = setHistStyle(histogram_base, bins) histogram_base.Draw("HIST") # c.SaveAs() gr.Draw('P same') gr2.Draw('P same') latex.DrawLatex(0.49, 0.93, " EGamma Run2018C, 13 TeV") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1000, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() leg.AddEntry(gr, 'With HBHENoise filter', 'P') leg.AddEntry(gr2, 'Without HBHENoise filter', 'P') leg.Draw() txt = 'Path: HLT_PFMETTypeOne200_HBHE_BeamHaloCleaned' texcms = AddText(txt) texcms.Draw("same") c.SaveAs('testTurnOn_EGamma.png')
def plotDataOverMCEff(hist_mc_tight, hist_mc_loose, hist_data_tight, hist_data_loose, plot_name='fakerate.pdf'): g = TGraphAsymmErrors(hist_mc_tight) g.Divide(hist_mc_tight, hist_mc_loose) g.GetYaxis().SetTitle('Fake rate') g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle()) g.GetYaxis().SetTitleOffset(1.2) g.GetYaxis().SetTitleOffset(1.3) g.SetLineColor(2) g.SetMarkerColor(2) g_data = TGraphAsymmErrors(hist_data_tight) g_data.Divide(hist_data_tight, hist_data_loose) g_data.GetYaxis().SetTitle('Fake rate') g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle()) g_data.GetYaxis().SetTitleOffset(1.2) g_data.GetYaxis().SetTitleOffset(1.3) g_data.SetMarkerColor(1) g_vals = g.GetY() g_data_vals = g_data.GetY() g_ratio = g_data.Clone('ratio') for i in xrange(g_data.GetN()): ratio = g_data_vals[i] / g_vals[i] if g_vals[i] else 0. g_ratio.SetPoint(i, g.GetX()[i], ratio) rel_y_low = math.sqrt((g_data.GetErrorYlow(i) / g_data_vals[i])**2 + ( g.GetErrorYlow(i) / g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0. g_ratio.SetPointEYlow(i, rel_y_low * ratio) rel_y_high = math.sqrt( (g_data.GetErrorYhigh(i) / g_data_vals[i])**2 + (g.GetErrorYhigh(i) / g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0. g_ratio.SetPointEYhigh(i, rel_y_high * ratio) # Gymnastics to get same label sizes etc in ratio and main plot ytp_ratio = 2. xtp_ratio = 2. # hr.GetYaxis().SetNdivisions(4) g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio) g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio) g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() / xtp_ratio) g_ratio.GetXaxis().SetTitleOffset( g.GetXaxis().GetTitleOffset()) # / ytp_ratio) g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio) g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio) g_data.GetXaxis().SetLabelColor(0) g_data.GetXaxis().SetLabelSize(0) g.GetXaxis().SetLabelColor(0) g.GetXaxis().SetLabelSize(0) g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle()) # maxy = 1.1 * min(g.GetMaximum(), g_data.GetMaximum(), 0.2) g.GetYaxis().SetRangeUser(0.001, 0.2) cv, pad, padr = HistDrawer.buildCanvas() pad.cd() g.Draw('AP') g_data.Draw('P') legend = TLegend(0.23, 0.73, 0.43, 0.91) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetLineColor(0) legend.SetLineWidth(0) legend.AddEntry(g.GetName(), 'MC', 'lep') legend.AddEntry(g_data.GetName(), 'Observed', 'lep') legend.Draw() padr.cd() g_ratio.GetYaxis().SetRangeUser(0.51, 1.49) g_ratio.GetYaxis().SetTitle('Obs/MC') g_ratio.Draw('AP') drawRatioLines(g_ratio) cv.Print(plot_name)