def writeFullUnc(pred_file): ''' Update the input root file, add a hist with total prediction and full uncertainty. ''' f = rt.TFile(pred_file, 'UPDATE') h = TGraphAsymmErrors(f.Get(pred_total_name).Clone('bkgtotal_unc_sr')) h_syst = TGraphAsymmErrors( f.Get(pred_total_name).Clone('bkgtotal_syst_unc_sr')) h_pieces = {} h_syst_pieces = {} for hname, sample in zip(graph_names, all_samples): h_pieces[sample] = TGraphAsymmErrors( f.Get(hname).Clone(sample + '_unc_sr')) h_syst_pieces[sample + "_up"] = TH1F(sample + '_syst_up', sample + '_syst_up', 183, 0, 183) h_syst_pieces[sample + "_dn"] = TH1F(sample + '_syst_dn', sample + '_syst_dn', 183, 0, 183) print "%30s %10s %16s" % ('bin', 'total pred', 'total unc.') for ibin in xrange(0, h.GetN()): bin = binlist[ibin] val = h.GetY()[ibin] e_low, e_up = fullUnc[bin] h.SetPointEYlow(ibin, e_low) h.SetPointEYhigh(ibin, e_up) print "%30s %10.4f +%8.4f -%8.4f" % (bin, val, e_up, e_low) allVals[bin] = {'bkg': (val, e_low, e_up)} # Test for only syst histograms val = h_syst.GetY()[ibin] e_low, e_up = systUnc[bin] h_syst.SetPointEYlow(ibin, e_low) h_syst.SetPointEYhigh(ibin, e_up) for sample in all_samples: val = yields[bin][sample] e_low, e_up = fullUnc_pieces[sample][bin] #print "%11s %30s %10.4f +%8.4f -%8.4f" % (sample, bin, val, e_up, e_low) h_pieces[sample].SetPointEYlow(ibin, e_low) h_pieces[sample].SetPointEYhigh(ibin, e_up) allVals[bin][sample] = (val, e_low, e_up) # Test for only syst histograms e_low, e_up = systUnc_rel_pieces[sample][bin] #if sample in test_samp and bin in test_bin and type in test_type and debug: #if 'TTZ' in sample and e_up > 8: # print("%11s %30s %10.4f +%8.4f -%8.4f" % (sample, bin, val, e_up, e_low)) h_syst_pieces[sample + "_up"].SetBinContent(ibin + 1, e_up) h_syst_pieces[sample + "_dn"].SetBinContent(ibin + 1, e_low) h_syst_pieces[sample + "_up"].SetBinError(ibin + 1, 0) h_syst_pieces[sample + "_dn"].SetBinError(ibin + 1, 0) h.Write('bkgtotal_unc_sr', rt.TObject.kOverwrite) h.Write('bkgtotal_syst_unc_sr', rt.TObject.kOverwrite) for sample in all_samples: h_pieces[sample].Write(sample + '_unc_sr', rt.TObject.kOverwrite) h_syst_pieces[sample + "_up"].Write(sample + '_syst_up', rt.TObject.kOverwrite) h_syst_pieces[sample + "_dn"].Write(sample + '_syst_dn', rt.TObject.kOverwrite) f.Close()
def TextFileToRootGraphs(self, limit_text_file,med_idx=0):#, limit_text_filename): filename = limit_text_file #limit_text_filename limit_root_file = limit_text_file.replace(".txt",".root") f = open(filename,"r") med=array('f') mchi=array('f') expm2=array('f') expm1=array('f') expmed=array('f') expp1=array('f') expp2=array('f') obs=array('f') errx=array('f') for line in f: if len(line.rsplit())<7: continue med.append(float(line.rstrip().split()[1])) mchi.append(float(line.rstrip().split()[0])) expm2.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[2]) ) expm1.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[3]) ) expmed.append(float(line.rstrip().split()[4])) expp1.append(float(line.rstrip().split()[5]) - float(line.rstrip().split()[4]) ) expp2.append(float(line.rstrip().split()[6]) - float(line.rstrip().split()[4]) ) obs.append(float(line.rstrip().split()[7])) errx.append(0.0) print ('expm2: ', expm2) print ('expm1: ', expm1) print ('expmed: ', expmed) print ('expp1: ', expp1) print ('expp2: ', expp2) g_exp2 = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm2, expp2 ) ; g_exp2.SetName("exp2") g_exp1 = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm1, expp1 ) ; g_exp1.SetName("exp1") g_expmed = TGraphAsymmErrors(int(len(med)), med, expmed) ; g_expmed.SetName("expmed") g_obs = TGraphAsymmErrors(int(len(med)), med, obs ) ; g_obs.SetName("obs") f1 = TFile(limit_root_file,'RECREATE') g_exp2.Write() g_exp1.Write() g_expmed.Write() g_obs.Write() f1.Write() f1.Close() return limit_root_file
def writeFullUnc(pred_file): ''' Update the input root file, add a hist with total prediction and full uncertainty. ''' f = rt.TFile(pred_file, 'UPDATE') h = TGraphAsymmErrors(f.Get(pred_total_name).Clone('bkgtotal_unc_sr')) h_pieces = {} for hname, sample in zip(graph_names, all_samples): h_pieces[sample] = TGraphAsymmErrors( f.Get(hname).Clone(sample + '_unc_sr')) print "%30s %10s %16s" % ('bin', 'total pred', 'total unc.') for ibin in xrange(0, h.GetN()): bin = binlist[ibin] val = h.GetY()[ibin] e_low, e_up = fullUnc[bin] h.SetPointEYlow(ibin, e_low) h.SetPointEYhigh(ibin, e_up) print "%30s %10.2f +%8.2f -%8.2f" % (bin, val, e_up, e_low) allVals[bin] = {'bkg': (val, e_low, e_up)} for sample in all_samples: val = yields[bin][sample] e_low, e_up = fullUnc_pieces[sample][bin] h_pieces[sample].SetPointEYlow(ibin, e_low) h_pieces[sample].SetPointEYhigh(ibin, e_up) allVals[bin][sample] = (val, e_low, e_up) h.Write('bkgtotal_unc_sr', rt.TObject.kOverwrite) for sample in all_samples: h_pieces[sample].Write(sample + '_unc_sr', rt.TObject.kOverwrite) f.Close()
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 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 doeff(filename, histoname_den, histoname_num, histoname_out, outfile,rebin=1): numerator=filename.Get(histoname_num) denominator=filename.Get(histoname_den) if not rebin==1: numerator.Rebin(rebin) denominator.Rebin(rebin) n_num=numerator.Integral() n_den=denominator.Integral() error_bars=TGraphAsymmErrors() error_bars.Divide(numerator,denominator,"cl=0.683 b(1,1) mode") outfile.cd() error_bars.Write(histoname_out) return n_num/n_den
def PseudoTextToGraphTimeScan(textfilename): print "parsing: ", textfilename dirname = "timescanOutput/" filename = textfilename f = open(filename, "r").readlines() firstLine = f.pop(0) #removes the first line adc_ = array('f') adc_1 = array('f') adc_2 = array('f') adc_3 = array('f') adc_4 = array('f') prob = array('f') prob_e = array('f') errx = array('f') for line in f: adc_.append(float(line.rstrip().split()[0])) adc_1.append(float(line.rstrip().split()[0]) + 0.1) adc_2.append(float(line.rstrip().split()[0]) + 0.2) adc_3.append(float(line.rstrip().split()[0]) + 0.3) adc_4.append(float(line.rstrip().split()[0]) + 0.4) prob.append(float(line.rstrip().split()[1])) prob_e.append(float(line.rstrip().split()[2])) errx.append(0.0) g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e) g_prob_.SetName("prob_") f1 = TFile(filename.replace('.txt', '.root'), 'RECREATE') g_prob_.Write() f1.Close()
#adc_3 = [i+0.3 for i in adc_] #adc_4 = [i+0.4 for i in adc_] print adc_1 g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e) g_prob_.SetName("prob_") g_prob_26_ = TGraphAsymmErrors(int(len(adc_1)), adc_1, prob_26, errx, errx, prob_e_26, prob_e_26) g_prob_26_.SetName("prob_26_") g_prob_27_ = TGraphAsymmErrors(int(len(adc_)), adc_2, prob_27, errx, errx, prob_e_27, prob_e_27) g_prob_27_.SetName("prob_27_") g_prob_28_ = TGraphAsymmErrors(int(len(adc_)), adc_3, prob_28, errx, errx, prob_e_28, prob_e_28) g_prob_28_.SetName("prob_28_") g_prob_29_ = TGraphAsymmErrors(int(len(adc_)), adc_4, prob_29, errx, errx, prob_e_29, prob_e_29) g_prob_29_.SetName("prob_29_") f1 = TFile(filename.replace('.txt', '.root'), 'RECREATE') g_prob_.Write() g_prob_26_.Write() g_prob_27_.Write() g_prob_28_.Write() g_prob_29_.Write() f1.Close()
dirs['Andrew'] + "2017/zToMuMu") nEst = fakeTrackBkgdEstimate.printNest() g0.SetPoint(i, minD0, nEst.centralValue()) g0.SetPointError(i, D / 2.0, D / 2.0, min(nEst.maxUncertainty(), nEst.centralValue()), nEst.maxUncertainty()) if i == 0: nominal = nEst.centralValue() else: if nEst.centralValue() < nominal: maxFluctuationDown = max(maxFluctuationDown, nominal - nEst.centralValue()) else: maxFluctuationUp = max(maxFluctuationUp, nEst.centralValue() - nominal) sys.stdout = stdout print "[2017" + runPeriod + "] systematic uncertainty: - " + str( maxFluctuationDown) + " + " + str(maxFluctuationUp) + " (- " + str( (maxFluctuationDown / nominal) * 100.0) + " + " + str( (maxFluctuationUp / nominal) * 100.0) + ")%" sys.stdout = nullout fout = TFile("fakeTrackEstimateVsD0.root", "update") fout.cd() g0.Write("est_ZtoMuMu_2017" + runPeriod) fout.Close()
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()
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() chain4 = TChain('disTrkSelectionSmearedJetsNLayers4TreeMaker/Tree') chain5 = TChain('disTrkSelectionSmearedJetsNLayers5TreeMaker/Tree') chain6 = TChain('disTrkSelectionSmearedJetsNLayers6plusTreeMaker/Tree') chain4.Add('condor/2017/signalAcceptance_full_v8/AMSB_chargino_700GeV_100cm_94X/hist_*.root') chain5.Add('condor/2017/signalAcceptance_full_v8/AMSB_chargino_700GeV_100cm_94X/hist_*.root') chain6.Add('condor/2017/signalAcceptance_full_v8/AMSB_chargino_700GeV_100cm_94X/hist_*.root') (n4, w4) = reweightMET(chain4, grRatio) (n5, w5) = reweightMET(chain5, grRatio) (n6, w6) = reweightMET(chain6, grRatio)
leg.AddEntry(hCrossSec, f'measured', 'p') leg.AddEntry(hCrossSecExtrap, f'extrapolated', 'p') leg.AddEntry(hFONLL['cent'], f'FONLL + PYTHIA8 decayer', 'f') cCrossSec = TCanvas('cCrossSec', '', 500, 500) cCrossSec.DrawFrame( ptMinMeas, hCrossSecExtrap.GetMinimum() / 5, ptLimsForExtrap[-1], hCrossSecExtrap.GetMaximum() * 5, ';#it{p}_{T} (GeV/#it{c});d#sigma/d#it{p}_{T} #times BR (#mub GeV^{-1} #it{c})' ) cCrossSec.SetLogy() for var in ['cent', 'min', 'max']: hFONLL[var].Scale(1.e-6) hFONLL[var].Draw('hist same') gCrossSecExtrap.Draw('2') hCrossSecExtrap.Draw('same') gCrossSec.Draw('2') hCrossSec.Draw('same') leg.Draw() outFile = TFile(inCfg['outfilename'], 'recreate') hCrossSecExtrap.Write() gCrossSecExtrap.Write() gCrossSecExtrapSyst.Write() gCrossSecLumi.Write() systErr.Write() outFile.Close() input('Press enter to exit')
def plotEfficiency(self, doFit=False): if hasattr(self, "Denominator") and hasattr(self, "Numerator"): if self._rebinFactor != 1: self.Denominator["hist"].Rebin(self._rebinFactor) self.Numerator["hist"].Rebin(self._rebinFactor) for ibin in range(-1, self.Numerator["hist"].GetNbinsX() + 1): if self.Numerator["hist"].GetBinContent( ibin + 1) > self.Denominator["hist"].GetBinContent(ibin + 1): print 'Fixing bad bin:', (ibin + 1) self.Numerator["hist"].SetBinContent( ibin + 1, self.Denominator["hist"].GetBinContent(ibin + 1)) self.Numerator["hist"].SetBinError( ibin + 1, self.Denominator["hist"].GetBinError(ibin + 1)) efficiencyGraph = TGraphAsymmErrors(self.Numerator["hist"], self.Denominator["hist"], "cp") pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC") pt_cmsPrelim.SetBorderSize(0) pt_cmsPrelim.SetFillStyle(0) pt_cmsPrelim.SetTextFont(62) pt_cmsPrelim.SetTextSize(0.0374065) pt_cmsPrelim.AddText("CMS Preliminary") pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC") pt_lumi.SetBorderSize(0) pt_lumi.SetFillStyle(0) pt_lumi.SetTextFont(42) pt_lumi.SetTextSize(0.0374065) pt_lumi.AddText(self._luminosityLabel) pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC") pt_leg.SetBorderSize(0) pt_leg.SetFillStyle(0) pt_leg.SetTextFont(42) pt_leg.SetTextSize(0.0349127) pt_leg.SetTextAlign(12) if self._leg == "METLeg": legLabel = "" for filt in self._metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + self._metHLTFilters[-1] pt_leg.AddText(legLabel) pt_leg.AddText(self._datasetLabel) if self._leg == "TrackLeg": pt_leg.AddText(self._path + "*") pt_leg.AddText(self._datasetLabel) legLabel = "" for filt in self._metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + self._metHLTFilters[-1] + " applied" pt_leg.AddText(legLabel) if self._leg == "METPath": if self._path == "GrandOr": pt_leg.AddText("OR of Signal Paths") else: pt_leg.AddText(self._path + "*") pt_leg.AddText(self._datasetLabel) lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC") lumiLabel.SetBorderSize(0) lumiLabel.SetFillStyle(0) lumiLabel.SetTextFont(42) lumiLabel.SetTextSize(0.0387597) lumiLabel.AddText(str(self._luminosityLabel)) oneLine = TLine(xlo, 1.0, xhi, 1.0) oneLine.SetLineWidth(3) oneLine.SetLineStyle(2) backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi) backgroundHist.GetYaxis().SetTitle("Trigger Efficiency") backgroundHist.GetYaxis().SetRangeUser(ylo, yhi) if self._leg == "METLeg" or self._leg == "METPath": backgroundHist.GetXaxis().SetTitle(self._metLegAxisTitle) elif self._leg == "TrackLeg": backgroundHist.GetXaxis().SetTitle(self._trackLegAxisTitle) SetStyle(backgroundHist) SetStyle(efficiencyGraph) self._canvas.cd() backgroundHist.Draw() efficiencyGraph.Draw("P") pt_cmsPrelim.Draw("same") pt_lumi.Draw("same") pt_leg.Draw("same") oneLine.Draw("same") if doFit: (fitFunc, fitText) = self.PlotFit(efficiencyGraph) fitFunc.Draw("same") fitText.Draw("same") if not os.path.exists('plots_' + self.Denominator["sample"]): os.mkdir('plots_' + self.Denominator["sample"]) if self._leg == "METPath": self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_Efficiency.pdf") else: self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_" + self._leg + ".pdf") self._fout.cd() if self._tgraphSuffix is not None: efficiencyGraph.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix) if doFit: fitFunc.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix + "_fitResult") else: efficiencyGraph.Write(self._path + "_" + self._leg) if doFit: fitFunc.Write(self._path + "_" + self._leg + "_fitResult") else: print "Denominator and Numerator must be defined for path ", self._path, ", leg ", self._leg return 0.0
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()
def plotHistos(dac, histVals, qiCalib = None, outDir = "results", currentMode = ""): adcGraphs = [] chargeGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) convFactor = 1. if qiCalib is None: # Use nominal qiCalib print "Using nominal QI calibrations" if currentMode == "low": convFactor = 1.375 elif currentMode == "high": convFactor = 7.7 offset = 0. else: print "Using custom QI calibrations" #for i in range(len(histVals[dac[0]])): for i in range(12): adcGr = TGraphAsymmErrors() adcGr.SetMarkerStyle(22) #adcGr.SetMarkerSize(1.0) adcGr.SetName("h%d_ADC" % i) adcGr.SetTitle("h%d ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) chGr = TGraphAsymmErrors() chGr.SetMarkerStyle(22) #chGr.SetMarkerSize(1.3) chGr.SetName("h%d_LinADC" % i) chGr.SetTitle("h%d Lin ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) adcGraphs.append(adcGr) chargeGraphs.append(chGr) for i, dv in enumerate(dac): for n in range(len(adcGraphs)): mean = histVals[dv][n]["mean"] err = histVals[dv][n]["rms"] if qiCalib is not None: QIchan = int(n/6)*8 + n%6 + 1 convFactor = qiCalib[QIchan]["slope"] offset = qiCalib[QIchan]["offset"] # Index of new point np = adcGraphs[n].GetN() # Set value and error adcGraphs[n].SetPoint(np, dv*convFactor + offset, mean) adcGraphs[n].SetPointError(np, 0., 0., err, err) chMean, chErr = linADC(mean, err) chargeGraphs[n].SetPoint(np, dv*convFactor + offset, chMean) chargeGraphs[n].SetPointError(np, 0., 0., chErr, chErr) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/adcH; mkdir -p %s/chargeH" % (outDir, outDir) ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/histos.root", "RECREATE") xAxisTitle = "Charge [fC]" if currentMode in ["low", "high"] else "DAC value" for i,adcGr in enumerate(adcGraphs): """ adcGr.Fit('pol1', "Q") # Q: Quiet mode f = adcGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) """ adcGr.GetXaxis().SetTitle(xAxisTitle) adcGr.GetYaxis().SetTitle("ADC") adcGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) adcGr.Draw("AP") adcGr.Write() Quiet(c1.SaveAs)(outDir + "/adcH/adc_hist_%d.png" % i) c1.SetLogy(True) for i,chGr in enumerate(chargeGraphs): chGr.Fit('pol1', "Q") # Q: Quiet mode f = chGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) chGr.GetXaxis().SetTitle(xAxisTitle) chGr.GetYaxis().SetTitle("Linearized ADC") chGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) pad1.SetLogy(True) chGr.Draw("AP") chGr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.45,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/chargeH/charge_hist_%d.png" % i) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close()
def limit(method, channel): particle = channel[1:2] particleP = particle + "'" if channel.startswith('X') else channel[0] THEORY = ['A1', 'B3'] if channel.startswith('X') else [] suffix = "" if method == "hvt": suffix = "_HVT" if method == "cls": suffix = "_CLs" if method == "monoH": suffix = "_monoH" filename = "./combine/" + method + "/" + channel + "_M%d.txt" mass, val = fillValues(filename) 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]) Exp0s.SetPoint(n, m, val[m][3]) Exp1s.SetPoint(n, m, val[m][3]) Exp1s.SetPointError(n, 0., 0., val[m][3] - val[m][2], val[m][4] - val[m][3]) Exp2s.SetPoint(n, m, val[m][3]) Exp2s.SetPointError(n, 0., 0., val[m][3] - val[m][1], val[m][5] - val[m][3]) 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() for m in sorted(HVT[t]['Z']['XS'].keys()): if m < mass[0] or m > mass[-1]: continue XsW, XsW_Up, XsW_Down, XsZ, XsZ_Up, XsZ_Down = 0., 0., 0., 0., 0., 0. XsZ = 1000. * HVT[t]['Z']['XS'][m] * HVT[t]['Z']['BR'][m] 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, XsW + XsZ) Theory[t].SetPointError(n, 0., 0., (XsW - XsW_Down) + (XsZ - XsZ_Down), (XsW_Up - XsW) + (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 + "h) (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.01, 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)) drawAnalysis(channel) drawRegion(channel, True) drawCMS(LUMI, YEAR, "Preliminary") #Preliminary # legend top = 0.9 nitems = 4 + len(THEORY) leg = TLegend(0.55, 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() """ if True and channel.endswith('sl'): mass, val = fillValues("./combine/alpha/X"+particle+"Hbonly_M%d.txt") Exp, Obs = TGraphAsymmErrors(), TGraphAsymmErrors() for i, m in enumerate(mass): if not m in val: continue Exp.SetPoint(Exp.GetN(), m, val[m][3]) Obs.SetPoint(Obs.GetN(), m, val[m][0]) Exp.SetLineWidth(3) Exp.SetLineColor(602) #602 Exp.SetLineStyle(5) Obs.SetLineWidth(3) Obs.SetLineColor(602) Exp.Draw("SAME, L") Obs.Draw("SAME, L") mass15, val15 = fillValues("./combine/Vh_2015/X"+particle+"h_M%d.txt") Exp15, Obs15 = TGraphAsymmErrors(), TGraphAsymmErrors() for i, m in enumerate(mass15): if not m in val: continue Exp15.SetPoint(Exp15.GetN(), m, val15[m][3]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.)) Obs15.SetPoint(Obs15.GetN(), m, val15[m][0]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.)) Exp15.SetLineWidth(3) Exp15.SetLineColor(856) #602 Exp15.SetLineStyle(6) Obs15.SetLineWidth(3) Obs15.SetLineColor(856) Exp15.Draw("SAME, L") #Obs15.Draw("SAME, L") leg2.AddEntry(Exp, "1+2 b-tag", "l") """ if True and channel == 'AZh': massLL, valLL = fillValues("./combine/AZh/AZhll_M%d.txt") ExpLL, ObsLL = TGraphAsymmErrors(), TGraphAsymmErrors() for i, m in enumerate(massLL): if not m in val: continue ExpLL.SetPoint(ExpLL.GetN(), m, valLL[m][3] * multF) ObsLL.SetPoint(ObsLL.GetN(), m, valLL[m][0] * multF) ExpLL.SetLineWidth(3) ExpLL.SetLineColor(833) #602 ExpLL.SetLineStyle(5) ObsLL.SetLineWidth(3) ObsLL.SetLineColor(833) ExpLL.Draw("SAME, L") #ObsLL.Draw("SAME, L") massNN, valNN = fillValues("./combine/AZh/AZhnn_M%d.txt") ExpNN, ObsNN = TGraphAsymmErrors(), TGraphAsymmErrors() for i, m in enumerate(massNN): if not m in val: continue ExpNN.SetPoint(ExpNN.GetN(), m, valNN[m][3] * multF) ObsNN.SetPoint(ObsNN.GetN(), m, valNN[m][0] * multF) ExpNN.SetLineWidth(3) ExpNN.SetLineColor(855) #602 ExpNN.SetLineStyle(6) ObsNN.SetLineWidth(3) ObsNN.SetLineColor(855) ExpNN.Draw("SAME, L") #ObsNN.Draw("SAME, L") leg2.AddEntry(ExpLL, "Expected, A #rightarrow Zh #rightarrow llb#bar{b}", "l") leg2.AddEntry(ExpNN, "Expected, A #rightarrow Zh #rightarrow #nu#nub#bar{b}", "l") if method == 'combo': massAH, valAH = fillValues("./combine/dijet/X" + particle + "Hah_M%d.txt") ExpAH = TGraphAsymmErrors() for i, m in enumerate(massAH): if not m in val: continue ExpAH.SetPoint(ExpAH.GetN(), m, valAH[m][3] * multF) ExpAH.SetLineWidth(2) ExpAH.SetLineColor(602) #602 ExpAH.SetLineStyle(4) ExpAH.Draw("SAME, L") massSL, valSL = fillValues("./combine/alpha/X" + particle + "Hsl_M%d.txt") ExpSL = TGraphAsymmErrors() for i, m in enumerate(massSL): if not m in val: continue ExpSL.SetPoint(ExpSL.GetN(), m, valSL[m][3] * multF) ExpSL.SetLineWidth(3) ExpSL.SetLineColor(860 - 9) #602 ExpSL.SetLineStyle(7) ExpSL.Draw("SAME, L") leg2.AddEntry(ExpAH, "B2G-17-002", "l") leg2.AddEntry(ExpSL, "B2G-17-004", "l") 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("plotsLimit/Exclusion/" + channel + suffix + ".png") c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".C") c1.Print("plotsLimit/Exclusion/" + channel + 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 "" print "p1s[", for i in range(Exp0s.GetN()): print Exp0s.GetY()[i] + Exp1s.GetErrorYhigh(i), ",", print "]," print "m1s[", for i in range(Exp0s.GetN()): print Exp0s.GetY()[i] - Exp1s.GetErrorYlow(i), ",", print "]," print "[", for i in range(Exp0s.GetN()): print Exp0s.GetY()[i], ",", print "]" #if not 'ah' in channel and not 'sl' in channel: return # ---------- 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, YEAR, "Preliminary") drawAnalysis(channel[1:3]) c2.Print("plotsLimit/Significance/" + channel + suffix + ".png") c2.Print("plotsLimit/Significance/" + channel + suffix + ".pdf") # c2.Print("plotsLimit/Significance/"+channel+suffix+".root") # c2.Print("plotsLimit/Significance/"+channel+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, YEAR, "Preliminary") drawAnalysis(channel[1:3]) c3.Print("plotsLimit/pValue/" + channel + suffix + ".png") c3.Print("plotsLimit/pValue/" + channel + suffix + ".pdf") # c3.Print("plotsLimit/pValue/"+channel+suffix+".root") # c3.Print("plotsLimit/pValue/"+channel+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, YEAR, "Preliminary") drawAnalysis(channel[1:3]) c4.Print("plotsLimit/BestFit/" + channel + suffix + ".png") c4.Print("plotsLimit/BestFit/" + channel + suffix + ".pdf") # c4.Print("plotsLimit/BestFit/"+channel+suffix+".root") # c4.Print("plotsLimit/BestFit/"+channel+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 plot(inputfilename=None, histofilename="EfficiencyHistos.root", basecut="nTelTracks == 1", matchcut="hasHit == 0", ucells=0, vcells=0): ubins = ucells vbins = vcells total_cut = TCut(basecut) pass_cut = TCut(basecut) + TCut(matchcut) if inputfilename == None: return None rawfile = gROOT.FindObject(inputfilename) if rawfile: rawfile.Close() rawfile = TFile(inputfilename, 'READ') histofile = gROOT.FindObject(histofilename) if histofile: histofile.Close() histofile = TFile( histofilename, 'RECREATE', 'Efficiency histos created from input file ' + inputfilename) # Get access to tracks tree = rawfile.Get("Track") # Compute efficiency for v cells h_track_v_total = TH1F("h_track_v_total", "", vbins, 0, vcells) tree.Draw("cellV_fit >> +h_track_v_total", total_cut, "goff") h_track_v_total.GetXaxis().SetTitle("cellV_fit [cellID]") h_track_v_total.GetYaxis().SetTitle("tracks") h_track_v_pass = TH1F("h_track_v_pass", "", vbins, 0, vcells) tree.Draw("cellV_fit >> +h_track_v_pass", pass_cut, "goff") h_track_v_pass.GetXaxis().SetTitle("cellV_fit [cellID]") h_track_v_pass.GetYaxis().SetTitle("tracks") g_efficiency_v = TGraphAsymmErrors() g_efficiency_v.SetName("g_efficiency_v") g_efficiency_v.Divide(h_track_v_pass, h_track_v_total) g_efficiency_v.SetTitle("") g_efficiency_v.GetXaxis().SetTitle("cellV_fit [cellID]") g_efficiency_v.GetYaxis().SetTitle("efficiency") g_efficiency_v.Write() # Compute efficiency for u cells h_track_u_total = TH1F("h_track_u_total", "", ubins, 0, ucells) tree.Draw("cellU_fit >> +h_track_u_total", total_cut, "goff") h_track_u_total.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_u_total.GetYaxis().SetTitle("tracks") h_track_u_pass = TH1F("h_track_u_pass", "", ubins, 0, ucells) tree.Draw("cellU_fit >> +h_track_u_pass", pass_cut, "goff") h_track_u_pass.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_u_pass.GetYaxis().SetTitle("tracks") g_efficiency_u = TGraphAsymmErrors() g_efficiency_u.SetName("g_efficiency_u") g_efficiency_u.Divide(h_track_u_pass, h_track_u_total) g_efficiency_u.SetTitle("") g_efficiency_u.GetXaxis().SetTitle("cellU_fit [cellID]") g_efficiency_u.GetYaxis().SetTitle("efficiency") g_efficiency_u.Write() # Compute efficiency for u:v h_track_total = TH2F("h_track_total", "", ubins, 0, ucells, vbins, 0, vcells) tree.Draw("cellV_fit:cellU_fit >> +h_track_total", total_cut, "goff") h_track_total.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_total.GetYaxis().SetTitle("cellV_fit [cellID]") h_track_total.GetZaxis().SetTitle("tracks") h_track_pass = TH2F("h_track_pass", "", ubins, 0, ucells, vbins, 0, vcells) tree.Draw("cellV_fit:cellU_fit >> +h_track_pass", pass_cut, "goff") h_track_pass.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_pass.GetYaxis().SetTitle("cellV_fit [cellID]") h_track_pass.GetZaxis().SetTitle("tracks") g_efficiency = h_track_pass g_efficiency.SetName("g_efficiency") g_efficiency.Divide(h_track_pass, h_track_total) g_efficiency.SetTitle("") g_efficiency.GetXaxis().SetTitle("cellU_fit [cellID]") g_efficiency.GetYaxis().SetTitle("cellV_fit [cellID]") g_efficiency.GetZaxis().SetTitle("efficiency") g_efficiency.SetStats(0) g_efficiency.Write() # write the tree into the output file and close the file histofile.Write() histofile.Close() rawfile.Close()
AVGCORRYIELD, AVGSTATUNC, AVGFPROMPT, \ AVGFPROMPTLOW, AVGFPROMPTHIGH, AVGERROR = average_pkpi_pk0s(HISTO_PKPI, HISTO_PK0S, GRFD_PKPI, GRFD_PK0S, ERRSPKPI, ERRSPK0S, MATCHPKPI, MATCHPK0S, MATCHPKPIGR, MATCHPK0SGR) HISTAVG = HISTO_PK0S.Clone("histoSigmaCorr_average") GRFDAVG = TGraphAsymmErrors(PTBINS) for ipt in range(PTBINS): HISTAVG.SetBinContent(ipt + 1, AVGCORRYIELD[ipt]) HISTAVG.SetBinError(ipt + 1, AVGSTATUNC[ipt]) GRFDAVG.SetPoint(ipt + 1, GRFD_PK0S.GetX()[ipt + 1], AVGFPROMPT[ipt]) GRFDAVG.SetPointError(ipt+1, GRFD_PK0S.GetEXlow()[ipt+1], GRFD_PK0S.GetEXhigh()[ipt+1], \ AVGFPROMPTLOW[ipt], AVGFPROMPTHIGH[ipt]) AVGERROR.print() print("\n\n Store above in", ERROR_OUT) print("\n\n\nStoring ROOT objects in", FILE_OUT) FOUT = TFile(FILE_OUT, "RECREATE") FOUT.cd() HISTAVG.Write("histoSigmaCorr_average") HISTO_PKPI.Write("histoSigmaCorr_pKpi") HISTO_PK0S.Write("histoSigmaCorr_pK0s") GRFDAVG.Write("gFcCorrConservative_average") GRFD_PKPI.Write("gFcCorrConservative_pKpi") GRFD_PK0S.Write("gNbCorrConservative_pK0s") FOUT.Close()
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: 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() #print "m =", m, " --> fitted r / injected r = {:<7} / {:<7} = {:<5}".format(val[m][3], pull0[m], val[m][3]/pull0[m]) #print "m =", m, " --> central r = {:<5}".format(val[m][3]) print "m =", m, " --> 2.5 x central r = {:<5}".format(2.5*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, # 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 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) # if g_data.GetN() != hist_data_tight.GetNbinsX(): # import pdb; pdb.set_trace() 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.3 * max(g.GetMaximum(), g_data.GetMaximum(), 0.05) g.GetYaxis().SetRangeUser(0.0011, maxy) 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.01, 1.99) g_ratio.GetYaxis().SetTitle('Obs/MC') g_ratio.Draw('AP') drawRatioLines(g_ratio) cv.Print(plot_name) g.GetYaxis().SetRangeUser(0.0001, 1) pad.SetLogy(True) cv.Print(plot_name.replace('.', '_log.')) f = ROOT.TFile(plot_name.replace('.', '_log.').replace('.pdf', '.root'), 'RECREATE') g.Write() g_data.Write() cv.Write() f.Close()
def TextToGraphTimeScan(textfilename): dirname="timescanOutput/" #filenames=['timescanOutput/Rate_2017data_FrontTrain_cutval_2.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_4.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_6.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_8.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_10.txt'] filename = textfilename f = open(filename,"r").readlines() firstLine = f.pop(0) #removes the first line adc_ = array('f') adc_1 = array('f') adc_2 = array('f') adc_3 = array('f') adc_4 = array('f') prob = array('f') prob_e = array('f') prob_26 = array('f') prob_e_26 = array('f') prob_27 = array('f') prob_e_27 = array('f') prob_28 = array('f') prob_e_28 = array('f') prob_29 = array('f') prob_e_29 = array('f') errx = array('f') for line in f: adc_.append( float( line.rstrip().split()[0])) adc_1.append( float( line.rstrip().split()[0]) + 0.1) adc_2.append( float( line.rstrip().split()[0]) + 0.2) adc_3.append( float( line.rstrip().split()[0]) + 0.3) adc_4.append( float( line.rstrip().split()[0]) + 0.4) prob.append( float( line.rstrip().split()[1]) ) prob_e.append( float( line.rstrip().split()[2]) ) prob_26.append( float( line.rstrip().split()[3]) ) prob_e_26.append( float( line.rstrip().split()[4]) ) prob_27.append( float( line.rstrip().split()[5]) ) prob_e_27.append( float( line.rstrip().split()[6]) ) prob_28.append( float( line.rstrip().split()[7]) ) prob_e_28.append( float( line.rstrip().split()[8]) ) prob_29.append( float( line.rstrip().split()[9]) ) prob_e_29.append( float( line.rstrip().split()[10]) ) errx.append(0.0) #adc_1 = [i+0.1 for i in adc_] #adc_2 = [i+0.2 for i in adc_] #adc_3 = [i+0.3 for i in adc_] #adc_4 = [i+0.4 for i in adc_] print adc_1 g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e ) ; g_prob_.SetName("prob_") g_prob_26_ = TGraphAsymmErrors(int(len(adc_1)), adc_1, prob_26, errx, errx, prob_e_26, prob_e_26 ) ; g_prob_26_.SetName("prob_26_") g_prob_27_ = TGraphAsymmErrors(int(len(adc_)), adc_2, prob_27, errx, errx, prob_e_27, prob_e_27 ) ; g_prob_27_.SetName("prob_27_") g_prob_28_ = TGraphAsymmErrors(int(len(adc_)), adc_3, prob_28, errx, errx, prob_e_28, prob_e_28 ) ; g_prob_28_.SetName("prob_28_") g_prob_29_ = TGraphAsymmErrors(int(len(adc_)), adc_4, prob_29, errx, errx, prob_e_29, prob_e_29 ) ; g_prob_29_.SetName("prob_29_") f1 = TFile(filename.replace('.txt','.root'), 'RECREATE') g_prob_.Write() g_prob_26_.Write() g_prob_27_.Write() g_prob_28_.Write() g_prob_29_.Write() f1.Close()
adc_3.append(float(line.rstrip().split()[0]) + 0.3) adc_4.append(float(line.rstrip().split()[0]) + 0.4) prob.append(float(line.rstrip().split()[1])) #prob_e.append( float( line.rstrip().split()[2]) ) prob_26.append(float(line.rstrip().split()[2])) #prob_e_26.append( float( line.rstrip().split()[4]) ) errx.append(0.0) #adc_1 = [i+0.1 for i in adc_] #adc_2 = [i+0.2 for i in adc_] #adc_3 = [i+0.3 for i in adc_] #adc_4 = [i+0.4 for i in adc_] print adc_1 g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, errx, errx) g_prob_.SetName("iso_") g_prob_26_ = TGraphAsymmErrors(int(len(adc_1)), adc_1, prob_26, errx, errx, errx, errx) g_prob_26_.SetName("noniso_") f1 = TFile(filename.replace('.txt', '.root'), 'RECREATE') g_prob_.Write() g_prob_26_.Write() f1.Close()
def main(): """ Main function """ parser = argparse.ArgumentParser(description="Arguments to pass") parser.add_argument( "configfile_name", metavar="text", default="config_Dplus_pp5TeV.yml", help="input yaml config file", ) parser.add_argument("--batch", action="store_true", default=False, help="suppress video output") args = parser.parse_args() if args.batch: gROOT.SetBatch(True) # load info from config file with open(args.configfile_name, "r") as yml_configfile: cfg = yaml.safe_load(yml_configfile) frac_method = cfg["fraction"] histos, norm = load_inputs(cfg) # consistency check of bins ptlims = {} for histo in ["rawyields", "acceffp", "acceffnp"]: ptlims[histo] = get_hist_binlimits(histos[histo]) if (histo != "rawyields" and not np.equal(ptlims[histo], ptlims["rawyields"]).all()): print("\033[91mERROR: histo binning not consistent. Exit\033[0m") sys.exit(10) # compute cross section axistit_cross = "d#sigma/d#it{p}_{T} (pb GeV^{-1} #it{c})" axistit_cross_times_br = "d#sigma/d#it{p}_{T} #times BR (pb GeV^{-1} #it{c})" axistit_pt = "#it{p}_{T} (GeV/#it{c})" axistit_fprompt = "#if{f}_{prompt}" gfraction = TGraphAsymmErrors(0) gfraction.SetNameTitle("gfraction", f";{axistit_pt};{axistit_fprompt}") hptspectrum = TH1F( "hptspectrum", f";{axistit_pt};{axistit_cross}", len(ptlims["rawyields"]) - 1, ptlims["rawyields"], ) hptspectrum_wo_br = TH1F( "hptspectrum_wo_br", f";{axistit_pt};{axistit_cross_times_br}", len(ptlims["rawyields"]) - 1, ptlims["rawyields"], ) for i_pt, (ptmin, ptmax) in enumerate( zip(ptlims["rawyields"][:-1], ptlims["rawyields"][1:])): pt_cent = (ptmax + ptmin) / 2 pt_delta = ptmax - ptmin rawy = histos["rawyields"].GetBinContent(i_pt + 1) rawy_unc = histos["rawyields"].GetBinError(i_pt + 1) eff_times_acc_prompt = histos["acceffp"].GetBinContent(i_pt + 1) eff_times_acc_nonprompt = histos["acceffnp"].GetBinContent(i_pt + 1) ptmin_fonll = ( histos["FONLL"]["nonprompt"]["central"].GetXaxis().FindBin(ptmin * 1.0001)) ptmax_fonll = ( histos["FONLL"]["nonprompt"]["central"].GetXaxis().FindBin(ptmax * 0.9999)) crosssec_nonprompt_fonll = [ histos["FONLL"]["nonprompt"][pred].Integral( ptmin_fonll, ptmax_fonll, "width") / (ptmax - ptmin) for pred in histos["FONLL"]["nonprompt"] ] # compute prompt fraction if frac_method == "Nb": frac = compute_fraction_nb( # BR already included in FONLL prediction rawy, eff_times_acc_prompt, eff_times_acc_nonprompt, crosssec_nonprompt_fonll, pt_delta, 1.0, 1.0, norm["events"], norm["sigmaMB"], ) elif frac_method == "fc": crosssec_prompt_fonll = [ histos["FONLL"]["prompt"][pred].Integral( ptmin_fonll, ptmax_fonll, "width") / (ptmax - ptmin) for pred in histos["FONLL"]["prompt"] ] frac = compute_fraction_fc( eff_times_acc_prompt, eff_times_acc_nonprompt, crosssec_prompt_fonll, crosssec_nonprompt_fonll, ) # compute cross section times BR crosssec, crosssec_unc = compute_crosssection( rawy, rawy_unc, frac[0], eff_times_acc_prompt, ptmax - ptmin, 1.0, norm["sigmaMB"], norm["events"], 1.0, frac_method, ) hptspectrum.SetBinContent(i_pt + 1, crosssec / norm["BR"]) hptspectrum.SetBinError(i_pt + 1, crosssec_unc / norm["BR"]) hptspectrum_wo_br.SetBinContent(i_pt + 1, crosssec) hptspectrum_wo_br.SetBinError(i_pt + 1, crosssec_unc) gfraction.SetPoint(i_pt, pt_cent, frac[0]) gfraction.SetPointError(i_pt, pt_delta / 2, pt_delta / 2, frac[0] - frac[1], frac[2] - frac[0]) # create plots style_hist = StyleObject1D() style_hist.markercolor = kAzure + 4 style_hist.markerstyle = kFullCircle style_hist.markersize = 1 style_hist.linecolor = kAzure + 4 style_hist.linewidth = 2 style_hist.draw_options = "P" fig_crosssec = ROOTFigure(1, 1, column_margin=(0.14, 0.035), row_margin=(0.1, 0.035), size=(600, 800)) fig_crosssec.axes(label_size=0.025, title_size=0.030) fig_crosssec.axes("x", title=axistit_pt, title_offset=1.5) fig_crosssec.axes("y", title=axistit_cross_times_br, title_offset=1.8) fig_crosssec.define_plot(0, 0, y_log=True) fig_crosssec.add_object(hptspectrum_wo_br, style=style_hist) fig_crosssec.create() output_dir = cfg["output"]["directory"] if not os.path.exists(output_dir): os.makedirs(output_dir) fig_crosssec.save( os.path.join(output_dir, f'{cfg["output"]["filename"]}.pdf')) # save output file output_file = TFile( os.path.join(output_dir, f'{cfg["output"]["filename"]}.root'), "recreate") hptspectrum.Write() hptspectrum_wo_br.Write() gfraction.Write() for hist in histos: if isinstance(histos[hist], TH1): histos[hist].Write() else: for flav in histos[hist]: for pred in histos[hist][flav]: histos[hist][flav][pred].Write() output_file.Close()
def plotQIcalibration(results, outDir = "results", currentMode = ""): gROOT.SetBatch(True) calibGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) #for ch in xrange(1, len(results)+1): # Number of channels for ch in sorted(results.keys()): gr = TGraphAsymmErrors() gr.SetMarkerStyle(22) gr.SetMarkerSize(1.2) gr.SetName("Channel_%d_Charge_vs_DAC" % ch) gr.SetTitle("Channel %d Charge vs DAC value%s" % (ch, " %s current mode" % currentMode if currentMode in ["low", "high"] else "")) res = results[ch] for i, dacVal in enumerate(sorted(res.keys())): mean = res[dacVal]["mean"] * 25.e6 # Convert to fC err = res[dacVal]["std"] * 25.e6 # Index of new point np = gr.GetN() # Set value and error gr.SetPoint(np, dacVal, mean) gr.SetPointError(np, 0., 0., err, err) calibGraphs.append((gr,ch)) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/calibGraphs" % outDir ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/calibration.root", "RECREATE") fitParams = {} # Converted to charge by * 25ns for i,(gr,ch) in enumerate(calibGraphs): gr.Fit('pol1', "Q") # Q: Quiet mode f = gr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %g #pm %g slope %g #pm %g" % (p0, p0_err, p1, p1_err) # Convert to fC fitParams[ch] = {"slope":(p1), "offset":(p0)} #fitParams[(i+1)] = {"slope":(p1), "offset":(p0)} gr.GetXaxis().SetTitle("DAC value") gr.GetYaxis().SetTitle("Charge [fC]") if currentMode == "low": gr.GetYaxis().SetTitleOffset(1.37) pad1.cd() gr.Draw("AP") gr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.40,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/calibGraphs/channel_%d.png" % (i+1)) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close() return fitParams
hSignifCatania.Write('hSignifCatania') cSignif.Write() cSignif.SaveAs('%s_Significance.pdf' % outFileName) cBackground = TCanvas('cBackground', '', 500, 500) cBackground.SetLogy() hBackground.Draw() hBackground.Write('hBackground') cBackground.SaveAs('%s_Background.pdf' % outFileName) cFprompt = TCanvas('cFprompt', '', 500, 500) cFprompt.DrawFrame(cutVars['Pt']['min'][0], 0., cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1], 1., ';#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} (#it{f}_{c})') gFprompt.Draw('p') gFprompt.Write('gFprompt') cFprompt.SaveAs('%s_Fprompt.pdf' % outFileName) cEff = TCanvas('cEff', '', 500, 500) cEff.DrawFrame( cutVars['Pt']['min'][0], 1.e-4, cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1], 1., ';#it{p}_{T} (GeV/#it{c});(Acc #times #epsilon) #times 2#it{y}_{fid}') cEff.SetLogy() hAccEffPrompt.Draw('same') hAccEffFD.Draw('same') hAccEffPrompt.Write() hAccEffFD.Write() cEff.Write() cEff.SaveAs('%s_Efficiency.pdf' % outFileName)
totalGr.GetXaxis().SetTitle("Higgs mass [GeV/c^{2}]") totalGr.GetYaxis().SetTitle("Cross section [pb]") glugluGr.SetName("gg") glugluGr.SetTitle("gg") glugluGr.SetMarkerStyle(21) glugluGr.SetMarkerColor(2) glugluGr.SetFillColor(0) glugluGr.SetFillStyle(0) glugluGr.Draw("e1p") vbfGr.SetName("vbf") vbfGr.SetTitle("VBF") vbfGr.SetMarkerStyle(22) vbfGr.SetMarkerColor(4) vbfGr.SetFillColor(0) vbfGr.SetFillStyle(0) vbfGr.Draw("e1p") leg = c.BuildLegend() leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetTextFont(42) fout = ROOT.TFile.Open('thxsec.root', 'RECREATE') fout.cd() totalGr.Write() glugluGr.Write() vbfGr.Write() fout.Close()
"2016_final_prompt/fakeTrackBackground_d0Sideband_new") zToMuMuEstimate.addChannel( "DisTrkInvertD0NHits4", "ZtoMuMuDisTrkSidebandD0CutNHits4", "SingleMu_2016" + runPeriod, dirs['Andrew'] + "2016_final_prompt/fakeTrackBackground_d0Sideband_new") zToMuMuEstimate.addChannel( "DisTrkInvertD0NHits5", "ZtoMuMuDisTrkSidebandD0CutNHits5", "SingleMu_2016" + runPeriod, dirs['Andrew'] + "2016_final_prompt/fakeTrackBackground_d0Sideband_new") zToMuMuEstimate.addChannel( "DisTrkInvertD0NHits6", "ZtoMuMuDisTrkSidebandD0CutNHits6", "SingleMu_2016" + runPeriod, dirs['Andrew'] + "2016_final_prompt/fakeTrackBackground_d0Sideband_new") zToMuMuEstimate.addChannel( "Basic", "BasicSelection", "MET_2016" + runPeriod, dirs['Andrew'] + "2016_final_prompt/basicSelection_new") zToMuMuEstimate.addChannel( "ZtoLL", "ZtoMuMu", "SingleMu_2016" + runPeriod, dirs['Andrew'] + "2016_final_prompt/zToMuMu_new") nEst = zToMuMuEstimate.printNest() g1.SetPoint(i, minD0, nEst[0]) g1.SetPointError(i, D / 2.0, D / 2.0, min(nEst[1], nEst[0]), nEst[1]) fout = TFile("fakeTrackEstimateVsD0.root", "update") fout.cd() g0.Write("est_BasicSelection_2016" + runPeriod) g1.Write("est_ZtoMuMu_2016" + runPeriod) fout.Close()
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) etichetta.SetTextColor(4) etichetta.SetTextFont(102) etichetta.DrawLatex(0.45, 0.8, "#splitline{SL1_L1 threshold scan}{Runs: "+str(run_interval)+"}") can_scan_SL1_L1.Update() can_scan_SL1_L1.Print(outpath + "ThresholdScan_SL1_L1_"+run_interval+".png") can_scan_SL1_L1.Print(outpath + "ThresholdScan_SL1_L1_"+run_interval+".pdf") graph.SetName("ThresholdScan_SL1_L1_"+run_interval) new_file_SL1_L1 = TFile(outpath + "Graph_thresholdScan_SL1_L1_"+run_interval+ ".root",'RECREATE') graph.Write() graph.Set(0) #SL1_L4 can_scan_SL1_L4 = TCanvas("can_scan_SL1_L4","can_scan_SL1_L4", 1000, 800) can_scan_SL1_L4.SetGrid() can_scan_SL1_L4.cd() graph = TGraphAsymmErrors() n=0 for a in sorted(scan_SL1_L4): #print scan_SL1_L4[a] graph.SetPoint(n,a,scan_SL1_L4[a]) n = n+1 graph.SetMarkerSize(1.) graph.SetMarkerStyle(21) graph.SetMarkerColor(862)
log += str(ival_) + " " + str(expm2_) + " " + str( expm1_) + " " + str(expmed_) + " " + str(expp1_) + " " + str( expp2_) + " " + str(obs_) + "\n" # print ival, float(line.rstrip().split()[4]), xsec_, float(line.rstrip().split()[4])/xsec_ log += "\n" g_exp2 = TGraphAsymmErrors(int(len(xvals)), xvals, expmed, errx, errx, expm2, expp2) g_exp2.SetName("exp2") g_exp1 = TGraphAsymmErrors(int(len(xvals)), xvals, expmed, errx, errx, expm1, expp1) g_exp1.SetName("exp1") g_expmed = TGraphAsymmErrors(int(len(xvals)), xvals, expmed) g_expmed.SetName("expmed") g_obs = TGraphAsymmErrors(int(len(xvals)), xvals, obs) g_obs.SetName("obs") f1 = TFile(scanname + '/' + scanname + '_MH4-' + str(M) + '.root', 'RECREATE') g_exp2.Write() g_exp1.Write() g_expmed.Write() g_obs.Write() f1.Write() f1.Close() f.close() logfile = open("alllimits_" + scanname + ".txt", "w") logfile.write(log) logfile.close()
etichetta.SetNDC() etichetta.SetTextSize(0.04) etichetta.SetTextColor(418) etichetta.SetTextFont(102) etichetta.DrawLatex( 0.2, 0.8, "#splitline{SL1_L1 HV scan}{Runs: " + str(run_interval) + "}") can_HV_scan_SL1_L1.Update() can_HV_scan_SL1_L1.Print(outpath + "HVScan_SL1_L1_" + str(run_interval) + options.optionalstring + ".png") can_HV_scan_SL1_L1.Print(outpath + "HVScan_SL1_L1_" + str(run_interval) + options.optionalstring + ".pdf") graph_HV_L1.SetName("HV_scan_SL1_L1_" + run_interval) new_file_HV_scan_SL1_L1 = TFile( outpath + "Graph_HV_scan_SL1_L1_" + run_interval + options.optionalstring + ".root", 'RECREATE') graph_HV_L1.Write() graph_HV_L1.Set(0) print "Graph_HV_scan_SL1_L1_" + run_interval + options.optionalstring + ".root written in " + outpath ##Prepare the canvas to plot the HV scan for SL1_L4 can_HV_scan_SL1_L4 = TCanvas("can_HV_scan_SL1_L4", "can_HV_scan_SL1_L4", 1000, 800) can_HV_scan_SL1_L4.SetGrid() can_HV_scan_SL1_L4.cd() ##Prepare summary TGraph graph_HV_L4 = TGraphAsymmErrors() n = 0 for a in sorted(HV_scan_L4): #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_SL4_L4']))