plt.ylim(-10,5) print i,tddc,tzc plt.show() i+=1 if(i > NCNT): break # tz = [tzi - 80 - 0.7055 for tzi in tz] tz = [tzi - 70 for tzi in tz] h1 = TH1F('h1','',400,-40,40) for tzi in tz: if(tzi < 20 and tzi > -20): h1.Fill(tzi) hmean = h1.GetMean() hrms = h1.GetRMS() f1 = TF1('f1','gaus',-40,40) h1.Fit('f1') p0 = f1.GetParameter(0) p1 = f1.GetParameter(1) p2 = f1.GetParameter(2) fout = open("spread.txt",'a') sout = "directory=%s NCNT=%d TAU=%f FGSPS=%f VTHR=%f NAVG1=%f CFDD=%f CFDTHR=%f const=%f mean=%f sigma=%f HMEAN=%f HRMS=%f\n" % (directory,NCNT,TAU,FGSPS,VTHR,NAVG1,CFDD,CFDTHR,p0,p1,p2,hmean,hrms) print sout fout.write(sout) fout.close() h1.Draw()
abs_alpha = abs(par[0]) if (t >= -abs_alpha): return par[4] * exp(-0.5 * t * t) else: nDivAlpha = par[1] / abs_alpha AA = exp(-0.5 * abs_alpha * abs_alpha) B = nDivAlpha - abs_alpha arg = nDivAlpha / (B - t) return par[4] * (arg**par[1]) CrystalBall = TF1("CrystalBall", CrystalBall_raw, fit_start, fit_end, 5) def CrystalBallGaus_raw(x, par): if par[3] < 0: return 0 t = (x[0] - par[2]) / par[3] if (par[0] < 0): t = -t abs_alpha = abs(par[0]) if (t >= -abs_alpha): return par[4] * exp(-0.5 * t * t + exp(-(x[0] - par[5])**2 /
def fit(histo, outdir, file=0, Ecm=0): """Fit the transverse profile to gat the parametrization and save in root file""" canvas_fit = TCanvas("c_fit_{}_{}".format(histo, Ecm), "c_fit", 800, 600) if not file: infile = outdir + ".root" else: infile = file file_ = TFile(infile, "r") file_.cd() g_fit = gDirectory.Get(histo) g_fit.Draw() par = array('d', 13 * [0.]) f1 = TF1("f1", "gaus", -4, -3.5) g_fit.Fit(f1, "R0") par1 = f1.GetParameters() tail1 = TF1("tail1", "crystalball", -6, -3.5) tail1.SetParameters(par1[0], par1[1], par1[2], 1.0, 1.6) tail1.SetLineColor(3) g_fit.Fit(tail1, "R0+") par2 = tail1.GetParameters() tail2 = TF1("tail2", "crystalball", -4, -2) tail2.SetParameters(par1[0], par1[1], par1[2], -0.68, 1.85) tail2.SetLineColor(4) g_fit.Fit(tail2, "R0+") par3 = tail2.GetParameters() par[0], par[1], par[2] = par1[0], par1[1], par1[2] par[3], par[4], par[5], par[6], par[7] = par2[0], par1[1], par2[2], par2[ 3], par2[4] par[8], par[9], par[10], par[11], par[12] = par3[0], par1[1], par3[ 2], par3[3], par3[4] total = TF1("total", 'gaus(0)+crystalball(3)+crystalball(8)', -6, -2.3) total.SetParameters(par) total.SetLineColor(1) g_fit.Fit(total, "R+") # gStyle.SetOptFit(1) tot_param = total.GetParameters() sum_sigma = sqrt(tot_param[2] * tot_param[2] + tot_param[5] * tot_param[5] + tot_param[10] * tot_param[10]) print sum_sigma sum_sigma2 = sqrt(par1[2] * par1[2] + par2[2] * par2[2] + par3[2] * par3[2]) print "Verif = ", sum_sigma2 uncertainty = TLatex() uncertainty.DrawLatex(0, 0, "#sigma = {}".format(sum_sigma)) # write into the output file and close the file0 outFileName = "{}.root".format(outdir) outFile = TFile(outFileName, "UPDATE") raw_input("hit a key to exit") canvas_fit.Write("", TObject.kOverwrite) outFile.Write() outFile.Close()
#coding=utf-8 from __future__ import division, print_function from ROOT import TGraph, TGraphErrors, TCanvas, TF1 import style import sys style.style.cd() name_in = sys.argv[1] can = TCanvas("can", "can") gr = TGraphErrors(name_in) gr.SetTitle("curva di risonanza;#nu [Hz];A [V]") gr.Draw("AP") fu = TF1("fu_ris", "[0]/sqrt(1+[1]*(x^2-[2]^2)^2)", 300, 700) fu.SetParameters(1.41,0.00000001,563.7) fu.SetNpx(100000) gr.Fit("fu_ris", "W") can.SaveAs("relazione/img/" + name_in + ".eps") print("\\begin{tabular}{r@{ $\\pm$ }lr@{ $\\pm$ }l}") print("\\multicolumn{2}{c}{$\\nu$ [Hz]} &\\multicolumn{2}{c}{$A$ [V]} \\\\ ") print("\\hline") with open(name_in) as file: for line in file: if "//" in line: continue line = [float(x) for x in line.split()] print("{0[0]:.0f} & {0[2]:.0f} & {0[1]:.3f} & {0[3]:.3f} \\\\ ".format(line)) print("\\end{tabular}")
def do_significance(self): self.df_evt_data = pd.read_pickle(self.f_evt_data) self.df_evttotsample_data = pd.read_pickle(self.f_evttotsample_data) #first extract the number of data events in the ml sample #and in the total number of events self.p_nevttot = len(self.df_evttotsample_data) self.p_nevtml = len(self.df_evt_data) print("Number of data events used for ML: %d", self.p_nevtml) print("Total number of data events: %d", self.p_nevttot) #calculate acceptance correction. we use in this case all #the signal from the mc sample, without limiting to the n. signal #events used for training denacc = len(self.df_mcgen[self.df_mcgen["ismcprompt"] == 1]) numacc = len(self.df_mc[self.df_mc["ismcprompt"] == 1]) acc, acc_err = self.calceff(numacc, denacc) print("acceptance and error", acc, acc_err) #calculation of the expected fonll signals df_fonll = pd.read_csv(self.f_fonll) ptmin = self.p_binmin ptmax = self.p_binmax df_fonll_in_pt = \ df_fonll.query('(pt >= @ptmin) and (pt < @ptmax)')[self.p_fonllband] prod_cross = df_fonll_in_pt.sum() * self.p_fragf * 1e-12 / len( df_fonll_in_pt) delta_pt = ptmax - ptmin signal_yield = 2. * prod_cross * delta_pt * self.p_br * acc * self.p_taa \ / (self.p_sigmamb * self.p_fprompt) print("Expected signal yield: %f", signal_yield) signal_yield = self.p_raahp * signal_yield print("Expected signal yield x RAA hp: %f", signal_yield) #now we plot the fonll expectation plt.figure(figsize=(20, 15)) plt.subplot(111) plt.plot(df_fonll['pt'], df_fonll[self.p_fonllband] * self.p_fragf, linewidth=4.0) plt.xlabel('P_t [GeV/c]', fontsize=20) plt.ylabel('Cross Section [pb/GeV]', fontsize=20) plt.title("FONLL cross section " + self.p_case, fontsize=20) plt.semilogy() plt.savefig(f'{self.dirmlplot}/FONLL_curve_{self.s_suffix}.png') df_data_sideband = self.df_data.query(self.s_selbkgml) df_data_sideband = shuffle(df_data_sideband, random_state=self.rnd_shuffle) df_data_sideband = df_data_sideband.tail( round(len(df_data_sideband) * self.p_bkgfracopt)) hmass = TH1F('hmass', '', self.p_num_bins, self.p_mass_fit_lim[0], self.p_mass_fit_lim[1]) df_mc_signal = self.df_mc[self.df_mc["ismcsignal"] == 1] mass_array = df_mc_signal['inv_mass'].values for mass_value in np.nditer(mass_array): hmass.Fill(mass_value) gaus_fit = TF1("gaus_fit", "gaus", self.p_mass_fit_lim[0], self.p_mass_fit_lim[1]) gaus_fit.SetParameters(0, hmass.Integral()) gaus_fit.SetParameters(1, self.p_mass) gaus_fit.SetParameters(2, 0.02) print("To fit the signal a gaussian function is used") fitsucc = hmass.Fit("gaus_fit", "RQ") if int(fitsucc) != 0: print("Problem in signal peak fit") sigma = 0. sigma = gaus_fit.GetParameter(2) print("Mean of the gaussian: %f", gaus_fit.GetParameter(1)) print("Sigma of the gaussian: %f", sigma) sig_region = [self.p_mass - 3 * sigma, self.p_mass + 3 * sigma] fig_signif_pevt = plt.figure(figsize=(20, 15)) plt.xlabel('Threshold', fontsize=20) plt.ylabel(r'Significance Per Event ($3 \sigma$)', fontsize=20) plt.title("Significance Per Event vs Threshold", fontsize=20) fig_signif = plt.figure(figsize=(20, 15)) plt.xlabel('Threshold', fontsize=20) plt.ylabel(r'Significance ($3 \sigma$)', fontsize=20) plt.title("Significance vs Threshold", fontsize=20) for name in self.p_classname: print(name) df_sig = self.df_mltest[self.df_mltest["ismcprompt"] == 1] eff_array, eff_err_array, x_axis = self.calc_sigeff_steps( self.p_nstepsign, df_sig, name) df_bkg = self.df_mltest[self.df_mltest["ismcprompt"] == 0] df_bkg = df_bkg[df_bkg["ismcsignal"] == 0] bkg_array, bkg_err_array, _ = calc_bkg( df_data_sideband, name, self.p_nstepsign, self.p_mass_fit_lim, self.p_bin_width, sig_region, self.p_savefit, self.dirmlplot) sig_array = [eff * signal_yield for eff in eff_array] sig_err_array = [ eff_err * signal_yield for eff_err in eff_err_array ] bkg_array = [ bkg / (self.p_bkgfracopt * self.p_nevtml) for bkg in bkg_array ] bkg_err_array = [bkg_err / (self.p_bkgfracopt * self.p_nevtml) \ for bkg_err in bkg_err_array] signif_array, signif_err_array = calc_signif( sig_array, sig_err_array, bkg_array, bkg_err_array) plt.figure(fig_signif_pevt.number) plt.errorbar(x_axis, signif_array, yerr=signif_err_array, alpha=0.3, label=f'{name}', elinewidth=2.5, linewidth=4.0) signif_array_ml = [ sig * sqrt(self.p_nevtml) for sig in signif_array ] signif_err_array_ml = [ sig_err * sqrt(self.p_nevtml) for sig_err in signif_err_array ] plt.figure(fig_signif.number) plt.errorbar(x_axis, signif_array_ml, yerr=signif_err_array_ml, alpha=0.3, label=f'{name}_ML_dataset', elinewidth=2.5, linewidth=4.0) signif_array_tot = [ sig * sqrt(self.p_nevttot) for sig in signif_array ] signif_err_array_tot = [ sig_err * sqrt(self.p_nevttot) for sig_err in signif_err_array ] plt.figure(fig_signif.number) plt.errorbar(x_axis, signif_array_tot, yerr=signif_err_array_tot, alpha=0.3, label=f'{name}_Tot', elinewidth=2.5, linewidth=4.0) plt.figure(fig_signif_pevt.number) plt.legend(loc="lower left", prop={'size': 18}) plt.savefig( f'{self.dirmlplot}/Significance_PerEvent_{self.s_suffix}.png') plt.figure(fig_signif.number) plt.legend(loc="lower left", prop={'size': 18}) plt.savefig(f'{self.dirmlplot}/Significance_{self.s_suffix}.png')
return (freq, err) with open(file_output,'w') as file_out: with open(file_dati) as file: for line in file: if line[0] is '#': continue f, vin, vout = map(float, line.split()) a = vout / vin output_line = " ".join(map(str, (f, a, 0, a*0.06))) + "\n" file_out.write(output_line) canv = TCanvas('ampli','ampli') gr = TGraphErrors(file_output) # #create functions inf = TF1('inferiore','[0]+[1]*x',0,35) sup = TF1('superiore','[0]+[1]*x',2e3,4e3) amplifica = TF1('amplificazione', '[0]', 300, 650) amplifica.SetParameter("0",22) amplifica.SetLineStyle(7) #dashed amplifica.SetLineWidth(1) canv.SetLogx() gr.Fit('inferiore', 'QR+') gr.Fit('superiore', 'QR+') gr.Fit('amplificazione', 'QR+') amplificazione = amplifica.GetParameter(0) ampl_taglio = amplificazione / math.sqrt(2) taglio = TF1('ampiezzataglio', str(ampl_taglio),0,5e3) gr = set_graph_style(gr) taglio.SetLineStyle(7) #dashed taglio.SetLineWidth(1)
pCMS22.SetTextAlign(32) pCMS22.SetFillStyle(-1) pCMS22.SetBorderSize(0) #pCMS22.AddText(channel_name) pCMS2 = ROOT.TPaveText(0.5, 1. - top, 1. - right * 0.5, 1., "NDC") pCMS2.SetTextFont(42) pCMS2.SetTextSize(top * 0.75) pCMS2.SetTextAlign(32) pCMS2.SetFillStyle(-1) pCMS2.SetBorderSize(0) pCMS2.AddText("35.9 fb^{-1} (13 TeV)") for num in range(0, len(hist_names)): func_erf_Up = TF1("erffuncUp", "[0]/2.*(1.+TMath::Erf((x-[1])/[2]))", 0., 600.) func_erf_Up.SetLineWidth(1) func_erf_Up.SetLineColor(ROOT.kRed - 7) func_erf_Up.SetFillColor(ROOT.kRed - 7) func_erf_Up.SetFillStyle(3004) func_erf_Up.SetParameters(1., 82, 30.) # func_erf_Up.SetParameters(1.,76,30.) # func_erf_Up.SetParameters(1.,24,30.) list_ratio_data_mcUp[num].Fit(func_erf_Up, "R", "N", 0, 600.) func_erf_Down = TF1("erffuncDown", "[0]/2.*(1.+TMath::Erf((x-[1])/[2]))", 0., 600.) func_erf_Down.SetLineWidth(1) func_erf_Down.SetLineColor(ROOT.kRed - 7) func_erf_Down.SetFillColor(10) func_erf_Down.SetFillStyle(1001) func_erf_Down.SetParameters(1., 82, 30.)
from ROOT import gROOT, gStyle, gApplication from ROOT import kRed, kTRUE # set some global style options gROOT.SetStyle('Plain') gStyle.SetOptFit(1) TGaxis.SetMaxDigits(3) ## define fit function def decay(x, par): return par[0] * exp(-x[0] / par[1]) # set fit range, parameter names and start values myfit = TF1('myfit', decay, 0., 20.e3, 2) myfit.SetParName(0, 'A') myfit.SetParameter(0, 10.) myfit.SetParName(1, 'tau') myfit.SetParameter(1, 200.) # set fit line style myfit.SetLineColor(kRed) myfit.SetLineWidth(1) ## perform analysis def analyseDecay(fname): global file, c1, c2 # load histograms from file
abs_alpha = abs(par[0]) if (t >= -abs_alpha): return par[4] * exp(-0.5 * t * t) else: nDivAlpha = par[1] / abs_alpha AA = exp(-0.5 * abs_alpha * abs_alpha) B = nDivAlpha - abs_alpha arg = nDivAlpha / (B - t) return par[4] * (arg**par[1]) CrystalBall = TF1("CrystalBall", CrystalBall_raw, 40, 150, 5) def CrystalBallGaus_raw(x, par): if par[3] < 0: return 0 t = (x[0] - par[2]) / par[3] if (par[0] < 0): t = -t abs_alpha = abs(par[0]) if (t >= -abs_alpha): return par[4] * exp(-0.5 * t * t + exp(-(x[0] - par[5])**2 /
injToElectrons = 1660. / .25 # WARNING: different depending the version of the chip: v2: 1660/0.39 v4:1660/0.25 # -------- Fill dictionaries with function AnalyseThresholdScan() in functions.pyc DIC_AnalyseThresholdScan = AnalyseThresholdScanV4(FileDataThrScan) TDAC_value_dic = DIC_AnalyseThresholdScan[0] Threshold_value_dic = DIC_AnalyseThresholdScan[1] Sigma_value_dic = DIC_AnalyseThresholdScan[2] Chi2_value_dic = DIC_AnalyseThresholdScan[3] Scurve_plot_dic = DIC_AnalyseThresholdScan[4] Data_pointsX_dic = DIC_AnalyseThresholdScan[5] Data_pointsY_dic = DIC_AnalyseThresholdScan[6] # -------- Set histograms and fitting function myfit = TF1("myfit", "[0]+0.5*TMath::Erf([1]*([2]+x))", -1., 3000.) TDAC2D = TH2F("TDAC2D", "TDAC 2D plot;#Row;#Column;Threshold [e]", 12, 0, 12, 24, 24, 48) TDAC1D = TH1F("TDACDist", "TDAC distribution;Threshold [e];nb of pixels", 16, 0, 16) thresh2D = TH2F("thresh2D", "Thresh2D;#Row;#Column;Threshold [e]", 12, 0, 12, 24, 24, 48) thresh1D = TH1F("threshDist", "Threshold distribution;Threshold [e];nb of pixels", 300, -.1, 4000) sigma2D = TH2F("sigma2D", "Sigma 2D plot;#Row;#Column;Sigma [e]", 12, 0, 12, 24, 24, 48) sigma1D = TH1F("sigmaDist", "Sigma distribution;Sigma [e];nb of pixels", 300, -.1, 500) chi2_1D = TH1F("chi2Dist", "Chi2 distribution; ;nb of pixels", 300, 0, 1) chi2_2D = TH2F("chi2_2D", "Chi2 2D plot;#Row;#Column;chi2", 12, 0, 12, 24, 24,
pad2.SetTopMargin((padOverlap) / (padRatio + padOverlap)) pad2.SetBottomMargin(B / H / (padRatio + padOverlap)) pad2.SetFillColor(0) pad2.SetFillStyle(4000) pad2.SetBorderMode(0) pad2.SetFrameFillStyle(0) pad2.SetFrameBorderMode(0) pad2.SetTickx(0) pad2.SetTicky(0) pad1.Draw() pad2.Draw() noData = False oneLine = TF1("oneline", "1", -9e9, 9e9) oneLine.SetLineColor(kBlack) oneLine.SetLineWidth(1) oneLine.SetLineStyle(2) maxVal = stack.GetMaximum() if not noData: maxVal = max(rebinnedData.GetMaximum(), maxVal) minVal = 0 # minVal = max(stack.GetStack()[0].GetMinimum(),1) stack.SetMaximum(1.75 * maxVal) stack.SetMinimum(minVal) errorband = stack.GetStack().Last().Clone("error") errorband.Sumw2()
def Make_Mu_FakeRate(channelName): HistoFakeNum=ObjectPT+"_LowMT_LowDPhi_Iso" HistoFakeDeNum=ObjectPT+"_LowMT_LowDPhi_Total" ShapeNum=MakeTheHistogram(channelName,HistoFakeNum,HistoFakeNum,BinningFake,1) HistoNum=ShapeNum.Get("HISTO") ShapeDeNum=MakeTheHistogram(channelName,HistoFakeDeNum,HistoFakeDeNum,BinningFake,1) HistoDeNum=ShapeDeNum.Get("HISTO") print "\n---------------------------------------------------------------------------\n" print "overal FR = ", HistoNum.Integral()/ HistoDeNum.Integral(), "\n" print "---------------------------------------------------------------------------\n\n" HistoNum.Divide(HistoDeNum) canv = TCanvas("canv", "histograms", 600, 600) # HistoNum.SetMinimum(0.5) # HistoNum.GetXaxis().SetRangeUser(0,400) canv.SetLogy() # canv.SetGridx() canv.SetGridy() HistoNum.SetTitle("") if FR_vs_LeptonPT: HistoNum.GetXaxis().SetTitle("#mu p_{T} [GeV]") else: HistoNum.GetXaxis().SetTitle("Jet p_{T} [GeV]") HistoNum.GetYaxis().SetTitle("#mu Fake Rate (Tight Iso / Loose Iso)") HistoNum.GetYaxis().SetTitleOffset(1.3) HistoNum.GetYaxis().SetRangeUser(0.05,2) HistoNum.SetStats(0) HistoNum.SetMarkerStyle(20) # ###### Fit parameters for fake rate v.s. Jet Pt ##### Fit parameters for fake rate v.s. muon Pt # number of parameters in the fit if FR_vs_LeptonPT: nPar = 3 theFit=TF1("theFit", _FIT_Lepton, 80, 500,nPar) theFit.SetParameter(0, .2) theFit.SetParLimits(0, 0.1, 0.4) theFit.SetParameter(1, 4) theFit.SetParameter(2, -.30) else: nPar = 5 theFit=TF1("theFit",_FIT_Jet,60,500,nPar) # theFit.SetParLimits(0, 0, 0.5); ## theFit.SetParameter(0, 0.03) ## theFit.SetParameter(1, 0) # theFit.SetParameter(2, 0.6) # theFit.SetParameter(3, -0.6) ## theFit.SetParameter(4, 196.6) #Loose # theFit.SetParLimits(0, 0, 0.5); # theFit.SetParameter(0, 0.03) # theFit.SetParameter(1, 0) theFit.SetParameter(2, 0.6) # theFit.SetParameter(3, -0.6) # theFit.SetParameter(4, 96.6) HistoNum.Fit("theFit", "R0") HistoNum.Draw("E1") theFit.SetLineWidth(3) theFit.SetLineColor(3) FitParam=theFit.GetParameters() theFit.Draw("SAME") legende=make_legend() legende.AddEntry(HistoNum,"Jet#rightarrow#mu fake rate","lp") legende.AddEntry(theFit,"Fit (Landau+Pol1)","l") legende.Draw() l1=add_lumi() l1.Draw("same") l2=add_CMS() l2.Draw("same") l3=add_Preliminary() l3.Draw("same") categ = ROOT.TPaveText(0.51, 0.45+0.013, 0.93, 0.60+0.155, "NDC") categ.SetBorderSize( 0 ) categ.SetFillStyle( 0 ) categ.SetTextAlign( 12 ) categ.SetTextSize ( 0.04 ) categ.SetTextColor( 1 ) categ.SetTextFont ( 41 ) categ.AddText(channelName+" channel") # categ.Draw() canv.SaveAs("muFakeRate"+channelName+".pdf") canv.SaveAs("muFakeRate"+channelName+".root") if FR_vs_LeptonPT: return FitParam[0],FitParam[1],FitParam[2] else: return FitParam[0],FitParam[1],FitParam[2],FitParam[3],FitParam[4]
def draw(): N = 8 ecms = array('f', N * [0]) ecms_err = array('f', N * [0]) factor = array('f', N * [0]) factor_err = array('f', N * [0]) path = './txts/sys_err_window_raw.txt' mbc = TCanvas('mbc', 'mbc', 800, 600) set_canvas_style(mbc) f = open(path, 'r') lines = f.readlines() count = 0 sum_mean = 0 sum_err = 0 for line in lines: fargs = map(float, line.strip('\n').strip().split()) ecms[count] = fargs[0] ecms_err[count] = 0.0022 factor[count] = fargs[1] factor_err[count] = fargs[2] sum_mean += fargs[1] sum_err += fargs[2] count += 1 grerr = TGraphErrors(N, ecms, factor, ecms_err, factor_err) xtitle = 'E_{cms} (GeV)' ytitle = 'f^{RM(D^{+}#pi_{0}^{+}#pi_{0}^{-})}' set_graph_style(grerr, xtitle, ytitle) f = TF1('f', '[0]', ecms[0], ecms[1]) grerr.Fit(f) chi2 = f.GetChisquare() ndf = f.GetNDF() F = f.GetParameter(0) F_err = f.GetParError(0) grerr.Draw('ap') pt = TPaveText(0.35, 0.65, 0.75, 0.85, "BRNDC") set_pavetext(pt) pt.Draw() line = 'f#pm#sigma_{f^{RM(D^{+}#pi_{0}^{+}#pi_{0}^{-})}} = ' + str( round(F, 3)) + '#pm' + str(round(F_err, 3)) pt.AddText(line) line = '#chi^{2}/ndf = ' + str(round(chi2, 3)) + '/' + str(round( ndf, 3)) + ' = ' + str(round(chi2 / ndf, 3)) pt.AddText(line) line = '#Delta_{f^{RM(D^{+}#pi_{0}^{+}#pi_{0}^{-})}}/#sigma_{f^{RM(D^{+}#pi_{0}^{+}#pi_{0}^{-})}}=' + str( round((1 - F) / F_err, 3)) pt.AddText(line) mbc.Update() if not os.path.exists('./figs/'): os.makedirs('./figs/') mbc.SaveAs('./figs/sys_err_window.pdf') if not os.path.exists('./txts/'): os.makedirs('./txts/') with open('./txts/f_rm_Dpipi.txt', 'w') as f_out: f_out.write(str(F) + '\n') ecms = [ 4190, 4200, 4210, 4220, 4230, 4237, 4245, 4246, 4260, 4270, 4280, 4290, 4310, 4315, 4340, 4360, 4380, 4390, 4400, 4420, 4440, 4470, 4530, 4575, 4600, 4610, 4620, 4640, 4660, 4680, 4700, 4740, 4750, 4780, 4840, 4914, 4946 ] with open('./txts/sys_err_window.txt', 'w') as f_out: for ecm in ecms: out = str(ecm / 1000.) + '\t' + str(round(F_err * 100, 1)) + '\n' f_out.write(out) raw_input('Enter anything to end...')
def makeEoverEtrueAnalysis(inputfile, eta, et, iseeding, igathering, nevts, outputdir, doCBfit=False): gROOT.SetBatch(True) gROOT.ProcessLine('.L /work/mratti/CMS_style/tdrstyleGraph.C') gROOT.ProcessLine('setTDRStyle()') print '*******************************************' print 'Starting analysis for Eta={}, Et={}, seed thrs={}, gather thrs={}'.format( eta, et, iseeding, igathering) print 'inputfile={}'.format(inputfile) print '*******************************************' result = EoverEtrueAnalysisResult() if not os.path.isfile(inputfile): print 'ERROR: did not find inputfile', inputfile return False, result ################### # READ ################## #histoname = 'h_PFclusters_genMatched_eOverEtrue_Eta{eta}_Et{et}'.format(eta=eta, et=et) #histoname = 'h_superClusters_genMatched_eOverEtrue_Eta{eta}_Et{et}'.format(eta=eta, et=et) histonameFull = histoname + '_Eta{eta}_Et{et}'.format(eta=eta, et=et) inputdir = 'ecalnoisestudy' subdir = 'EtaEtBinnedQuantities' f = TFile(inputfile, 'READ') histo = f.Get('{}/{}/{}'.format(inputdir, subdir, histonameFull)) if not histo: print 'ERROR: did not find histogram', inputdir, subdir, histonameFull return False, result histo.SetMarkerStyle(20) histo.GetXaxis().SetTitle( 'E_{{PFcluster}} / E_{{True}} (GeV)'.format(eta=eta)) histo.GetYaxis().SetTitle('Entries') histo.GetXaxis().SetRangeUser(0, 2) #histo.GetYaxis().SetRangeUser(0,1500) if eta == "0p00_0p50" and et == "1_20": if '450ifb_nominal' in outputdir: histo.Rebin(2) #histo.GetYaxis().SetRangeUser(0., 1600) #if 'EE' in det: # histo.GetYaxis().SetRangeUser(0., 600) # better to avoid setting the range, since the mean calculation changes #histo.GetXaxis().SetRangeUser(xrange[0], xrange[1]) ################### # FIT ################## if doCBfit: # first fit a gaussian starting from reasonable parameters f0 = TF1('f1', 'gaus', 0.4, 2.) #f0.SetParameter(0, 200) f0.SetParameter(1, histo.GetMean()) f0.SetParameter(2, histo.GetRMS()) fitresult = histo.Fit(f0, 'SRM') mean = f0.GetParameter(1) sigma = f0.GetParameter(2) # refit to gaussian, just to make sure f0.SetParameter(1, mean) f0.SetParameter(2, sigma) f0.SetRange(mean - 3 * sigma, mean + 3 * sigma) fitresult = histo.Fit(f0, 'SRM') mean = f0.GetParameter(1) sigma = f0.GetParameter(2) # then restrict yourself to +/- 3 sigma and fit a crystal ball there f1 = TF1('f1', 'crystalball', 0.4, 2.) Nsigma = 4 if (eta == "1p48_2p00" and et != "1_20") or (eta == "2p50_3p00" and et == "40_60"): Nsigma = 3 f1.SetRange(mean - Nsigma * sigma, mean + Nsigma * sigma) f1.SetParameters( 200, 1, 0.05, 3, 2 ) # my guess: constant (normalization)=integral, mean = 1, sigma = 0.1, alpha (quanto lontano dal picco si innesta la coda) = 0.7, N = 0.5 (lunghezza della coda(?) f1.SetLineColor(kRed) fitresult = histo.Fit(f1, 'SRM') # fit it one more time, starting from fitted parameters f1.SetParameters(f1.GetParameters()) fitresult = histo.Fit(f1, 'SRM') # ... and one more time f1.SetParameters(f1.GetParameters()) fitresult = histo.Fit(f1, 'SRM') # ... and one more time f1.SetParameters(f1.GetParameters()) fitresult = histo.Fit(f1, 'SRM') else: # do one first fit on the full range f1 = TF1('f1', 'gaus', 0.4, 2.) f1.SetParameter(0, 200) f1.SetParameter(1, histo.GetMean()) f1.SetParameter(2, histo.GetRMS()) fitresult = histo.Fit(f1, 'SRM') # then set the initial parameters to the fit parameters and restrict to +/- 3 sigma mean = f1.GetParameter(1) sigma = f1.GetParameter(2) f1.SetParameter(1, mean) f1.SetParameter(2, sigma) f1.SetRange(mean - 3 * sigma, mean + 3 * sigma) fitresult = histo.Fit(f1, 'SRM') # then re-set the initial parameters to the fit parameters and restrict to +/- 2 sigma mean = f1.GetParameter(1) sigma = f1.GetParameter(2) f1.SetParameter(1, mean) f1.SetParameter(2, sigma) f1.SetRange(mean - 2 * sigma, mean + 2 * sigma) fitresult = histo.Fit(f1, 'SRM') # mean = f1.GetParameter(1) # sigma = f1.GetParameter(2) # f1.SetParameter(1, mean) # f1.SetParameter(2, sigma) # f1.SetRange(mean-2*sigma, mean+2*sigma) # fitresult = histo.Fit(f1, 'SRM') c = TCanvas() histo.Draw('PE') #fitresult = histo.Fit(f1, 'RS') f1.Draw('same') # save later ################### # Efficiency ################## hpass = TH1F('hpass', 'hpass', 1, 0., 1.) #Npass = histo.GetEntries() #Npass = histo.Integral(6,histo.FindLastBinAbove(0.)) # 0.2 cut in EoverEtrue Npass = histo.Integral(histo.FindBin(0.4), histo.FindBin(1.4)) # does it make sense to instead compute efficiency only in +-3 sigma fitted peak for i in range(0, int(Npass)): hpass.Fill(0.5) htot = TH1F('htot', 'htot', 1, 0., 1.) histonameFull = 'h_genP_nEvts_Eta{eta}_Et{Et}'.format(eta=eta, Et=et) h_genP = f.Get('{}/{}/{}'.format(inputdir, subdir, histonameFull)) Ntot = h_genP.GetEntries() for i in range(0, int(Ntot)): htot.Fill(0.5) print 'eff calculated from npass {} over ntot {}'.format( hpass.GetEntries(), htot.GetEntries()) if TEfficiency.CheckConsistency(hpass, htot): pEff = TEfficiency(hpass, htot) # default stat option is clopper pearson eff = pEff.GetEfficiency(1) erru = pEff.GetEfficiencyErrorUp(1) errd = pEff.GetEfficiencyErrorLow(1) else: eff = 1.0 erru = 1.0 errd = 1.0 eff_label = '{:.4f}+/-{:.4f}'.format(eff, erru) # erru and errd are the same #fout = open(det + '_' + outfile, 'a') #fout.write('Total efficiency for seeding={} gathering={}: {} \n'.format(iseeding,igathering,eff_label)) #fout.close() eff_label = 'N_{{reco}}/N_{{gen}}={}'.format(eff_label) defaultLabels([eff_label], x=0.62, y=0.65, spacing=0.04, size=0.06, dx=0.12) #sample_label = '#gamma#gamma, no tracker' sample_label = anaLabel et_label = 'Et=({},{})GeV'.format(et.split('_')[0], et.split('_')[1]) eta_label = 'Region=({},{})'.format(eta.split('_')[0], eta.split('_')[1]) defaultLabels([sample_label, et_label, eta_label], x=0.25, y=0.85, spacing=0.04, size=0.06, dx=0.12) ################### # RESULTS ################## c.SaveAs('{o}/EoverEtrue_Eta{eta}_Et{et}_s{s}_g{g}.pdf'.format( o=outputdir, eta=eta, s=iseeding, g=igathering, et=et)) c.SaveAs('{o}/EoverEtrue_Eta{eta}_Et{et}_s{s}_g{g}.png'.format( o=outputdir, eta=eta, s=iseeding, g=igathering, et=et)) return True, EoverEtrueAnalysisResult(eta=eta, et=et, eff=eff, erreff=erru, mean=f1.GetParameter(1), errmean=f1.GetParError(1), sigma=f1.GetParameter(2), errsigma=f1.GetParError(2), rms=histo.GetRMS(), errrms=histo.GetRMSError(), iseeding=iseeding, igathering=igathering)
def DoSimpleFit( histo, lumi, ZZtree, outputDir, title, fitMC, fitDATA ): #fitMC = true for fitting MC in FitMC.py, fitDATA = true for fitting data in FitDATA.py can = [] result = [] for i in range(0, len(histo)): canv = makeCMSCanvas( str(random.random()) + str(i), "Fit result " + str(i), 900, 700) can.append(canv) Z1_fitFunction = TF1(str(random.random()), DoubleCB(), 60., 120., 7) Z1_fitFunction.SetParLimits(0, 80., 100.) #mean Z1_fitFunction.SetParLimits(1, 0., 5.) #width Z1_fitFunction.SetParLimits(2, 0., 2.) #alpha1 Z1_fitFunction.SetParLimits(3, 0., 10.) #n1 Z1_fitFunction.SetParLimits(4, 0., 2.) #alpha2 Z1_fitFunction.SetParLimits(5, 0., 10.) #n2 # Z1_fitFunction.SetParLimits(6,0.,1000000.)#const Z1_fitFunction.SetParName(0, "Mean") #mean Z1_fitFunction.SetParName(1, "Sigma") #width Z1_fitFunction.SetParName(2, "#alpha_{1}") #alpha1 Z1_fitFunction.SetParName(3, "n_{1}") #n1 Z1_fitFunction.SetParName(4, "#alpha_{2}") #alpha2 Z1_fitFunction.SetParName(5, "n_{2}") #n2 Z1_fitFunction.SetParName(6, "C") #const for i in range(0, len(histo)): # print "***", histo[i].GetTitle(), lumi[i], title, histo[i].GetEntries(), "***" # define fit function if (fitMC): # fit function for fitting MC in FitMC.py Z1_fitFunction.SetParameters(91., 2.5, 1., 1., 1., 1., histo[i].Integral() / 5.) elif (fitDATA): # fit function for fitting DATA in FitDATA.py Z1_fitFunction.SetParameters(91., 2.5, 1., 1., 1., 1., histo[i].Integral() / 5.) else: if (ZZtree): Z1_fitFunction.SetParameters(91., 2.5, 1., 1., 1., 1., 10.) else: Z1_fitFunction.SetParameters(91., 2.5, 1., 1., 1., 1., histo[i].Integral() / 5.) # do the fit can[i].cd() histo[i].Fit(Z1_fitFunction) # do the fit histo[i].Draw("E") gStyle.SetOptFit() mass = Z1_fitFunction.GetParameters()[0] width = Z1_fitFunction.GetParameters()[1] mass_err = Z1_fitFunction.GetParError(0) width_err = Z1_fitFunction.GetParError(1) result.append(Result(mass, width, lumi[i], mass_err, width_err)) print("Mass: " + str(mass) + " Width: " + str(width)) printLumiPrelOut(can[i]) if (fitMC): can[i].SaveAs(str(outputDir) + "/" + str(title[i]) + "_fit.pdf") can[i].SaveAs(str(outputDir) + "/" + str(title[i]) + "_fit.png") elif (fitDATA): can[i].SaveAs(str(outputDir) + "/" + str(title[i]) + "_fit.pdf") can[i].SaveAs(str(outputDir) + "/" + str(title[i]) + "_fit.png") else: can[i].SaveAs( str(outputDir) + "/" + title + "_fit_" + str(i) + ".pdf") can[i].SaveAs( str(outputDir) + "/" + title + "_fit_" + str(i) + ".png") return result
def main(): gROOT.SetBatch(True) SetAtlasStyle() base_path = '../data/March_4/McAtNlo/UnfoldingMethodTest' output_eps_path = base_path + '/eps' base_filename = 'unfoldingMethodsTest_mc' systematic = 'nominal' toys = 5000 iterValue = 4 histogram_names = ['mc_truth_diffxs', 'data_unfolded_diffxs'] output_filename = base_path + '/unfoldingMethodsPlots' output_filename_ext = '.eps' can = TCanvas('can', 'can', 0, 0, 800, 600) can.SetMargin(0.2, 0.05, 0.15, 0.05) horizontalAt0 = TF1("horizontalAt0", "[0]+x*[1]", -100000, 100000) horizontalAt0.SetParameter(0, 0) horizontalAt0.SetParameter(1, 0) horizontalAt0.SetLineColor(kBlack) horizontalAt0.SetLineStyle(9) horizontalAt0.SetLineWidth(1) y_title = "#left(#frac{d#sigma}{dX}|_{unf} - #frac{d#sigma}{dX}|_{tru}#right)#times#left(#frac{d#sigma}{dX}|_{tru}#right)^{-1}" # load histograms for sampleName in sampleNames: x_title = '' latex_label = '' if sampleName is 'Tag1_SystemMass': x_title = 'M_{t#bar{t}} [GeV]' elif sampleName is 'Tag1_SystemPt': x_title = 'p_{T}^{t#bar{t}} [GeV]' elif sampleName is 'Tag1_Top1_lhood': x_title = 'leptonic top p_{T} [GeV]' elif sampleName is 'Tag1_Top2_lhood': x_title = 'hadronic top p_{T} [GeV]' for channel in channels: diffxs = {} truth = {} ratios = {} gratios = {} for half in halves: # create canvas and legend can.cd() legA = TLegend(0.23, 0.93, 0.53, 0.75) legA.SetBorderSize(0) legA.SetFillStyle(0) legB = TLegend(0.53, 0.93, 0.83, 0.75) legB.SetBorderSize(0) legB.SetFillStyle(0) # loop over methods and get histograms diffxs[half] = {} truth[half] = {} ratios[half] = {} gratios[half] = {} for unfoldingMethod in unfoldingMethods: # get the method value methodValue = -1 if unfoldingMethod == SVD: methodValue = regValues[sampleName] elif unfoldingMethod == Bayesian: methodValue = iterValue # open file with histograms in_filename = base_path + '/' + get_input_filename( systematic, sampleName, channel, unfoldingMethod, half, toys, methodValue) + '.root' in_file = TFile(in_filename) if not in_file.IsOpen(): print 'ERROR opening file', in_filename return # retrieve histograms histoname_base = get_histoname_base( systematic, sampleName, channel, unfoldingMethod, half, toys, methodValue) # get truth histoname = histoname_base + '_mc_truth_diffxs' histo = in_file.Get(histoname) if not histo: print 'ERROR retrieving histogram,\n', histoname, ',\n from file,\n', in_filename return histo.SetDirectory(0) histo.SetName(histoname_base + '_' + unfoldingMethod + '_mc_truth_diffxs') truth[half][unfoldingMethod] = histo # get unfolded distribution histoname = histoname_base + '_data_unfolded_diffxs' histo = in_file.Get(histoname) if not histo: print 'ERROR retrieving histogram,\n', histoname, ',\n from file,\n', in_filename return histo.SetDirectory(0) histo.SetName(histoname_base + '_' + unfoldingMethod + '_data_unfolded_diffxs') diffxs[half][unfoldingMethod] = histo in_file.Close() # end unfoldingMethods # end halves for half in halves: for unfoldingMethod in unfoldingMethods: # calculate ratio of unfolded-truth over truth ratio = GetRatioPlot( diffxs[half][unfoldingMethod], truth[oppositeHalves[ halves.index(half)]][unfoldingMethod]) histoname_base = get_histoname_base( systematic, sampleName, channel, unfoldingMethod, half, toys, methodValue) ratio.SetName(histoname_base + '_' + unfoldingMethod + '_ratio') ratio.SetDirectory(0) ratios[half][unfoldingMethod] = ratio axis_length = ratio.GetXaxis().GetXmax() - ratio.GetXaxis( ).GetXmin() offset = (unfoldingMethods.index(unfoldingMethod) - 1.5) * 0.005 * axis_length gratio = GetTGraphAsymmErrors(ratio, offset) # plot ratio gratio.SetMarkerColor( unfoldingMethods.index(unfoldingMethod) + 1) gratio.SetMarkerStyle( unfoldingMethods.index(unfoldingMethod) + 21) gratio.SetLineColor( unfoldingMethods.index(unfoldingMethod) + 1) gratio.SetLineWidth(2) # if this is the first method, need to set proper axis parameters if unfoldingMethods.index(unfoldingMethod) == 0: if sampleName is LeptonicTop: gratio.SetMaximum(0.11) gratio.SetMinimum(-0.09) elif sampleName is HadronicTop: gratio.SetMaximum(0.08) gratio.SetMinimum(-0.1) elif sampleName is SystemMass: gratio.SetMaximum(0.1) gratio.SetMinimum(-0.08) elif sampleName is SystemPt: gratio.SetMaximum(0.15) gratio.SetMinimum(-0.3) elif sampleName is SystemRapidity: gratio.SetMaximum(0.07) gratio.SetMinimum(-0.05) gratio.GetXaxis().SetTitle(x_title) gratio.GetYaxis().SetTitle(y_title) gratio.GetYaxis().SetTitleOffset(1.6) gratio.Draw('ap') else: gratio.Draw('p') # add to legend if unfoldingMethods.index(unfoldingMethod) >= 2: legB.AddEntry(gratio, unfoldingMethod, 'pl') else: legA.AddEntry(gratio, unfoldingMethod, 'pl') gratios[half][unfoldingMethod] = gratio horizontalAt0.Draw('same') legA.Draw('same') legB.Draw('same') text = TPaveText(0.2, 0.25, 0.4, 0.18, "NDC") text.SetFillStyle(0) text.SetBorderSize(0) text.AddText(half + ', ' + channel) # text.Draw('same') can.SaveAs(output_filename + '_' + channel + '_' + half + '_' + sampleName + output_filename_ext)
all_graphs = [] graphTitles = [] avgSF = [] avgSFerr = [] colour = ['#4169E1','#D2691E','#228B22','#DC143C','#696969','#9932CC','#D2B48C', 1, 2, 3, 4, 5, 6, 7, 8, 9,10] colour = [TColor.GetColor(c) for c in colour] # first get all the resolutions and prepare graphs for ifile, filename in enumerate(calo_init.filenamesIn): energy = calo_init.energy(ifile) f = TFile(filename, "READ") # mean value of the sampling fraction hMean = f.Get(histNameMean) if hMean: fitPre = TF1("fitPre","gaus", hMean.GetMean() - 1. * hMean.GetRMS(), hMean.GetMean() + 1. * hMean.GetRMS()) resultPre = hMean.Fit(fitPre, "SQRN") fit = TF1("fit","gaus",resultPre.Get().Parameter(1) - 2. * resultPre.Get().Parameter(2), resultPre.Get().Parameter(1) + 2. * resultPre.Get().Parameter(2) ) result = hMean.Fit(fit, "SQRN") avgSF.append(result.Get().Parameter(1)) avgSFerr.append(result.Get().Parameter(2)) hmerged = [] # first merge adjacent layers and get histograms of SF for islice in range(startIndex, Nslices + startIndex): h = TH1F() h = f.Get(histName+str(islice)) # if first hist to be merged lastIm = -1 if islice - startIndex in merge: lastIm += 1 hmerged.append(h)
xmin_DDPIPI, xmax_DDPIPI = 4.0205, 4.9985 def func_DDPIPI(x, par): ''' function for correlated breit wigner: e+e- --> DDpipi ''' xx = x[0] return par[0] * pow(xx, -2) * TMath.Exp( -1 * par[1] * (xx - 4.015)) + par[2] * TMath.Gaus(xx, par[3], par[4]) # initial parameters of fit functions par_D1_2420 = array('d', [1.0, 0.1, 0.1, 1.0]) par_psipp = array('d', [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) par_DDPIPI = array('d', [1.0, -1.0, 0., 4.74, 0.05]) # of TF1 fit functions tfunc_D1_2420 = TF1('tfunc_D1_2420', func_D1_2420, xmin_D1_2420, xmax_D1_2420, len(par_D1_2420)) tfunc_psipp = TF1('tfunc_psipp', func_psipp, xmin_psipp, xmax_psipp, len(par_psipp)) tfunc_DDPIPI = TF1('tfunc_DDPIPI', func_DDPIPI, xmin_DDPIPI, xmax_DDPIPI, len(par_DDPIPI)) # necessary list xmin_list = [xmin_D1_2420, xmin_psipp, xmin_DDPIPI] xmax_list = [xmax_D1_2420, xmax_psipp, xmax_DDPIPI] tfunc_list = [tfunc_D1_2420, tfunc_psipp, tfunc_DDPIPI] ''' estimate systematic uncertainty caused by line-shape ''' def CAL(): sampling(label_list, iter_old, Nrand)
def main(): gStyle.SetOptStat(0) BIAS_DIR = global_paths.BIASDIR + args.btagging + "/" if args.year == 'run2c': BIAS_DIR += "combined_run2_r{}{}/" ## individual plots stored in run2c_masspoints ## extract pulls pulls = {} for signal_strength in ['0', '2sigma', '5sigma']: print print print "--------------------------------------------------" print "r = " + signal_strength print "--------------------------------------------------" pulls[signal_strength] = TGraphErrors() for m in range(1600, 8001, 100): if (signal_strength == '2sigma' and m < 2600) or (signal_strength == '5sigma' and m < 4100): ##FIXME FIXME datacard_correction = True else: datacard_correction = False print print "m = " + str(m) if datacard_correction: print "correcting signal strength in the datacard" print pull0 = int(SIGNAL_STRENGTH[signal_strength][m]) tree = TChain("tree_fit_sb") for seed in [ '123456', '234567', '345678', '456789', '567891', '678912', '789123', '891234', '912345', '123459' ]: tree.Add( BIAS_DIR.format(signal_strength, "_lowm" if datacard_correction else "") + "fitDiagnostics_M{mass}_{seed}.root".format( mass=m, seed=seed)) ##FIXME FIXME hist = TH1D("s_pulls", ";%s/#sigma_{r};Number of toys" % ("#Deltar"), 25, -5, +5) # for i in range(tree.GetEntries()): if hist.GetEntries() >= 1000: continue tree.GetEntry(i) #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr) ##if tree.rLoErr < 0.: continue if abs(tree.r + 1.) < 0.001: continue if abs(tree.r - 1.) < 0.001: continue if abs(tree.r - 0.) < 0.001: continue if tree.rHiErr == 0. or tree.rLoErr == 0.: continue if abs(tree.r + abs(tree.rHiErr) - round(tree.r + abs(tree.rHiErr))) < 0.0001: continue if abs(tree.r - abs(tree.rLoErr) - round(tree.r - abs(tree.rLoErr))) < 0.0001: continue #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr) pull = (tree.r - pull0) / abs( tree.rHiErr) if tree.r - pull0 > 0. else ( tree.r - pull0) / abs(tree.rLoErr) ## my own approach hist.Fill(pull) ## individual plots for checking the fit quality c1 = TCanvas("c1", "Pulls", 600, 600) c1.cd() hist.GetXaxis().SetTitleSize(0.045) hist.GetYaxis().SetTitleSize(0.045) hist.GetYaxis().SetTitleOffset(1.1) hist.GetXaxis().SetTitleOffset(1.05) hist.GetXaxis().SetLimits(-6, 6.) hist.GetYaxis().SetLimits(0, 200.) hist.SetMinimum(0.) hist.SetMaximum(190.) c1.SetTopMargin(0.05) ##print "@ m= {}: \t mean = {}".format(m, hist.GetMean()) #pulls[signal_strength].SetPoint(pulls[signal_strength].GetN(), m, hist.GetMean()) ## get actual mean of histogram fit_func = TF1("gaussfit", "gaus", -3., 3.) hist.Fit(fit_func, "E") hist.Draw() drawCMS(-1, "Simulation Preliminary", year='run2') drawMass("m_{Z'} = " + str(m) + " GeV") c1.Print("plots/bias/run2c_masspoints/r" + signal_strength + "/bias_fit_" + str(m) + "_" + args.year + ".pdf") c1.Print("plots/bias/run2c_masspoints/r" + signal_strength + "/bias_fit_" + str(m) + "_" + args.year + ".png") n = pulls[signal_strength].GetN() pulls[signal_strength].SetPoint( n, m, fit_func.GetParameter(1)) ## get fitted gaussian mean pulls[signal_strength].SetPointError( n, 0., fit_func.GetParError(1)) ## set gaussian width as error fit_func.Delete() hist.Delete() c1.Delete() #except: # print "something went wrong in m =", m ## draw pulls outfile = TFile("plots/bias/bias_study_new_" + args.year + ".root", "RECREATE") c = TCanvas("canvas", "canvas", 800, 600) leg = TLegend(0.65, 0.7, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) for i, signal_strength in enumerate(['0', '2sigma', '5sigma']): pulls[signal_strength].SetMarkerStyle(2) pulls[signal_strength].SetMarkerColor(COLORS[signal_strength]) pulls[signal_strength].SetLineColor(COLORS[signal_strength]) pulls[signal_strength].SetLineWidth(2) pulls[signal_strength].SetMinimum(-0.7) pulls[signal_strength].SetMaximum(0.7) pulls[signal_strength].Draw("APL" if i == 0 else "PL") leg.AddEntry(pulls[signal_strength], LEGEND[signal_strength]) zeroline = TGraph() zeroline.SetPoint(zeroline.GetN(), 1000, 0) zeroline.SetPoint(zeroline.GetN(), 8600, 0) zeroline.SetMarkerStyle(7) zeroline.SetMarkerSize(0) zeroline.SetLineStyle(15) zeroline.SetLineColor(1) zeroline.Draw("PL") c.SetGrid() pulls['0'].SetTitle(";m_{Z'} (GeV);mean #Deltar/#sigma_{r}") pulls['0'].GetXaxis().SetTitleSize(0.045) pulls['0'].GetYaxis().SetTitleSize(0.045) pulls['0'].GetYaxis().SetTitleOffset(1.1) pulls['0'].GetXaxis().SetTitleOffset(1.05) pulls['0'].GetXaxis().SetLimits(1350., 8150.) c.SetTopMargin(0.05) leg.Draw() drawCMS(-1, "Simulation Preliminary", year='run2') c.Print("plots/bias/bias_study_new_" + args.year + ".png") c.Print("plots/bias/bias_study_new_" + args.year + ".pdf") c.Write() outfile.Close()
df_dbar_sig = df_dbar[df_dbar["ismcsignal"] == 1] # only not d signal df_dbar_fake = df_dbar[df_dbar["ismcsignal"] == 0] # only not d background if (reduced_data): rd_d_sig = int(df_d_sig.shape[0] / 4) rd_d_fake = int(df_d_fake.shape[0] / 4) rd_nd_sig = int(df_dbar_sig.shape[0] / 4) rd_nd_fake = int(df_dbar_fake.shape[0] / 4) print(df_d_sig.shape, rd_d_sig, rd_d_fake, rd_nd_sig, rd_nd_fake) df_d_sig = df_d_sig[:rd_d_sig] # only d signal # df_d_fake = df_d_fake[:rd_d_fake] # only d background df_dbar_sig = df_dbar_sig[:rd_nd_sig] # only not d signal # df_dbar_fake = df_dbar_fake[:rd_nd_fake] # only not d background cYields = TCanvas('cYields', 'The Fit Canvas') fit_fun1 = TF1("fit_fun_1", "gaus", 1.64, 2.1) h_invmass_dsig = TH1F("invariant mass", "", binning, df_d_sig.inv_mass.min(), df_d_sig.inv_mass.max()) fill_hist(h_invmass_dsig, df_d_sig.inv_mass) h_invmass_dsig.Fit(fit_fun1) par1 = fit_fun1.GetParameters() h_invmass_dsig.Draw() cYields.SaveAs("h_invmass_dsig.png") fit_fun2 = TF1("fit_fun2", "pol2", 1.82, 1.92) h_invmass_dbkg = TH1F("invariant mass", "", binning, df_d_fake.inv_mass.min(), df_d_fake.inv_mass.max()) fill_hist(h_invmass_dbkg, df_d_fake.inv_mass) h_invmass_dbkg.Fit(fit_fun2) par2 = fit_fun2.GetParameters() h_invmass_dbkg.Draw()
def makeEoverEtrueAnalysis(inputfile, det, et, iseeding, igathering, nevts, outputdir): print '*******************************************' print 'Starting analysis for det={}, Et={}, seed thrs={}, gather thrs={}'.format( det, et, iseeding, igathering) print 'inputfile={}'.format(inputfile) print '*******************************************' result = EoverEtrueAnalysisResult() if not os.path.isfile(inputfile): return False, result ################### # READ ################## histoname = 'h_PFclusters_genMatched_{det}_eOverEtrue_{Et}'.format(det=det, Et=et) inputdir = 'ecalnoisestudy' subdir = 'EtBinnedQuantities' f = TFile(inputfile, 'READ') histo = f.Get('{}/{}/{}'.format(inputdir, subdir, histoname)) if not histo: return False, result histo.SetMarkerStyle(20) histo.GetXaxis().SetTitle( 'E_{{PFcluster}} / E_{{True}} (GeV)'.format(det=det)) histo.GetYaxis().SetTitle('Entries') histo.GetXaxis().SetRangeUser(0, 2) if det == 'EB': histo.GetYaxis().SetRangeUser(0, 500) else: histo.GetYaxis().SetRangeUser(0, 150) histo.Rebin(2) #histo.GetYaxis().SetRangeUser(0., 1600) #if 'EE' in det: # histo.GetYaxis().SetRangeUser(0., 600) # better to avoid setting the range, since the mean calculation changes #histo.GetXaxis().SetRangeUser(xrange[0], xrange[1]) ################### # FIT ################## #f1 = TF1('f1','crystalball',0.4, 2.) #f1.SetParameters(200, 1, 0.05, 3, 2) # my guess: constant (normalization)=integral, mean = 1, sigma = 0.1, alpha (quanto lontano dal picco si innesta la coda) = 0.7, N = 0.5 (lunghezza della coda(?) #f1.SetLineColor(kRed) f1 = TF1('f1', 'gaus', 0.4, 2.) f1.SetParameter(0, 200) f1.SetParameter(1, histo.GetMean()) f1.SetParameter(2, histo.GetRMS()) # do one first fit on the full range fitresult = histo.Fit(f1, 'RM') # L for loglikelihood , mean = f1.GetParameter(1) sigma = f1.GetParameter(2) f1.SetParameter(1, mean) f1.SetParameter(2, sigma) f1.SetRange(mean - 3 * sigma, mean + 3 * sigma) fitresult = histo.Fit(f1, 'SRM') c = TCanvas() histo.Draw('PE') #fitresult = histo.Fit(f1, 'RS') f1.Draw('same') # save later #fo.cd() #fitresult.Write() #fo.Close() # Get the fitted function parameters and write them to txt file #fit_params = [ ('Param {}'.format(i),'{:.2f}'.format(f1.GetParameter(i)), '{:.2f}'.format(f1.GetParError(i)) ) for i in range(0,5)] #ffitout = open(det + '_' + fitoutfile , 'a') #ffitout.write('\n\nFit results for seeding={} gathering={} subdet={}:\n'.format(iseeding, igathering, det)) #ffitout.write('\nChi2/Ndf=' + str(f1.GetChisquare()) + '/' + str(f1.GetNDF()) + '\n') #par_string = '\n'.join("%s: val=%s err=%s" % tup for tup in fit_params) #ffitout.write(par_string) ################### # Efficiency ################## hpass = TH1F('hpass', 'hpass', 1, 0., 1.) #Npass = histo.GetEntries() # compute efficiency only in +-3 sigma fitted peak Npass = histo.Integral(6, histo.FindLastBinAbove(0.)) # 0.2 cut in EoverEtrue for i in range(0, int(Npass)): hpass.Fill(0.5) #htot = f.Get('{}/{}/{}'.format(inputdir,'general', 'h_genP_pt_{d}'.format(d=det))) htot = TH1F('htot', 'htot', 1, 0., 1.) histoname = 'h_genP_{det}_nEvts_{Et}'.format(det=det, Et=et) h_genP = f.Get('{}/{}/{}'.format(inputdir, subdir, histoname)) Ntot = h_genP.GetEntries() for i in range(0, int(Ntot)): htot.Fill(0.5) print 'eff calculated from npass {} over ntot {}'.format( hpass.GetEntries(), htot.GetEntries()) if TEfficiency.CheckConsistency(hpass, htot): pEff = TEfficiency(hpass, htot) # default stat option is clopper pearson eff = pEff.GetEfficiency(1) erru = pEff.GetEfficiencyErrorUp(1) errd = pEff.GetEfficiencyErrorLow(1) else: eff = 1.0 erru = 1.0 errd = 1.0 eff_label = '{:.4f}+/-{:.4f}'.format(eff, erru) # erru and errd are the same #fout = open(det + '_' + outfile, 'a') #fout.write('Total efficiency for seeding={} gathering={}: {} \n'.format(iseeding,igathering,eff_label)) #fout.close() eff_label = 'N_{{reco}}/N_{{gen}}={}'.format(eff_label) defaultLabels([eff_label], x=0.62, y=0.65, spacing=0.04, size=0.06, dx=0.12) sample_label = '#gamma#gamma, no tracker' et_label = 'Et=({},{})GeV'.format(et.split('_')[0], et.split('_')[1]) det_label = 'Region={}'.format(det) defaultLabels([sample_label, et_label, det_label], x=0.25, y=0.85, spacing=0.04, size=0.06, dx=0.12) ################### # RESULTS ################## c.SaveAs('{o}/EoverEtrue_{det}_Et{et}_seed{s}_gather{g}.pdf'.format( o=outputdir, det=det, s=iseeding, g=igathering, et=et)) c.SaveAs('{o}/EoverEtrue_{det}_Et{et}_seed{s}_gather{g}.png'.format( o=outputdir, det=det, s=iseeding, g=igathering, et=et)) return True, EoverEtrueAnalysisResult(det=det, et=et, eff=eff, erreff=erru, mean=f1.GetParameter(1), errmean=f1.GetParError(1), sigma=f1.GetParameter(2), errsigma=f1.GetParError(2), rms=histo.GetRMS(), errrms=histo.GetRMSError(), iseeding=iseeding, igathering=igathering)
def poissonFitfunc(): funcformulas = [] for ipeak in range(0,5): funcformulas.append("[0]*(TMath::Gaus(x,[1]+{0}*[2],[2]*[3],1)*TMath::Poisson({0},[4]) )".format(ipeak)) return TF1("poisson_fitfunc"," + ".join(funcformulas))
from draw_functions import draw_1histogram, draw_2histograms ENERGY = 50 SF=5.4 filename="../../FCCSW/output_ecalSim_e"+str(ENERGY)+"GeV_eta0_10events.root" #filename="root://eospublic.cern.ch//eos/fcc/users/n/novaj/newgeometry_4nov/output_e"+str(ENERGY)+"GeV_bfield0_part1_Lar4mm_Pb2mm_tracker_v2.root" print "Processing file ",filename ma = CaloAnalysis_profiles(SF, ENERGY) ma.loop(filename) print "Mean hit energy: ", ma.histClass.h_hitEnergy.GetMean() print "1/SF calculated: ", ENERGY/(ma.histClass.h_hitEnergy.GetMean()) #Longo-Sestili formula #http://arxiv.org/pdf/hep-ex/0001020.pdf fit = TF1("fit","[0]*(pow([2]*x,[1]-1)*[2]*exp(-[2]*(x))/TMath::Gamma([1]))") fit.SetParName(0,"A") #normalization factor fit.SetParName(1,"#alpha") fit.SetParName(2,"#beta") gStyle.SetOptStat("emr"); c1 = TCanvas("c1","c1",1000,1000) c1.Divide(3,2) c1.cd(1) draw_1histogram(ma.histClass.h_ptGen, "p_{T}^{gen} [GeV]","") c1.cd(2) draw_1histogram(ma.histClass.h_pdgGen, "PDG code","") c1.cd(4) ma.histClass.h_cellEnergy.Rebin(2) draw_1histogram(ma.histClass.h_cellEnergy, "Total cell energy [GeV]","")
reader = csv.reader(f) reader.next() for row in reader: for (i, v) in enumerate(row): if i == 0: varx = float(v) varx = varx * 10**6 if i == 1: vary = float(v) vary = vary h1f.Fill(varx, vary) columns[i].append(v) par = array('d', 3 * [0.]) g1 = TF1('g1', 'gaus', -10, 10) g1.SetLineColor(2) h1f.Fit(g1, 'R+') par1 = g1.GetParameters() norm = str(par1[0]) mean = str(par1[1]) rms = str(par1[2]) print(File[-24:-23], File[-22:-21], par1[0], par1[1], par1[2]) for ch_data_f in channels: if ch_data_f.lower() in File.lower(): with open(ch_data_f + "_data.txt", "a") as channel_data: channel_data.write(File[-24:-23]) channel_data.write(".") channel_data.write(File[-22:-21]) channel_data.write(",") channel_data.write(norm)
ey = array('d') x.fromlist(list(np.array(data[1]))) y.fromlist(list(np.array(data[4]))) ex.fromlist(list(np.array(data[3]))) ey.fromlist(list(np.array(data[5]))) c1 = TCanvas('c1', 'A Simple Graph with error bars', 200, 10, 700, 500) c1.SetGrid() c1.GetFrame().SetFillColor( 21 ) c1.GetFrame().SetBorderSize( 12 ) gr = TGraphErrors( len(x), x, y, ex, ey ) ff = TF1('ff', 'pol1', -1, 2) # ff.SetParameters( 7.6e+02, -3.7, 1.e-01) fit = gr.Fit(ff,'srf') print(fit.Ndf()) print(fit.Chi2()) gr.SetTitle( 'Calibration' ) gr.SetMarkerColor( 4 ) gr.SetMarkerStyle( 20 ) gr.GetXaxis().SetTitle( '#omega, 10^{15} 1/s' ) gr.GetYaxis().SetTitle( 'V_{0}, V' ) gr.Draw( 'ap' ) # ff.Draw()
def Fitting(scalestring, Fit_id): list_scale = scalestring.split(",") # Set up canvas, remove titles and stats boxes gStyle.SetOptTitle(0) gStyle.SetOptStat(0) c = TCanvas("c", "c", 1600, 800) # Legend mylegend = TLegend(1.0, 0.3, 0.75, 1.0, "Legend") mylegend.SetTextSize(0.04) dict_scale_hist = {} dict_gaus_fit = {} dict_bukin_fit = {} colorcounter = 1 for scale in list_scale: histname = "Higgs_" + scale + "_M" dict_scale_hist[scale] = file.Get(histname) # If error here, check Bukin.py has: import math dict_gaus_fit[scale] = TF1( "Gauss", Gauss(), dict_scale_hist[scale].GetMean() - 3 * dict_scale_hist[scale].GetRMS(), dict_scale_hist[scale].GetMean() + 3 * dict_scale_hist[scale].GetRMS(), 3) dict_bukin_fit[scale] = TF1( "Bukin", Bukin(), dict_scale_hist[scale].GetMean() - 3 * dict_scale_hist[scale].GetRMS(), dict_scale_hist[scale].GetMean() + 3 * dict_scale_hist[scale].GetRMS(), 6) for scale in list_scale: if Fit_id == 1: print print "The ROOT Gaussian fit produces: " dict_scale_hist[scale].Fit("gaus", "0 +") # zero option to not draw print print "The user defined Gaussian fit produces: " dict_gaus_fit[scale].SetParName(0, "User_Constant") dict_gaus_fit[scale].SetParName(1, "User_Mean") dict_gaus_fit[scale].SetParName(2, "User_Sigma") dict_gaus_fit[scale].SetLineColor(colorcounter) dict_gaus_fit[scale].SetParameters( 100, dict_scale_hist[scale].GetMean(), dict_scale_hist[scale].GetRMS()) dict_scale_hist[scale].Fit(dict_gaus_fit[scale], "+ R") # + option to not delete previous fit # Add legend entry for Gaussian mylegend.AddEntry(dict_gaus_fit[scale], scale + "_Gauss", "l") elif Fit_id == 2: print print "The Bukin fit produces: " dict_bukin_fit[scale].SetParameters( 0, dict_scale_hist[scale].GetMean(), dict_scale_hist[scale].GetRMS(), 0, 0, 0) dict_bukin_fit[scale].SetLineColor(colorcounter) dict_scale_hist[scale].Fit(dict_bukin_fit[scale], "+ R") # Add legend entry mylegend.AddEntry(dict_bukin_fit[scale], scale + "_Bukin", "l") colorcounter += 1 for scale in list_scale: dict_scale_hist[scale].Draw( "func same") # using "func" here only plots fn for last fit #Set Canvas Title pave = TPaveText(0.00, 0.9, 0.3, 1.0, "tblrNDC") pave.SetTextColor(1) pave.SetTextSize(0.05) pave.AddText("Histogram Fits") pave.Draw("same") # Draw legend mylegend.Draw("same") c.Print("output/fitted.pdf")
def signal(category): interPar = True n = len(genPoints) cColor = color[category] if category in color else 4 nBtag = category.count('b') isAH = False #relict from using Alberto's more complex script if not os.path.exists(PLOTDIR+"MC_signal_"+YEAR): os.makedirs(PLOTDIR+"MC_signal_"+YEAR) #*******************************************************# # # # Variables and selections # # # #*******************************************************# X_mass = RooRealVar ( "jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV") weight = RooRealVar( "MANtag_weight", "", -1.e9, 1.e9 ) # Define the RooArgSet which will include all the variables defined before # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add' variables = RooArgSet(X_mass) variables.add(RooArgSet(weight)) X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax()) X_mass.setRange("X_integration_range", X_mass.getMin(), X_mass.getMax()) if VARBINS: binsXmass = RooBinning(len(abins)-1, abins) X_mass.setBinning(binsXmass) plot_binning = RooBinning(int((X_mass.getMax()-X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax()) else: X_mass.setBins(int((X_mass.getMax()-X_mass.getMin())/10)) binsXmass = RooBinning(int((X_mass.getMax()-X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax()) plot_binning = binsXmass X_mass.setBinning(plot_binning, "PLOT") massArg = RooArgSet(X_mass) SRcut = "" #*******************************************************# # # # Signal fits # # # #*******************************************************# treeSign = {} setSignal = {} vmean = {} vsigma = {} valpha1 = {} vslope1 = {} valpha2 = {} vslope2 = {} smean = {} ssigma = {} salpha1 = {} sslope1 = {} salpha2 = {} sslope2 = {} sbrwig = {} signal = {} signalExt = {} signalYield = {} signalIntegral = {} signalNorm = {} signalXS = {} frSignal = {} frSignal1 = {} frSignal2 = {} frSignal3 = {} # Signal shape uncertainties (common amongst all mass points) xmean_jes = RooRealVar("CMS"+YEAR+"_sig_"+category+"_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.02, -1., 1.) #0.001 smean_jes = RooRealVar("CMS"+YEAR+"_sig_"+category+"_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10) xsigma_jer = RooRealVar("CMS"+YEAR+"_sig_"+category+"_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.10, -1., 1.) ssigma_jer = RooRealVar("CMS"+YEAR+"_sig_"+category+"_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10) xmean_jes.setConstant(True) smean_jes.setConstant(True) xsigma_jer.setConstant(True) ssigma_jer.setConstant(True) for m in massPoints: signalMass = "%s_M%d" % (stype, m) signalName = "ZpBB_{}_{}_M{}".format(YEAR, category, m) sampleName = "ZpBB_M{}".format(m) signalColor = sample[sampleName]['linecolor'] if signalName in sample else 1 # define the signal PDF vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.96, m*1.05) smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)", RooArgList(vmean[m], xmean_jes, smean_jes)) vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.0222, m*0.020, m*0.023) ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)", RooArgList(vsigma[m], xsigma_jer, ssigma_jer)) valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha 1", 0.2, 0.05, 0.28) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0", RooArgList(valpha1[m])) #vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 0.1, 20.) # slope of the power tail vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 2., 15.) # slope of the power tail sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0", RooArgList(vslope1[m])) valpha2[m] = RooRealVar(signalName + "_valpha2", "Crystal Ball alpha 2", 1.) valpha2[m].setConstant(True) salpha2[m] = RooFormulaVar(signalName + "_alpha2", "@0", RooArgList(valpha2[m])) #vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", 6., 2.5, 15.) # slope of the higher power tail ## FIXME test FIXME vslope2_estimation = -5.88111436852 + m*0.00728809389442 + m*m*(-1.65059568762e-06) + m*m*m*(1.25128996309e-10) vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", vslope2_estimation, vslope2_estimation*0.9, vslope2_estimation*1.1) # slope of the higher power tail ## FIXME end FIXME sslope2[m] = RooFormulaVar(signalName + "_slope2", "@0", RooArgList(vslope2[m])) # slope of the higher power tail signal[m] = RooDoubleCrystalBall(signalName, "m_{%s'} = %d GeV" % ('X', m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m], salpha2[m], sslope2[m]) # extend the PDF with the yield to perform an extended likelihood fit signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 50, 0., 1.e15) signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e15) signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e15) signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m]) # ---------- if there is no simulated signal, skip this mass point ---------- if m in genPoints: if VERBOSE: print " - Mass point", m # define the dataset for the signal applying the SR cuts treeSign[m] = TChain("tree") if YEAR=='run2': pd = sample[sampleName]['files'] if len(pd)>3: print "multiple files given than years for a single masspoint:",pd sys.exit() for ss in pd: if not '2016' in ss and not '2017' in ss and not '2018' in ss: print "unknown year given in:", ss sys.exit() else: pd = [x for x in sample[sampleName]['files'] if YEAR in x] if len(pd)>1: print "multiple files given for a single masspoint/year:",pd sys.exit() for ss in pd: if os.path.exists(NTUPLEDIR + ss + "_"+BTAGGING+ ".root"): treeSign[m].Add(NTUPLEDIR + ss + "_"+BTAGGING+ ".root") else: print "found no file for sample:", ss if treeSign[m].GetEntries() <= 0.: print " - 0 events available for mass", m, "skipping mass point..." signalNorm[m].setVal(-1) vmean[m].setConstant(True) vsigma[m].setConstant(True) salpha1[m].setConstant(True) sslope1[m].setConstant(True) salpha2[m].setConstant(True) sslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) continue setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m])) if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded" # FIT entries = setSignal[m].sumEntries() if entries < 0. or entries != entries: entries = 0 signalYield[m].setVal(entries) # Instead of eventWeightLumi #signalYield[m].setVal(entries * LUMI / (300000 if YEAR=='run2' else 100000) ) if treeSign[m].GetEntries(SRcut) > 5: if VERBOSE: print " - Running fit" frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1)) if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80 if VERBOSE: frSignal[m].correlationMatrix().Print() drawPlot(signalMass+"_"+category, stype+category, X_mass, signal[m], setSignal[m], frSignal[m]) else: print " WARNING: signal", stype, "and mass point", m, "in category", category, "has 0 entries or does not exist" # Remove HVT cross sections #xs = getCrossSection(stype, channel, m) xs = 1. signalXS[m].setVal(xs * 1000.) signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range")) boundaryFactor = signalIntegral[m].getVal() if boundaryFactor < 0. or boundaryFactor != boundaryFactor: boundaryFactor = 0 if VERBOSE: print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events" signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br = 1 [fb] vmean[m].setConstant(True) vsigma[m].setConstant(True) valpha1[m].setConstant(True) vslope1[m].setConstant(True) valpha2[m].setConstant(True) vslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) #*******************************************************# # # # Signal interpolation # # # #*******************************************************# # ====== CONTROL PLOT ====== c_signal = TCanvas("c_signal", "c_signal", 800, 600) c_signal.cd() frame_signal = X_mass.frame() for j, m in enumerate(genPoints): if m in signalExt.keys(): #print "color:",(j%9)+1 #print "signalNorm[m].getVal() =", signalNorm[m].getVal() #print "RooAbsReal.NumEvent =", RooAbsReal.NumEvent signal[m].plotOn(frame_signal, RooFit.LineColor((j%9)+1), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range")) frame_signal.GetXaxis().SetRangeUser(0, 10000) frame_signal.Draw() #drawCMS(-1, "Simulation Preliminary", year=YEAR) drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) drawAnalysis(category) drawRegion(category) c_signal.SaveAs(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_Signal.pdf") c_signal.SaveAs(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_Signal.png") #if VERBOSE: raw_input("Press Enter to continue...") # ====== CONTROL PLOT ====== # Normalization gnorm = TGraphErrors() gnorm.SetTitle(";m_{X} (GeV);integral (GeV)") gnorm.SetMarkerStyle(20) gnorm.SetMarkerColor(1) gnorm.SetMaximum(0) inorm = TGraphErrors() inorm.SetMarkerStyle(24) fnorm = TF1("fnorm", "pol9", 700, 3000) fnorm.SetLineColor(920) fnorm.SetLineStyle(7) fnorm.SetFillColor(2) fnorm.SetLineColor(cColor) # Mean gmean = TGraphErrors() gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)") gmean.SetMarkerStyle(20) gmean.SetMarkerColor(cColor) gmean.SetLineColor(cColor) imean = TGraphErrors() imean.SetMarkerStyle(24) fmean = TF1("fmean", "pol1", 0, 10000) fmean.SetLineColor(2) fmean.SetFillColor(2) # Width gsigma = TGraphErrors() gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)") gsigma.SetMarkerStyle(20) gsigma.SetMarkerColor(cColor) gsigma.SetLineColor(cColor) isigma = TGraphErrors() isigma.SetMarkerStyle(24) fsigma = TF1("fsigma", "pol1", 0, 10000) fsigma.SetLineColor(2) fsigma.SetFillColor(2) # Alpha1 galpha1 = TGraphErrors() galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha") galpha1.SetMarkerStyle(20) galpha1.SetMarkerColor(cColor) galpha1.SetLineColor(cColor) ialpha1 = TGraphErrors() ialpha1.SetMarkerStyle(24) falpha1 = TF1("falpha", "pol1", 0, 10000) #pol0 falpha1.SetLineColor(2) falpha1.SetFillColor(2) # Slope1 gslope1 = TGraphErrors() gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)") gslope1.SetMarkerStyle(20) gslope1.SetMarkerColor(cColor) gslope1.SetLineColor(cColor) islope1 = TGraphErrors() islope1.SetMarkerStyle(24) fslope1 = TF1("fslope", "pol1", 0, 10000) #pol0 fslope1.SetLineColor(2) fslope1.SetFillColor(2) # Alpha2 galpha2 = TGraphErrors() galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha") galpha2.SetMarkerStyle(20) galpha2.SetMarkerColor(cColor) galpha2.SetLineColor(cColor) ialpha2 = TGraphErrors() ialpha2.SetMarkerStyle(24) falpha2 = TF1("falpha", "pol1", 0, 10000) #pol0 falpha2.SetLineColor(2) falpha2.SetFillColor(2) # Slope2 gslope2 = TGraphErrors() gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)") gslope2.SetMarkerStyle(20) gslope2.SetMarkerColor(cColor) gslope2.SetLineColor(cColor) islope2 = TGraphErrors() islope2.SetMarkerStyle(24) fslope2 = TF1("fslope", "pol1", 0, 10000) #pol0 fslope2.SetLineColor(2) fslope2.SetFillColor(2) n = 0 for i, m in enumerate(genPoints): if not m in signalNorm.keys(): continue if signalNorm[m].getVal() < 1.e-6: continue if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal()) gnorm.SetPoint(n, m, signalNorm[m].getVal()) #gnorm.SetPointError(i, 0, signalNorm[m].getVal()/math.sqrt(treeSign[m].GetEntriesFast())) gmean.SetPoint(n, m, vmean[m].getVal()) gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02)) gsigma.SetPoint(n, m, vsigma[m].getVal()) gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05)) galpha1.SetPoint(n, m, valpha1[m].getVal()) galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10)) gslope1.SetPoint(n, m, vslope1[m].getVal()) gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10)) galpha2.SetPoint(n, m, salpha2[m].getVal()) galpha2.SetPointError(n, 0, min(valpha2[m].getError(), valpha2[m].getVal()*0.10)) gslope2.SetPoint(n, m, sslope2[m].getVal()) gslope2.SetPointError(n, 0, min(vslope2[m].getError(), vslope2[m].getVal()*0.10)) #tmpVar = w.var(var+"_"+signalString) #print m, tmpVar.getVal(), tmpVar.getError() n = n + 1 gmean.Fit(fmean, "Q0", "SAME") gsigma.Fit(fsigma, "Q0", "SAME") galpha1.Fit(falpha1, "Q0", "SAME") gslope1.Fit(fslope1, "Q0", "SAME") galpha2.Fit(falpha2, "Q0", "SAME") gslope2.Fit(fslope2, "Q0", "SAME") # gnorm.Fit(fnorm, "Q0", "", 700, 5000) #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S")) #gnorm.Fit(fnorm, "Q", "SAME", 700, 6000) gnorm.Fit(fnorm, "Q", "SAME", 1800, 8000) ## adjusted recently for m in massPoints: if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.) # Interpolation method syield = gnorm.Eval(m) spline = gnorm.Eval(m, 0, "S") sfunct = fnorm.Eval(m) #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield)) delta = abs(1.-spline/sfunct) if sfunct > 0 else 0 syield = spline if interPar: #jmean = gmean.Eval(m) #jsigma = gsigma.Eval(m) #jalpha1 = galpha1.Eval(m) #jslope1 = gslope1.Eval(m) #jalpha2 = galpha2.Eval(m) #jslope2 = gslope2.Eval(m) jmean = gmean.Eval(m, 0, "S") ## checking if a spline yields nicer fits FIXME jsigma = gsigma.Eval(m, 0, "S") jalpha1 = galpha1.Eval(m, 0, "S") jslope1 = gslope1.Eval(m, 0, "S") jalpha2 = galpha2.Eval(m, 0, "S") jslope2 = gslope2.Eval(m, 0, "S") else: jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m jalpha2 = falpha2.GetParameter(0) + falpha2.GetParameter(1)*m + falpha2.GetParameter(2)*m*m jslope2 = fslope2.GetParameter(0) + fslope2.GetParameter(1)*m + fslope2.GetParameter(2)*m*m inorm.SetPoint(inorm.GetN(), m, syield) signalNorm[m].setVal(max(0., syield)) imean.SetPoint(imean.GetN(), m, jmean) if jmean > 0: vmean[m].setVal(jmean) isigma.SetPoint(isigma.GetN(), m, jsigma) if jsigma > 0: vsigma[m].setVal(jsigma) ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1) if not jalpha1==0: valpha1[m].setVal(jalpha1) islope1.SetPoint(islope1.GetN(), m, jslope1) if jslope1 > 0: vslope1[m].setVal(jslope1) ialpha2.SetPoint(ialpha2.GetN(), m, jalpha2) if not jalpha2==0: valpha2[m].setVal(jalpha2) islope2.SetPoint(islope2.GetN(), m, jslope2) if jslope2 > 0: vslope2[m].setVal(jslope2) #### newly introduced, not yet sure if helpful: vmean[m].removeError() vsigma[m].removeError() valpha1[m].removeError() valpha2[m].removeError() vslope1[m].removeError() vslope2[m].removeError() #signalNorm[m].setConstant(False) ## newly put here to ensure it's freely floating in the combine fit c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200 c1.Divide(2, 3) c1.cd(1) gmean.SetMinimum(0.) gmean.Draw("APL") imean.Draw("P, SAME") drawRegion(category) c1.cd(2) gsigma.SetMinimum(0.) gsigma.Draw("APL") isigma.Draw("P, SAME") drawRegion(category) c1.cd(3) galpha1.Draw("APL") ialpha1.Draw("P, SAME") drawRegion(category) galpha1.GetYaxis().SetRangeUser(0., 1.1) #adjusted upper limit from 5 to 2 c1.cd(4) gslope1.Draw("APL") islope1.Draw("P, SAME") drawRegion(category) gslope1.GetYaxis().SetRangeUser(0., 150.) #adjusted upper limit from 125 to 60 if True: #isAH: c1.cd(5) galpha2.Draw("APL") ialpha2.Draw("P, SAME") drawRegion(category) galpha2.GetYaxis().SetRangeUser(0., 2.) c1.cd(6) gslope2.Draw("APL") islope2.Draw("P, SAME") drawRegion(category) gslope2.GetYaxis().SetRangeUser(0., 20.) c1.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalShape.pdf") c1.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalShape.png") c2 = TCanvas("c2", "Signal Efficiency", 800, 600) c2.cd(1) gnorm.SetMarkerColor(cColor) gnorm.SetMarkerStyle(20) gnorm.SetLineColor(cColor) gnorm.SetLineWidth(2) gnorm.Draw("APL") inorm.Draw("P, SAME") gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100) gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25) #drawCMS(-1, "Simulation Preliminary", year=YEAR) drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) drawAnalysis(category) drawRegion(category) c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.pdf") c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# # create workspace w = RooWorkspace("Zprime_"+YEAR, "workspace") for m in massPoints: getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName())) getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName())) getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName())) w.writeToFile(WORKDIR+"MC_signal_%s_%s.root" % (YEAR, category), True) print "Workspace", WORKDIR+"MC_signal_%s_%s.root" % (YEAR, category), "saved successfully"
c1 = TCanvas('c1', 'The FillRandom example', 200, 10, 700, 900) c1.SetFillColor(18) pad1 = TPad('pad1', 'The pad with the function', 0.05, 0.50, 0.95, 0.95, 21) pad2 = TPad('pad2', 'The pad with the histogram', 0.05, 0.05, 0.95, 0.45, 21) pad1.Draw() pad2.Draw() pad1.cd() gBenchmark.Start('fillrandom') # # A function (any dimension) or a formula may reference # an already defined formula # form1 = TFormula('form1', 'abs(sin(x)/x)') sqroot = TF1('sqroot', 'x*gaus(0) + [3]*form1', 0, 10) sqroot.SetParameters(10, 4, 1, 20) pad1.SetGridx() pad1.SetGridy() pad1.GetFrame().SetFillColor(42) pad1.GetFrame().SetBorderMode(-1) pad1.GetFrame().SetBorderSize(5) sqroot.SetLineColor(4) sqroot.SetLineWidth(6) sqroot.Draw() lfunction = TPaveLabel(5, 39, 9.8, 46, 'The sqroot function') lfunction.SetFillColor(41) lfunction.Draw() c1.Update() #
if (icnt == NCNT): break print len(tzero1), len(tzero2), len(iw1), len(iw2) td = [tz1i - tz2i for tz1i, tz2i in zip(tzero1, tzero2)] h1 = TH1F("h1", "", 1000, -50, 50) i = 0 for tdi, iw1i, iw2i in zip(td, iw1, iw2): h1.Fill(tdi) i += 1 h2 = TH1F("h2", "", 1000, -50, 50) # h2.SetLineColor(2) h2.GetXaxis().CenterTitle() i = 0 for tdi, iw1i, iw2i in zip(td, iw1, iw2): if ((int(iw1i) & 0xffff0000) == (int(iw2i) & 0xffff0000)): h2.Fill(tdi) i += 1 h2.GetXaxis().SetTitle("CFD CH0-CH1 #deltaT (ns)") h2.GetXaxis().CenterTitle() # h1.Draw() # h2.Draw("same") h2.Draw("") f1 = TF1("f1", "gaus") h2.Fit(f1)
sigmas_err[tag] += [par.getError()] sig_p_result = None dx_results = {} fun = '[0] + [1] * (x - {})^2'.format(0.25) dx_funs = {'xm': fun, 'ym': fun} for i, tag in enumerate(('xm', 'ym')): g = TGraphErrors(len(sigmas[tag]), array('d', av[:]), array('d', sigmas[tag]), array('d', err_x[:]), array('d', sigmas_err[tag])) g.SetName('sigmas_' + tag) g.SetTitle('err_' + tag) graphs[tag] = g canvases['magnet'].cd(i + 1) if type(dx_funs[tag]) == str: fun = TF1('err_fun_' + tag, dx_funs[tag]) dx_funs[tag] = fun else: fun = dx_funs[tag] fun.SetLineColor(kBlue) dx_results[tag] = g.Fit(fun, 'S') g.Draw('AP') from ROOT import RooCBShape cb_mean = RooRealVar('cb_mean', 'cb_mean', 0, -100, 100) cb_s1 = RooRealVar('cb_s1', 'cb_s1', 100, 0, 500) cb_sf = RooRealVar('cb_sf', 'cb_sf', 100, 0.1, 500) cb_s2 = RooFormulaVar('cb_s2', 'cb_s2', "@0 * @1", RooArgList(cb_sf, cb_s1)) cb_frac = RooRealVar('cb_f', 'f' + tag, 0.2, 0.001, 0.99) cb_n = RooRealVar('cb_n', 'n', 1) cb_a1 = RooRealVar('cb_a', 'alpha', 20, 0.001, 200)