def fit(x, y): from ROOT import TF1, TGraphAsymmErrors g = TGraphAsymmErrors(len(x)) for i in xrange(len(x)): g.SetPoint(i, x[i], y[i].nominal_value) g.SetPointError(i, 0, 0, y[i].std_dev, y[i].std_dev) fit = TF1("fit", "-[1]*x*x+[0]", -40, 120) fit.SetParNames("z0", "a") g.Fit(fit) return fit
gDplusOverD0.Fit('fDplusOverD0', 'rq') hFrameDstar = cRatios.cd(2).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); D*^{+} / D^{0}') hFrameDstar.GetYaxis().SetDecimals() gDstarOverD0.Draw('p') gDstarOverD0.Fit('fDstarOverD0', 'rq') hFrameDs = cRatios.cd(3).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); D_{s}^{+} / D^{0}') hFrameDs.GetYaxis().SetDecimals() gDsOverD0.Draw('p') gDsOverD0.Fit('fDsOverD0', 'rq') hFrameLc = cRatios.cd(4).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); #Lambda_{c}^{+} / D^{0}') hFrameLc.GetYaxis().SetDecimals() gLcOverD0.Draw('p') gLcOverD0.Fit('fLcOverD0', 'r') dfDplus = dfD0FONLL.copy() for col in dfDplus.columns: if col not in ['ptmin', 'ptmax']: dfDplus[col] = dfDplus.apply(lambda x: x[col] * gDplusOverD0.Eval( (x['ptmax'] + x['ptmin']) / 2), axis=1) dfDs = dfD0FONLL.copy() for col in dfDs.columns: if col not in ['ptmin', 'ptmax']: dfDs[col] = dfDs.apply(lambda x: x[col] * gDsOverD0.Eval( (x['ptmax'] + x['ptmin']) / 2), axis=1)
def draw_geff(target_dir, c_title, ext, t, title, h_name, h_bins, to_draw, denom_cut, extra_num_cut, opt, color, marker_st=1, marker_sz=1): c = TCanvas("c", "c", 600, 600) c.Clear() gPad.SetGrid(1) gStyle.SetStatStyle(0) gStyle.SetOptStat(0) gStyle.SetOptFit(0) t.Draw(to_draw + ">>num_" + h_name + h_bins, extra_num_cut + denom_cut, "goff") num = TH1F(gDirectory.Get("num_" + h_name)) if not num: sys.exit('num does not exist') num = TH1F(num.Clone("eff_" + h_name)) t.Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff") den = TH1F(gDirectory.Get("denom_" + h_name).Clone("denom_" + h_name)) eff = TGraphAsymmErrors(num, den) if not "same" in opt: num.Reset() num.GetYaxis().SetRangeUser(0., 1.05) num.SetStats(0) num.SetTitle(title) num.Draw() eff.SetLineWidth(2) eff.SetLineColor(color) eff.SetMarkerStyle(marker_st) eff.SetMarkerColor(color) eff.SetMarkerSize(marker_sz) eff.Draw(opt + " same") ## Do fit in the flat region if "eta" in c_title: xmin = eta_min xmax = eta_max else: xmin = -999. xmax = 999. f1 = TF1("fit1", "pol0", xmin, xmax) r = eff.Fit("fit1", "RQS") ptstats = TPaveStats(0.25, 0.35, 0.75, 0.55, "brNDC") ptstats.SetName("stats") ptstats.SetBorderSize(0) ptstats.SetLineWidth(0) ptstats.SetFillColor(0) ptstats.SetTextAlign(11) ptstats.SetTextFont(42) ptstats.SetTextSize(.05) ptstats.SetTextColor(kRed) ptstats.SetOptStat(0) ptstats.SetOptFit(1111) chi2 = int(r.Chi2()) ndf = int(r.Ndf()) ## prob = r.Prob() round(2.675, 2) p0 = f1.GetParameter(0) p0e = f1.GetParError(0) ptstats.AddText("#chi^{2} / ndf: %d/%d" % (chi2, ndf)) ## ptstats.AddText("Fit probability: %f %" %(prob)) ptstats.AddText("Efficiency: %f #pm %f %%" % (p0, p0e)) ptstats.Draw("same") pt = TPaveText(0.09899329, 0.9178322, 0.8993289, 0.9737762, "blNDC") pt.SetName("title") pt.SetBorderSize(1) pt.SetFillColor(0) pt.SetFillStyle(0) pt.SetTextFont(42) pt.AddText(eff.GetTitle()) pt.Draw("same") c.Modified() c.SaveAs(target_dir + c_title + ext)
graph.GetXaxis().SetLimits(x[0]-2*x_low[0], x[-1]+2*x_low[-1]) if args.logy: c.SetLogy(1) graph.GetHistogram().SetMinimum(y.min()/2) graph.GetHistogram().SetMaximum(y.max()*3) graph.SetTitle("") Frame(gPad) yrlabel = TextAuto(gPad, args.year, align = 31) last = histo.GetNbinsX() - 1 func = TF1("func","sqrt(([0]/(x))^2 + 2*([1]^2))", x[0]-x_low[0], x[last]+x_high[last]) func.SetParameter(0, N) func.SetParameter(1, C) graph.Fit("func","R") Nlabel = Text(gPad, 0.6, 0.7, "N = {:.3f} #pm {:.3f} ns".format(func.GetParameter(0), func.GetParError(0))) Clabel = Text(gPad, 0.6, 0.65,"C = {:.3f} #pm {:.3f} ns".format(func.GetParameter(1), func.GetParError(1))) c.Update() c.Modified() if args.show: input() if (args.effs): ename = "effs_deltaT_e1_seeds_vs_effA_e1_seeds" if args.glob: ename = "effs_deltaT_ee_vs_effA_ee" eff_s_graph = inFile.Get(ename+"_"+args.sel) eff_s_graph.SetMarkerStyle(8)
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
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()
#calculate the efficiency hEff = TGraphAsymmErrors(hSel, hAll) #hEff = TH1D("hEffBemc", "", nbins, bins.data()); #hEff.Divide(hSel, hAll, 1, 1, "B"); fitFunc = TF1("fitFunc", fitFuncErf, 0., 10. , 4) fitFunc.SetParNames("n", "pthr", "sigma", "e0") fitFunc.SetParameters(0.45, 1., 0.3, 0.01) fitFunc.FixParameter(3, 0.) fitFunc.SetLineColor(clin) fitFunc.SetLineWidth(2) fitFunc.SetNpx(1000) #make the fit r1 = ( hEff.Fit(fitFunc, "RS") ).Get() out.write(ut.log_tfit_result(r1)) #test for cast in fit result #gROOT.LoadMacro("../plot_utils.h") #rt.FitResultShow(r1) ut.show_tfit_result(r1) #log fit parameters in 3-digit precision ut.log_results(out, "Fit parameters in 3-digit precision:") chistr = "chi2/ndf: {0:.3f}".format(r1.Chi2()/r1.Ndf()) ut.log_results(out, chistr) for ipar in xrange(3): nam = fitFunc.GetParName(ipar) val = fitFunc.GetParameter(ipar) err = fitFunc.GetParError(ipar)