def make_scatter_plots_pls(sig_name, bkg_name): hname = sig_name h = histograms[hname] h.SetMinimum(h.ymin) h.SetMaximum(h.ymax) h.Draw() n = len(h.data) # hname = bkg_name h = histograms[hname] g = Graph(n) # truncate data = h.data[:n] # truncate for i, (xx, yy) in enumerate(data): g.SetPoint(i, xx, yy) g.markerstyle = 4 g.markercolor = 'black' g.Draw("p") keepalive(gPad.func(), g) # hname = sig_name h = histograms[hname] g = Graph(n) data = h.data for i, (xx, yy) in enumerate(data): g.SetPoint(i, xx, yy) g.markerstyle = 4 g.markercolor = 'red' g.Draw("p") keepalive(gPad.func(), g) gPad.Print(options.outdir + hname + ".png") return
def spread_x( histograms, bin_edges ): """ Usually when plotting multiple histograms with same x-values and similar y-values their markers will overlap. This function spreads the data points across a bin. It creates a set of graphs with the same y-values but different x. @param histograms: list of histograms with same binning @param bin_edges: the bin edges of the histograms """ # construct bins from the bin edges bins = [( bin_lower, bin_upper ) for bin_lower, bin_upper in izip( bin_edges[:-1], bin_edges[1:] )] # now get the bin widths bin_widths = [abs( bin_i[1] - bin_i[0] ) for bin_i in bins] # number of histograms number_of_hists = len( histograms ) # and divide the bins into equidistant bits leaving some space to the bin edges x_locations = [] add_locations = x_locations.append for bin_lower, width in izip( bin_edges, bin_widths ): x_step = width / ( 1.0 * number_of_hists + 1 ) # +1 due to spacing to bin edge add_locations( [bin_lower + n * x_step for n in range( 1, number_of_hists + 1 )] ) # transpose x_locations = map( list, zip( *x_locations ) ) graphs = [] for histogram, x_coordinates in zip( histograms, x_locations ): g = Graph( histogram ) for i, ( x, y ) in enumerate( zip( x_coordinates, histogram.y() ) ): g.SetPoint( i, x, y ) graphs.append( g ) return graphs
def tau_from_L_curve(unfoldingObject): ''' Get best tau via l curve method Not tested ''' lCurve = TGraph() logTauX = TSpline3() logTauY = TSpline3() iBest = unfoldingObject.ScanLcurve(500, 0., 0., lCurve, logTauX, logTauY) # Additional info, plots t = Double(0) x = Double(0) y = Double(0) logTauX.GetKnot(iBest, t, x) logTauY.GetKnot(iBest, t, y) bestLcurve = Graph(1) bestLcurve.SetPoint(1, x, y) lCurve.SetMarkerColor(600) lCurve.SetMarkerSize(1) lCurve.SetMarkerStyle(5) # lCurve.Draw("AP"); bestLcurve.markercolor = 'red' # bestLcurve.Draw("*"); return unfoldingObject.GetTau()
def roc(ana, category, discr_var): """ Calculates the ROC curve Returns the sorted list of wp and a TGraph """ h_template = Hist(1000, 0, 1) h_sig = ana.tau.get_hist_array({discr_var: h_template}, category=category) h_sig = h_sig[discr_var] h_bkg = ana.jet.get_hist_array({discr_var: h_template}, category=category) h_bkg = h_bkg[discr_var] roc_gr = Graph(h_sig.GetNbinsX()) roc_list = [] for i in range(1, h_sig.GetNbinsX()): eff_sig_i = (h_sig.Integral() - h_sig.Integral(0, i)) / h_sig.Integral() eff_bkg_i = (h_bkg.Integral() - h_bkg.Integral(0, i)) / h_bkg.Integral() rej_bkg_i = 1. / eff_bkg_i if eff_bkg_i != 0 else 0. roc_list.append( working_point(h_sig.GetBinLowEdge(i), eff_sig_i, eff_bkg_i)) roc_gr.SetPoint(i, eff_sig_i, rej_bkg_i) return roc_gr, roc_list
def old_working_points(ana, category, wp_level): log.info('create the workers') names = ['loose', 'medium', 'tight'] cuts = [ wp_level + '_is_loose == 1', wp_level + '_is_medium == 1', wp_level + '_is_tight == 1' ] workers = [FuncWorker(get_sig_bkg, ana, category, cut) for cut in cuts] run_pool(workers, n_jobs=-1) yields = [w.output for w in workers] log.info('--> Calculate the total yields') sig_tot = ana.tau.events(category)[1].value bkg_tot = ana.jet.events(category, weighted=True)[1].value gr = Graph(len(cuts)) wps = [] for i, (val, yields, name) in enumerate(zip(cuts, yields, names)): eff_sig = yields[0] / sig_tot eff_bkg = yields[1] / bkg_tot rej_bkg = 1. / eff_bkg if eff_bkg != 0 else 0 wps.append(working_point(val, eff_sig, eff_bkg, name=name)) gr.SetPoint(i, eff_sig, rej_bkg) return gr, wps
def double_profile(tprofile_x, tprofile_y): """creates a graph with points whose x and y values and errors are taken from the bins of two profiles with identical binning""" ## Note: underflow and overflow bins are discarded if len(tprofile_x) != len(tprofile_y): raise ValueError( "Cannot build double profile: x and y profiles " "have different number or bins ({} and {})".format( len(tprofile_x) - 2, len(tprofile_y) - 2)) _dp_graph = Graph(len(tprofile_x) - 2, type='errors') # symmetric errors _i_point = 0 for _i_bin, (_bin_proxy_x, _bin_proxy_y) in enumerate(zip(tprofile_x, tprofile_y)): # disregard overflow/underflow bins if _i_bin == 0 or _i_bin == len(tprofile_x) - 1: continue if _bin_proxy_y.value: _dp_graph.SetPoint(_i_point, _bin_proxy_x.value, _bin_proxy_y.value) _dp_graph.SetPointError(_i_point, _bin_proxy_x.error, _bin_proxy_y.error) _i_point += 1 # remove "unfilled" points while (_dp_graph.GetN() > _i_point): _dp_graph.RemovePoint(_dp_graph.GetN() - 1) return _dp_graph
def get_uncertainty_graph(hnom, curve_uncert): """ Convert an histogram and a RooCurve into a TGraphAsymmError Parameters ---------- hnom: TH1F, TH1D, ... The histogram of nominal values curve_uncert: RooCurve The uncertainty band around the nominal value TODO: Improve the handling of the underflow and overflow bins """ graph = Graph(hnom.GetNbinsX()) for ibin in xrange(1, hnom.GetNbinsX() + 1): uncerts = [] for ip in xrange(3, curve_uncert.GetN() - 3): x, y = ROOT.Double(0.), ROOT.Double(0.) curve_uncert.GetPoint(ip, x, y) if hnom.GetBinLowEdge(ibin) <= x < hnom.GetBinLowEdge(ibin + 1): uncerts.append(y) log.debug('{0}, bin {1}: {2}'.format(hnom.name, ibin, uncerts)) low, high = min(uncerts), max(uncerts) bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) + hnom.GetBinLowEdge(ibin)) e_x_low = bin_center - hnom.GetBinLowEdge(ibin) e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center bin_content = hnom.GetBinContent(ibin) e_y_low = hnom.GetBinContent(ibin) - low e_y_high = high - hnom.GetBinContent(ibin) graph.SetPoint(ibin - 1, bin_center, bin_content) graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high) return graph
def grrScale(gr1, scale): x1 = Double() x_ = Double() x1e = Double() y1 = Double() y1e = Double() y = [] ex = [] ey = [] NC = gr1.GetN() x = [0 for i in range(NC)] for ii in range(NC): x1e = gr1.GetErrorX(ii) y1e = gr1.GetErrorY(ii) gr1.GetPoint(ii, x_, y1) x1 = x_ * 1.0 x[ii] = x1 y.append(y1 * scale) ex.append(x1e) ey.append(y1e * scale) gr = Graph(NC) for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)): gr.SetPoint(i, x0, y0) gr.SetPointError(i, x0e, x0e, y0e, y0e) return gr
def remap_x_values(hist, corr_hist): """ Map the x values of hist to the y values of map_hist. In order to do so, it is necessary that the x values of hist are also present as x-values in map_hist. Parameters ---------- hist : Hist1D corr_hist : Hist2D Correlations between the quantity on hist's x-axis (also corr_hist's xaxis) and the new quantity to plot agains (on corr_hist's y-axis. Returns ------- Graph Graph of the remapped hist. Errors are ??? TODO """ hist = asrootpy(hist) corr_hist = asrootpy(corr_hist) profx = asrootpy(corr_hist.ProfileX(gen_random_name())) rt_graph = Graph() for i, (nch_ref_bin, counter_bin) in enumerate(zip(profx.bins(), hist.bins())): rt_graph.SetPoint(i, nch_ref_bin.value, counter_bin.value) xerr, yerr = nch_ref_bin.error / 2.0, counter_bin.error / 2.0 rt_graph.SetPointError(i, xerr, xerr, yerr, yerr) return rt_graph
def get_mean_rms(category, var): gr_mean = Graph(len(SIGNALS_14TEV)) gr_rms = Graph(len(SIGNALS_14TEV)) for ip, signal in enumerate(SIGNALS_14TEV): with root_open('efficiencies/eff_presel_{0}_v{1}.root'.format( signal, VERSION)) as fsig: h_s = fsig[category].Get('h_' + category + '_' + var['name']) gr_mean.SetPoint(ip, DATASETS[signal]['mu'], h_s.GetMean()) gr_mean.SetPointError(ip, 0, 0, h_s.GetMeanError(), h_s.GetMeanError()) gr_rms.SetPoint(ip, DATASETS[signal]['mu'], h_s.GetRMS()) gr_rms.SetPointError(ip, 0, 0, h_s.GetRMSError(), h_s.GetRMSError()) gr_mean.xaxis.title = 'Average Interactions Per Bunch Crossing' gr_mean.yaxis.title = 'Mean of ' + get_label(var) gr_rms.xaxis.title = 'Average Interactions Per Bunch Crossing' gr_rms.yaxis.title = 'RMS of ' + get_label(var) return gr_mean, gr_rms
def addConstantError(gr1, error, **kwargs): x_ = Double() x1e = Double() y1_ = Double() y1e = Double() NC = gr1.GetN() y2 = [0 for i in range(NC)] ex = [] ey = [] x = [0 for i in range(NC)] gr = Graph(NC) for ii in range(NC): x1e = gr1.GetErrorX(ii) y1e = gr1.GetErrorY(ii) gr1.GetPoint(ii, x_, y1_) print("{} {} {}".format(i, x_, y1_)) x1 = x_ * 1.0 x[ii] = x1 y1 = y1_ * 1.0 y2[ii] = y1 print("Append y with {}".format(y1)) print(y2) ex.append(x1e) if (kwargs.get('rel'), False): ey.append(math.sqrt(y1e**2 + (error * y1)**2)) print("Old error: {}, New Error: {}".format( y1e, math.sqrt(y1e**2 + (error * y1)**2))) else: ey.append(math.sqrt(y1e**2 + error**2)) # gr.SetPoint(i,x1,y1) # print("Set point {} {},{}".format(i,x1,y1)) # # if(kwargs.get('rel'),False): # gr.SetPointError(i,x1e,x1e,math.sqrt(y1e**2+(error*y1)**2),math.sqrt(y1e**2+(error*y1)**2)) # print("Set point Error {} {},{}".format(i,x1e,math.sqrt(y1e**2+(error*y1)**2))) # else: # gr.SetPointError(i,x1e,x1e,math.sqrt(y1e**2+error**2),math.sqrt(y1e**2+error**2)) gr = Graph(NC) print(x) print(y2) print(ex) print(ey) for x0, y0, x0e, y0e, i in zip(x, y2, ex, ey, range(NC)): gr.SetPoint(i, x0, y0) print("Set point {} {},{}".format(i, x0, y0)) gr.SetPointError(i, x0e, x0e, y0e, y0e) print("Set point Error {} {},{}".format(i, x0e, y0e)) print(gr) return gr
def draw_curve_7(_func, name, title, ylow, yhigh): """ Draw 7TeV trigger efficiency curves """ graphs = [] for (trigger, color) in triggers: tool = ROOT.TauTriggerCorrections( os.path.join(base, 'triggerSF_%s.root' % trigger)) func = getattr(tool, _func) eff = map(lambda x: func(x, 0), pt) eff_low = map(lambda x: func(x, -1), pt) eff_high = map(lambda x: func(x, 1), pt) graph = Graph(len(pt), name=trigger) for i, (p, e, e_low, e_high) in enumerate(zip(pt, eff, eff_low, eff_high)): graph.SetPoint(i, p / 1000, e) graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e) graph.linecolor = color graph.linewidth = 2 graph.fillstyle = '/' graph.fillcolor = color graphs.append(graph) c = Canvas() leg = Legend(len(graphs), pad=c, topmargin=0.4, leftmargin=0.3, textsize=25, margin=0.2) for i, g in enumerate(graphs): if i == 0: g.Draw('3AC') g.xaxis.title = '#font[52]{p}_{T} [GeV]' g.xaxis.SetLimits(20, 100) g.yaxis.SetLimits(ylow, yhigh) g.yaxis.SetRangeUser(ylow, yhigh) g.yaxis.title = title else: g.Draw('3C SAME') leg.AddEntry(g, g.name, 'L') leg.Draw() lines = [] for thresh in (25, 35): line = Line(thresh, ylow, thresh, yhigh) line.linestyle = 'dashed' line.linewidth = 2 line.Draw() lines.append(line) c.SaveAs('trigger_{0}.png'.format(name)) c.SaveAs('trigger_{0}.eps'.format(name))
def get_rebinned_graph(graph_origin, binning=None): if binning is None: return graph_origin graph_rebin = Graph(len(binning) - 1) if len(graph_origin) != len(graph_rebin): log.warning('uniform: {0} bins != rebinned: {1} bins'.format( len(graph_origin), len(graph_rebin))) raise RuntimeError('wrong binning') for ipoint, (y, yerr) in enumerate(zip(graph_origin.y(), graph_origin.yerr())): x_rebin_err = 0.5 * (binning[ipoint + 1] - binning[ipoint]) x_rebin = binning[ipoint] + x_rebin_err graph_rebin.SetPoint(ipoint, x_rebin, y) graph_rebin.SetPointError(ipoint, x_rebin_err, x_rebin_err, yerr[0], yerr[1]) return graph_rebin
def UncertGraph(hnom, curve_uncert): """ Convert an histogram and a RooCurve into a TGraphAsymmError Parameters ---------- hnom: TH1F, TH1D,... The histogram of nominal values curve_uncert: RooCurve The uncertainty band around the nominal value curve_uncert: RooCurve TODO: Improve the handling of the underflow and overflow bins """ graph = Graph(hnom.GetNbinsX()) # --------------------------------------------- for ibin in xrange(1, hnom.GetNbinsX() + 1): uncerts = [] for ip in xrange(3, curve_uncert.GetN() - 3): x, y = ROOT.Double(0.), ROOT.Double(0.) curve_uncert.GetPoint(ip, x, y) if int(x) == int(hnom.GetBinLowEdge(ibin)): uncerts.append(y) uncerts.sort() log.info('{0}: {1}'.format(hnom.name, uncerts)) if len(uncerts) != 2: for val in uncerts: if val in uncerts: uncerts.remove(val) if len(uncerts) != 2: raise RuntimeError( 'Need exactly two error values and got {0}'.format(uncerts)) bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) + hnom.GetBinLowEdge(ibin)) e_x_low = bin_center - hnom.GetBinLowEdge(ibin) e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center bin_content = hnom.GetBinContent(ibin) e_y_low = hnom.GetBinContent(ibin) - uncerts[0] e_y_high = uncerts[1] - hnom.GetBinContent(ibin) graph.SetPoint(ibin - 1, bin_center, bin_content) graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high) # --------------------------------------------- return graph
def scaleGraph(gr1, sc): x1 = ROOT.Double() x_ = ROOT.Double() y1 = ROOT.Double() test = [] y = [] NC = gr1.GetN() x = [0 for i in range(NC)] for ii in range(NC): gr1.GetPoint(ii, x_, y1) x1 = x_ * 1.0 x[ii] = x1 y.append(y1 * sc) gr = Graph(NC) for x0, y0, i in zip(x, y, range(NC)): gr.SetPoint(i, x0, y0) return gr
def makeSystError(gr1, gr2, **kwargs): x_ = Double() x1e = Double() x2 = Double() x2e = Double() y1 = Double() y1e = Double() y2 = Double() y2e = Double() NC = gr1.GetN() print("Number of points: {}".format(NC)) y = [] ex = [] ey = [] x = [0 for i in range(NC)] for ii in range(NC): x1e = gr1.GetErrorX(ii) y1e = gr1.GetErrorY(ii) gr1.GetPoint(ii, x_, y1) x1 = x_ * 1.0 gr2.GetPoint(ii, x2, y2) x2e = gr2.GetErrorX(ii) y2e = gr2.GetErrorY(ii) x[ii] = x1 if (kwargs.get('abs', False)): y.append(math.fabs(y1 - y2)) elif (kwargs.get('rel', False)): y.append((y1 - y2) / (y1 + y2)) else: y.append(y1 - y2) ex.append(x1e) ey.append(math.sqrt(y1e**2 + y2e**2)) gr = Graph(NC) for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)): gr.SetPoint(i, x0, y0) print("Set point {} {},{}".format(i, x0, y0)) gr.SetPointError(i, x0e, x0e, y0e, y0e) return gr
def grrDivide(gr1, gr2): x1 = Double() x_ = Double() x1e = Double() x2 = Double() x2e = Double() y1 = Double() y1e = Double() y2 = Double() y2e = Double() test = [] y = [] ex = [] ey = [] NC = gr1.GetN() x = [0 for i in range(NC)] test = [0 for i in range(NC)] for ii in range(NC): x1e = gr1.GetErrorX(ii) y1e = gr1.GetErrorY(ii) gr1.GetPoint(ii, x_, y1) x1 = x_ * 1.0 gr2.GetPoint(ii, x2, y2) x2e = gr2.GetErrorX(ii) y2e = gr2.GetErrorY(ii) x[ii] = x1 y.append(y1 / y2 if y2 != 0 else 0) ex.append(x2e) ey.append( math.sqrt(pow(y1e / y2, 2) + pow(y1 * y2e / (y2 * y2), 2)) if y2 != 0 else 0) gr = Graph(NC) for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)): gr.SetPoint(i, x0, y0) gr.SetPointError(i, x0e, x0e, y0e, y0e) return gr
def main(): print('Number of arguments: ', len(sys.argv), 'arguments.') print('Argument list:',str(sys.argv)) filename = sys.argv[1] separate = int(sys.argv[2]) if(len(sys.argv) > 3): start = int(sys.argv[3]) end = int(sys.argv[4]) else: start = 1 end = 6 n_figs = end-start print("Number of figs: {}".format(n_figs)) print("Input file: ") print(filename) FullJets_R04 = dataset('Full jets R=0.4',NFIN=0,range=(start,end),filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',color=2,style=24,rebin=2) #Mixed_FullJets_R04 = datasetMixed("Full jets R=0.4",NFIN=0,range=5,filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',color=2,style=24,rebin=2) #signal,jetPt = FullJets_R04.getHist('JtWeightBin',jetpt = True) #signal2 = FullJets_R04.getHist('JtWeightLeadingRefBin',jetpt=False) compareHistsWithRatio(FullJets_R04,['JtWeightBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin'],['Jet axis ref.','leading ref. (xlong 0.0-0.2)','leading ref. (xlong 0.2-0.4)','leading ref. (xlong 0.4-0.6)','leading ref. (xlong 0.6-1.0)'],step=1,extras=['','Xlong00','Xlong01','Xlong02','Xlong03']) plt.savefig("PythonFigures/JetVsLeadingRefConst.pdf",format='pdf') #Save figure plt.show() sets = compareHistsWithRatio(FullJets_R04,['JetConeJtWeightBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin'],['Jet axis ref.','leading ref.(xlong 0.0-0.2)','leading ref.(xlong 0.2-0.4)','leading ref.(xlong 0.4-0.6)','leading ref. (xlong 0.6-1.0)'],step=1,extras=['','Xlong00','Xlong01','Xlong02','Xlong03']) plt.savefig("PythonFigures/JetVsLeadingRefJetCone.pdf",format='pdf') #Save figure plt.show() JtJet = sets[0][0] JtLeadingxlong00 = sets[1][0] JtLeadingxlong01 = sets[2][0] JtLeadingxlong02 = sets[3][0] JtLeadingxlong03 = sets[4][0] JtLeading = [h.clone() for h in sets[1][0]] for h,s,s2,s3 in zip(JtLeading,sets[2][0],sets[3][0],sets[4][0]): h.Add(s,1) h.Add(s2,1) h.Add(s3,1) # print(JtLeading) # for set in sets[2:]: # for h,s in zip(JtLeading,set[0]): # print(s) # h.Add(s,1) jetPt = sets[0][1] jetPtCenter = array('d',[(a+b)/2.0 for a,b in jetPt]) jetPtErrors = array('d',[(b-a)/2.0 for a,b in jetPt]) FullJets_fit = [] FullJets_parameters = [] FullJets_gausRMS = [] FullJets_gammaRMS = [] FullJets_gausYield = [] FullJets_gammaYield = [] for jT,title in zip((JtJet,JtLeading,JtLeadingxlong00,JtLeadingxlong01,JtLeadingxlong02),("Jet ref.","Leading ref","Leading ref.(xlong 0.0-0.2)","Leading ref.(xlong 0.2-0.4)","Leading ref.(xlong 0.4-0.6)","Leading ref.(xlong 0.6-1.0)")): gausRMS = [] gammaRMS = [] gausRMSe = [] gammaRMSe = [] gausYield = [] gammaYield = [] gausYielde = [] gammaYielde = [] fits = [] parameters = [] for h,i in zip(jT,range(Njets)): fit,d = defs.fitJtHisto(h,'',1,i,8,title,draw=False) fits.append(fit) parameters.append(d) gausRMS.append(d['gausRMS']) gausRMSe.append(d['gausRMSe']) gammaRMS.append(d['gammaRMS']) gammaRMSe.append(d['gammaRMSe']) gausYield.append(d['gausYield']) gausYielde.append(d['gausYielde']) gammaYield.append(d['gammaYield']) gammaYielde.append(d['gammaYielde']) gausRMSg = Graph(len(gausRMS)-2) gammaRMSg = Graph(len(gammaRMS)-2) gausYieldg = Graph(len(gausYield) -2) gammaYieldg = Graph(len(gammaYield)-2) for h,he,g in zip((gausYield,gammaYield),(gausYielde,gammaYielde),(gausYieldg,gammaYieldg)): for x,xe,a,e,i in zip(jetPtCenter[2:],jetPtErrors[2:],h[2:],he[2:],range(len(gausRMS)-2)): g.SetPoint(i,x,a) g.SetPointError(i,xe,xe,e,e) for a,b,c,d,e,f,i in zip(gausRMS[2:],gammaRMS[2:],gausRMSe[2:],gammaRMSe[2:],jetPtCenter[2:],jetPtErrors[2:],range(len(gausRMS)-2)): gausRMSg.SetPoint(i,e,a) gausRMSg.SetPointError(i,f,f,c,c) gammaRMSg.SetPoint(i,e,b) gammaRMSg.SetPointError(i,f,f,d,d) FullJets_gausRMS.append(gausRMSg) FullJets_gammaRMS.append(gammaRMSg) FullJets_gausYield.append(gausYieldg) FullJets_gammaYield.append(gammaYieldg) FullJets_fit.append(fits) FullJets_parameters.append(parameters) print(gausRMS[2:]) print(gammaRMS[2:]) print(jetPtCenter[2:]) drawWithErrors2Combined(FullJets_gausRMS,FullJets_gammaRMS,["Jet ref.","Leading ref.","Leading ref.(xlong 0.0-0.2)","Leading ref.(xlong 0.2-0.4)","Leading ref.(xlong 0.4-0.6)"],15,500,1,0,1.85,0,r'jet $p_T$',r'$\sqrt{\left<j_T^2\right>}$','Pythia','PythonFigures/JetVsLeadingRefJetConeFits') return if(separate > 0): fig = plt.figure(1) ax = fig.add_subplot(1,1,1) ax.set_xscale('log') ax.set_yscale('log') ax.text(0.2,0.0005,d['system'] +'\n'+ d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7) rplt.errorbar(signal[separate],xerr=False,emptybins=False,axes=ax,label="Jet axis reference",fmt='o') #Plot jT histogram, rplt.errorbar(signal2[separate],xerr=False,emptybins=False,axes=ax,label="Leading track reference",fmt='o') ax.text(0.3,1e2,r'$p_{{T,\mathrm{{jet}}}}$:''\n'r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],jetPt[separate][1])) ax.set_xlim([0.1,12]) ax.set_ylim([5e-6,1.5e3]) ax.legend(loc = 'lower left') plt.savefig("PythonFigures/MixedFullJetsR04JetConeJtLeadingRefJetPt{0}.pdf".format(separate),format='pdf') #Save figure plt.show() #Draw figure on screen else: n_rows = n_figs//4 print(n_rows) fig, axs = defs.makegrid(4,n_figs//4,xlog=True,ylog=True,d=d,shareY=True,figsize=(10,5)) axs = axs.reshape(n_figs) axs[1].text(0.12,0.002,d['system'] +'\n'+ d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7) for jT,jT2,pT,ax,i in zip(signal[start:],signal2[start:],jetPt[start:],axs,range(0,9)): jT.SetMarkerColor(1) jT2.SetMarkerColor(2) plot = rplt.errorbar(jT,xerr=False,emptybins=False,axes=ax,label="Jet axis reference",fmt='o',fillstyle='none',ecolor='black') #Plot jT histogram, plot = rplt.errorbar(jT2,xerr=False,emptybins=False,axes=ax,label="Leading track reference",fmt='o',fillstyle='none',ecolor='red') #Plot jT histogram, ax.text(0.3,1e2,r'$p_{{T,\mathrm{{jet}}}}$:''\n'r' {:02d}-{:02d} GeV'.format(pT[0],pT[1])) ax.set_xlim([0.1,22]) #Set x-axis limits ax.set_ylim([5e-4,2e3]) #Set y-axis limits ax.set_xticklabels(ax.get_xticklabels(),horizontalalignment='left') axs[0].legend(loc = 'lower left') plt.savefig("PythonFigures/MixedFullJetsR04JetConeJtLeadingRefPtFrom{}To{}.pdf".format(start,end),format='pdf') #Save figure plt.show() #Draw figure on screen
def main(): print('Number of arguments: ', len(sys.argv), 'arguments.') print('Argument list:', str(sys.argv)) filename = sys.argv[1] if len(sys.argv) > 2: fileData = sys.argv[2] else: fileData = None print("Input file: ") print(filename) Njets = 9 if fileData is not None: fD = root_open(fileData, 'read') iS = 0 gGausRMSData = fD.Get("gGausRMS{:02d}".format(iS)) gGausRMSerrData = fD.Get("gGausRMS{:02d}_Systematics".format(iS)) gGausYieldData = fD.Get("gGausYield{:02d}".format(iS)) gGausYielderrData = fD.Get("gGausYield{:02d}_Systematics".format(iS)) gGammaRMSData = fD.Get("gGammaRMS{:02d}".format(iS)) gGammaRMSerrData = fD.Get("gGammaRMS{:02d}_Systematics".format(iS)) gGammaYieldData = fD.Get("gGammaYield{:02d}".format(iS)) gGammaYielderrData = fD.Get("gGammaYield{:02d}_Systematics".format(iS)) with root_open(filename, 'read') as f: FullJets_jT = [] colors = (1, 2, 3) for iF, c in zip((8, 6, 7), colors): jT = [ f.get( 'AliJJetJtTask/AliJJetJtHistManager/JetConeJtWeightBin/JetConeJtWeightBinNFin{:02d}JetPt{:02d}' .format(iF, ij)) for ij in range(Njets) ] bgJt = [ f.get( 'AliJJetJtTask/AliJJetJtHistManager/BgJtWeightBin/BgJtWeightBinNFin{:02d}JetPt{:02d}' .format(iF, ij)) for ij in range(Njets) ] jetPtBin = [ f.get( 'AliJJetJtTask/AliJJetJtHistManager/JetPtBin/JetPtBinNFin{:02d}JetPt{:02d}' .format(iF, ij)) for ij in range(Njets) ] nJets = [h.Integral() for h in jetPtBin] nBgs = [ f.get( 'AliJJetJtTask/AliJJetJtHistManager/BgTrkNumberBin/BgTrkNumberBinNFin{:02d}JetPt{:02d}' .format(iF, ij)).Integral() for ij in range(Njets) ] FullJets_jT.append(jT) #FullJets_bgJt.append(bgJt) #FullJets_jetPtBin.append(jetPtBin) for j, b, nj, nb in zip(jT, bgJt, nJets, nBgs): j.Rebin(2) b.Rebin(2) j.Scale(1.0 / nj, "width") b.Scale(1.0 / nb, "width") j.SetMarkerColor(c) b.SetMarkerColor(c) j.Add(b, -1.0) jetPt = [ (int( re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*', h.GetTitle(), re.M | re.I).group(1)), int( re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*', h.GetTitle(), re.M | re.I).group(2))) for h in FullJets_jT[0] ] #Use regular expressions to extract jet pT range from histogram titles jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt]) jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt]) print(jetPt, type(jetPt)) print(jetPtCenter, type(jetPtCenter)) print(jetPtErrors, type(jetPtErrors)) FullJets_fit = [] FullJets_parameters = [] FullJets_gausRMS = [] FullJets_gammaRMS = [] FullJets_gausYield = [] FullJets_gammaYield = [] for jT in FullJets_jT: gausRMS = [] gammaRMS = [] gausRMSe = [] gammaRMSe = [] gausYield = [] gammaYield = [] gausYielde = [] gammaYielde = [] fits = [] parameters = [] for h, i in zip(jT, range(Njets)): fit, d = fitJtHisto(h, '', 1, i, 8) fits.append(fit) parameters.append(d) gausRMS.append(d['gausRMS']) gausRMSe.append(d['gausRMSe']) gammaRMS.append(d['gammaRMS']) gammaRMSe.append(d['gammaRMSe']) gausYield.append(d['gausYield']) gausYielde.append(d['gausYielde']) gammaYield.append(d['gammaYield']) gammaYielde.append(d['gammaYielde']) gausRMSg = Graph(len(gausRMS) - 2) gammaRMSg = Graph(len(gammaRMS) - 2) gausYieldg = Graph(len(gausYield) - 2) gammaYieldg = Graph(len(gammaYield) - 2) for h, he, g in zip((gausYield, gammaYield), (gausYielde, gammaYielde), (gausYieldg, gammaYieldg)): for x, xe, a, e, i in zip(jetPtCenter[2:], jetPtErrors[2:], h[2:], he[2:], range(len(gausRMS) - 2)): g.SetPoint(i, x, a) g.SetPointError(i, xe, xe, e, e) for a, b, c, d, e, f, i in zip(gausRMS[2:], gammaRMS[2:], gausRMSe[2:], gammaRMSe[2:], jetPtCenter[2:], jetPtErrors[2:], range(len(gausRMS) - 2)): gausRMSg.SetPoint(i, e, a) gausRMSg.SetPointError(i, f, f, c, c) gammaRMSg.SetPoint(i, e, b) gammaRMSg.SetPointError(i, f, f, d, d) FullJets_gausRMS.append(gausRMSg) FullJets_gammaRMS.append(gammaRMSg) FullJets_gausYield.append(gausYieldg) FullJets_gammaYield.append(gammaYieldg) FullJets_fit.append(fits) FullJets_parameters.append(parameters) if fileData is not None: FullJets_gausRMS.append(gGausRMSData) FullJets_gammaRMS.append(gGammaRMSData) FullJets_gausYield.append(gGausYieldData) FullJets_gammaYield.append(gGammaYieldData) fig, axs = plt.subplots(2, 1, figsize=(7, 7)) ax = axs[0] ax.set_xlim([0.1, 15]) ax.set_ylim([5e-6, 2e3]) ax.set_xlabel(r'$j_{T}\left(GeV/c\right)$', fontsize=labelsize) ax.set_ylabel(r'$\frac{1}{N_{jets}}\frac{dN}{j_{T}dj_{T}}$', fontsize=labelsize) ratios = [] ax.set_xscale('log') ax.set_yscale('log') for h, c, R in zip(FullJets_jT, (0, 1, 2, 3), Rs): h[6].SetMarkerColor(colors[c]) h[6].SetMarkerStyle(styles[c]) h[6].SetLineColor(colors[c]) ratio = h[6].Clone() ratio.Divide(FullJets_jT[1][6]) ratios.append(ratio) plot = rplt.errorbar(h[6], xerr=False, emptybins=False, label='R = {:.1f}'.format(R), axes=ax, fmt='+') line = plot.get_children()[0] line.set_markersize(mSize) if (styles[c] > 23): line.set_markerfacecolor('none') #line.set_markeredgecolor(color) line.set_color(colors[c]) ax.text( 0.15, 0.001, 'Pythia \n Full Jets\n' + r'Anti-$k_T$' + '\n' + r'$p_{{T,\mathrm{{jet}}}}$: {:02d}-{:02d} GeV/c'.format(60, 80), fontsize=10) handles, labels = ax.get_legend_handles_labels() handles = [ container.ErrorbarContainer(h, has_xerr=False, has_yerr=True) if isinstance(h, container.ErrorbarContainer) else h for h in handles ] ax.legend(handles, labels, loc='upper right', numpoints=1, prop={'family': 'monospace'}) #ax.legend(loc = 'upper right') ax.set_xlim([0.1, 15]) ax.set_ylim([5e-6, 2e3]) ax.grid(True) ax = axs[1] ax.grid(True) ax.set_xlabel(r'$j_{T}\left[GeV\right]$', fontsize=labelsize) ax.set_ylabel('Ratio', fontsize=labelsize) #Add x-axis labels for bottom row for ratio, c in zip(ratios, (0, 1, 2, 3)): #ratio.SetMarkerColor(c) #ratio.SetMarkerStyle(24) plot = rplt.errorbar(ratio, xerr=False, emptybins=False, axes=ax) line = plot.get_children()[0] line.set_markersize(mSize) if (styles[c] > 23): line.set_markerfacecolor('none') #line.set_markeredgecolor(color) line.set_color(colors[c]) ax.set_xlim([0.1, 15]) ax.set_ylim([0.1, 3]) ax.set_xscale('log') plt.tight_layout() plt.subplots_adjust(wspace=0, hspace=0) #Set space between subfigures to 0 plt.savefig("PythonFigures/RcomparisonSignalPt6080.pdf".format(file), format='pdf') #Save figure plt.show() #Draw figure on screen drawWithErrors2Combined(FullJets_gausRMS, FullJets_gammaRMS, 15, 500, 1, 0, 1.65, 0, r'jet $p_T (GeV/c)$', r'$\sqrt{\left<j_T^2\right>}$', 'Pythia', 'PythonFigures/RcomparisonRMS', separate=True) return drawWithErrors2Combined( FullJets_gausYield, FullJets_gammaYield, 15, 500, 1, 0, 10, 0, r'jet $p_T$', r'Yield', 'Pythia', 'PythonFigures/RcomparisonYield', ) ratios = [] for hists in FullJets_jT: if hists is not None: ratio = [] for h, true in zip(hists, FullJets_jT[1]): h2 = h.Clone() h2.Divide(true) ratio.append(h2) else: ratio = None ratios.append(ratio) fig, axs = defs.makegrid(4, 2, xlog=True, ylog=False, d=d, shareY=False) axs = axs.reshape(8) axs[4].set_ylabel("Ratio to R = 0.4", fontsize=labelsize) axs[7].set_ylabel("Ratio to R = 0.4", fontsize=labelsize) axs[1].text( 0.02, 0.005, 'Pythia\n' r'pPb $\sqrt{s_{NN}} = 5.02 \mathrm{TeV}$' '\n Full jets \n' r'Anti-$k_T$', fontsize=7 ) #Add text to second subfigure, first parameters are coordinates in the drawn scale/units for hists, R in zip(FullJets_jT, Rs): for jT, ax, i, pT in zip(hists[2:], axs[0:4], range(0, 9), jetPt[2:]): rplt.errorbar(jT, emptybins=False, xerr=False, label="R = {:.1f}".format(R), axes=ax, fmt='o') #Plot jT histogram, ax.text( 0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:' '\n' r' {:02d}-{:02d} GeV'.format(pT[0], pT[1])) ax.set_xlim([0.01, 20]) #Set x-axis limits ax.set_ylim([5e-4, 2e3]) #Set y-axis limits ax.set_yscale('log') ax.grid(True) for ratio in ratios: for r, ax in zip(ratio[2:], axs[4:8]): rplt.errorbar(r, axes=ax, emptybins=False, xerr=False) ax.set_xlim([0.01, 20]) ax.set_ylim([0.1, 3]) ax.grid(True) axs[0].legend(loc='lower left') plt.savefig("PythonFigures/RcomparisonSignal.pdf", format='pdf') #Save figure plt.show() #Draw figure on screen
# set the random seed ROOT.gRandom.SetSeed(42) np.random.seed(42) # points x = np.sort(np.random.random(10)) * 3500 y = np.random.random(10) # set style for ROOT set_style('ATLAS') # create graph graph = Graph(x.shape[0]) for i, (xx, yy) in enumerate(zip(x, y)): graph.SetPoint(i, xx, yy) # set visual attributes graph.linecolor = 'blue' graph.markercolor = 'blue' graph.xaxis.SetTitle("E_{T} [GeV]") graph.yaxis.SetTitle("d#sigma_{jet}/dE_{T,jet} [fb/GeV]") graph.xaxis.SetRangeUser(0, 3500) graph.yaxis.SetRangeUser(0, 1) # plot with ROOT canvas = Canvas() graph.Draw("APL") label = ROOT.TText(0.4, 0.8, "ROOT") label.SetTextFont(43)
def pvalue_plot(poi, pvalues, pad=None, xtitle='X', ytitle='P_{0}', linestyle=None, linecolor=None, yrange=None, verbose=False): """ Draw a pvalue plot Parameters ---------- poi : list List of POI values tested pvalues : list List of p-values or list of lists of p-values to overlay multiple p-value curves pad : Canvas or Pad, optional (default=None) Pad to draw onto. Create new pad if None. xtitle : str, optional (default='X') The x-axis label (POI name) ytitle : str, optional (default='P_{0}') The y-axis label linestyle : str or list, optional (default=None) Line style for the p-value graph or a list of linestyles for multiple p-value graphs. linecolor : str or list, optional (default=None) Line color for the p-value graph or a list of linestyles for multiple p-value graphs. Returns ------- pad : Canvas The pad. graphs : list of Graph The p-value graphs """ if not pvalues: raise ValueError("pvalues is empty") if not poi: raise ValueError("poi is empty") # determine if pvalues is list or list of lists if not isinstance(pvalues[0], (list, tuple)): pvalues = [pvalues] if linecolor is not None: if not isinstance(linecolor, list): linecolor = [linecolor] linecolor = cycle(linecolor) if linestyle is not None: if not isinstance(linestyle, list): linestyle = [linestyle] linestyle = cycle(linestyle) with preserve_current_canvas(): if pad is None: pad = Canvas() pad.cd() pad.SetLogy() # create the axis min_poi, max_poi = min(poi), max(poi) haxis = Hist(1000, min_poi, max_poi) xaxis = haxis.xaxis yaxis = haxis.yaxis xaxis.SetRangeUser(min_poi, max_poi) haxis.Draw('AXIS') min_pvalue = float('inf') graphs = [] for ipv, pv in enumerate(pvalues): graph = Graph(len(poi), linestyle='dashed', drawstyle='L', linewidth=2) for idx, (point, pvalue) in enumerate(zip(poi, pv)): graph.SetPoint(idx, point, pvalue) if linestyle is not None: graph.linestyle = linestyle.next() if linecolor is not None: graph.linecolor = linecolor.next() graphs.append(graph) curr_min_pvalue = min(pv) if curr_min_pvalue < min_pvalue: min_pvalue = curr_min_pvalue if verbose: for graph in graphs: log.info(['{0:1.1f}'.format(xval) for xval in list(graph.x())]) log.info(['{0:0.3f}'.format(yval) for yval in list(graph.y())]) # automatically handles axis limits axes, bounds = draw(graphs, pad=pad, same=True, logy=True, xtitle=xtitle, ytitle=ytitle, xaxis=xaxis, yaxis=yaxis, ypadding=(0.2, 0.1), logy_crop_value=1E-300) if yrange is not None: xaxis, yaxis = axes yaxis.SetLimits(*yrange) yaxis.SetRangeUser(*yrange) min_pvalue = yrange[0] # draw sigma levels up to minimum of pvalues line = Line() line.SetLineStyle(2) line.SetLineColor(2) latex = ROOT.TLatex() latex.SetNDC(False) latex.SetTextSize(20) latex.SetTextColor(2) sigma = 0 while True: pvalue = gaussian_cdf_c(sigma) if pvalue < min_pvalue: break keepalive( pad, latex.DrawLatex(max_poi, pvalue, " {0}#sigma".format(sigma))) keepalive(pad, line.DrawLine(min_poi, pvalue, max_poi, pvalue)) sigma += 1 pad.RedrawAxis() pad.Update() return pad, graphs
_, entry = j print '[%d]' % i, entry idx = raw_input('which one should I use? ') idx = int(idx) _, to_use = matches[idx] print to_use.start.str, '-->', time.str points.append((to_use.start.time, time.time)) #linear fit from rootpy import ROOT ROOT.gROOT.SetBatch() from rootpy.plotting import Graph, F1, Canvas fcn = F1(args.fitfunc) graph = Graph(len(points)) for idx, point in enumerate(points): x, y = point graph.SetPoint(idx, x, y) graph.fit(fcn) canvas = Canvas() graph.Draw() canvas.SaveAs("shifts.png") with open(args.out, 'w') as out: for i, entry in enumerate(entries): entry.remap(fcn) out.write('%d\n' % i) out.write('%s\n\n' % entry.string)
'/storage/TopQuarkGroup/unfolding/unfolding_merged_sub1.root', 'read') h_truth_finebinned = inputFile.unfoldingAnalyserElectronChannel.truth h_truth = asrootpy( inputFile.unfoldingAnalyserElectronChannel.truth.Rebin( nbins, 'truth_new', bins)) print 'old:', get_bin_centers(bins) new_centers = barycenters(h_truth_finebinned, h_truth) print 'centre of mass:', new_centers new_centers = calculate_correct_x_coordinates(h_truth_finebinned, bins) print 'correct:', new_centers data = list(h_truth.y()) h_truth_new = Hist(new_centers) bin_widths = [25, 20, 25, 30, 1000] g_truth_new = Graph(len(new_centers)) for i, (x, y, width) in enumerate(zip(new_centers, data, bin_widths)): g_truth_new.SetPoint(i, x, y / width) error = h_truth.GetBinError(i + 1) g_truth_new.SetPointError(i, 0, 0, error, error) for bin_i in range(len(data)): h_truth_new.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i]) h_truth.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i]) h_truth_finebinned.SetFillStyle(0) h_truth_finebinned.Smooth(500) x, y = list(h_truth_finebinned.x()), list(h_truth_finebinned.y()) bin_edges = np.array(list(h_truth_finebinned.xedges())) bincenters = 0.5 * (bin_edges[1:] + bin_edges[:-1]) g_truth = Graph(h_truth) # g_truth_new = Graph(len(h_truth), h_truth_new) g_truth_new.SetLineColor('red')
def main(): JetPtBins = [5, 10, 20, 30, 40, 60, 80, 100, 150, 500] jetPtBins2 = [(JetPtBins[i], JetPtBins[i + 1]) for i in range(8)] #JetPtCenter = [7.5,15,25,35,50,70,90,125,325] JetPtCenter = [ 6.5, 12.45, 23.34, 33.83, 46.75, 67.73, 88.01, 116.11, 194.61 ] LeadPtMode = [2.0, 3.0, 5.6, 8.9, 9.9, 14.8, 20.7, 26.0, 34.6] LeadPtMean = [2.35, 3.72, 6.66, 9.59, 13.58, 17.98, 23.27, 27.55, 31.68] LeadPtError = [0.93, 1.69, 3.18, 4.43, 6.74, 8.34, 9.68, 10.27, 10.55] JetPtError = [2.5, 5, 5, 5, 10, 10, 10, 25, 175] JetPtLeadPtG = Graph( len(JetPtCenter)) #Gives jet pT as a function of leading pT JetPtLeadPtGerr = Graph(len(JetPtCenter)) LeadPtJetPtG = Graph(len(JetPtCenter)) LeadPtJetPtGerr = Graph(len(JetPtCenter)) for i, (x, y, e) in enumerate(zip(LeadPtMean, JetPtCenter, JetPtError)): JetPtLeadPtG.SetPoint(i, x, y) JetPtLeadPtGerr.SetPoint(i, x, e) for i, (x, y, e) in enumerate(zip(JetPtCenter, LeadPtMean, LeadPtError)): LeadPtJetPtG.SetPoint(i, x, y) LeadPtJetPtGerr.SetPoint(i, x, e) Njets = 8 topcomment = "_systematics_Triggered" finderName = [ "Full jets, Anti-k_\mathrm{T} R = 0.4", "Charged Jets, Anti-k_\mathrm{T} R = 0.4" ] finderType = ["Full", "Charged"] setTitle = ["0", "1", "2", "3", "4", "5"] finderR = {4, 4} iC = 0 logx = 1 doWeight = 1 mSize = 0.3 iS = 0 f = root_open("RootFiles/jtSystematics.root", 'read') f2 = root_open("RootFiles/dihadronjTFinalGraphs.root", 'read') gGausRMS = f.Get("gGausRMS{:02d}".format(iS)) gGausRMSerr = f.Get("gGausRMS{:02d}_Systematics".format(iS)) gGausYield = f.Get("gGausYield{:02d}".format(iS)) gGausYielderr = f.Get("gGausYield{:02d}_Systematics".format(iS)) gGammaRMS = f.Get("gGammaRMS{:02d}".format(iS)) gGammaRMSerr = f.Get("gGammaRMS{:02d}_Systematics".format(iS)) gGammaYield = f.Get("gGammaYield{:02d}".format(iS)) gGammaYielderr = f.Get("gGammaYield{:02d}_Systematics".format(iS)) gGausRMS.Print() for g in (gGausRMS, gGausRMSerr, gGausYield, gGausYielderr, gGammaRMS, gGammaRMSerr, gGammaYield, gGammaYielderr): n = g.GetN() xs = g.GetX() ys = g.GetY() for i, x, y, jetpt in zip(range(n), xs, ys, JetPtCenter): if (i < 3): g.SetPoint(i, 0, 0) else: g.SetPoint(i, jetpt, y) gGausRMS.Print() g = gGausRMSerr n = g.GetN() xs = g.GetX() ys = g.GetY() xerrs = g.GetEX() yerrs = g.GetEY() for i, x, y, xerr, yerr in zip(range(n), xs, ys, xerrs, yerrs): if (y > 0 and yerr / y > 0.13): yerr = 0.13 * y if (y > 0 and yerr / y < 0.09): yerr = 0.09 * y g.SetPointError(i, xerr, yerr) g = gGammaRMSerr n = g.GetN() xs = g.GetX() ys = g.GetY() xerrs = g.GetEX() yerrs = g.GetEY() for i, x, y, xerr, yerr in zip(range(n), xs, ys, xerrs, yerrs): if (y > 0 and yerr / y > 0.13): yerr = 0.13 * y if (y > 0 and yerr / y < 0.10): yerr = 0.08 * y g.SetPointError(i, xerr, yerr) iSPythia = 3 gGausRMSPythia = f.Get("gGausRMS{:02d}".format(iSPythia)) gGausYieldPythia = f.Get("gGausYield{:02d}".format(iSPythia)) gGammaRMSPythia = f.Get("gGammaRMS{:02d}".format(iSPythia)) gGammaYieldPythia = f.Get("gGammaYield{:02d}".format(iSPythia)) gGausRMSPythia.Print() for g in (gGausRMSPythia, gGausYieldPythia, gGammaRMSPythia, gGammaYieldPythia): n = g.GetN() xs = g.GetX() ys = g.GetY() for i, x, y, jetpt in zip(range(n), xs, ys, JetPtCenter): if (i < 3): g.SetPoint(i, 0, 0) else: g.SetPoint(i, jetpt, y) gGausRMSPythia.Print() gGausRMSJussi = f2.Get( "systematicError_RMSNarrow_p-Pb_5.02TeV_0.2<xlong<0.4") gGammaRMSJussi = f2.Get( "systematicError_RMSWide_p-Pb_5.02TeV_0.2<xlong<0.4") doWhat = False n = gGausRMS.GetN() xs = gGausRMSerr.GetX() gGausRMS2 = gGausRMS.Clone() gGausRMSerr2 = gGausRMSerr.Clone() gGausYield2 = gGausYield.Clone() gGausYielderr2 = gGausYielderr.Clone() gGammaRMS2 = gGammaRMS.Clone() gGammaRMSerr2 = gGammaRMSerr.Clone() gGammaYield2 = gGammaYield.Clone() gGammaYielderr2 = gGammaYielderr.Clone() gGausRMSPythia2 = gGausRMSPythia.Clone() gGausYieldPythia2 = gGausYieldPythia.Clone() gGammaRMSPythia2 = gGammaRMSPythia.Clone() gGammaYieldPythia2 = gGammaYieldPythia.Clone() for g in (gGausRMS2, gGausRMSerr2, gGausYield2, gGausYielderr2, gGammaRMS2, gGammaRMSerr2, gGammaYield2, gGammaYielderr2, gGausRMSPythia2, gGausYieldPythia2, gGammaRMSPythia2, gGammaYieldPythia2): n = g.GetN() xs = g.GetX() ys = g.GetY() xerrs = g.GetEX() yerrs = g.GetEY() for i, x, y, xerr, yerr in zip(range(n), xs, ys, xerrs, yerrs): g.SetPoint(i, LeadPtMean[i], y) g.SetPointError(i, LeadPtError[i], yerr) gGausRMSJussi2 = gGausRMSJussi.Clone() gGammaRMSJussi2 = gGammaRMSJussi.Clone() for g in (gGausRMSJussi2, gGammaRMSJussi2): n = g.GetN() xs = g.GetX() ys = g.GetY() xerrs = g.GetEX() yerrs = g.GetEY() for i, x, y, xerr, yerr in zip(range(n), xs, ys, xerrs, yerrs): print("Trigger pT: {}".format(x)) x1 = JetPtLeadPtG.Eval(x) x1e = JetPtLeadPtGerr.Eval(x) print("Estimated jet pT: {}".format(x1)) g.SetPoint(i, x1, y) g.SetPointError(i, x1e, yerr) Pythia = dataset("Pythia8 4C", NFIN=0, range=(2, 8), filename="RootFiles/Grid_Monash.root", directory='/JCDijetBaseTask/jcdijet', color=colors[1], style=24, rebin=Rebin) Pythia2 = dataset("Pythia8 Monash", NFIN=0, range=(2, 8), filename="RootFiles/Grid_Tune4c.root", directory='/JCDijetBaseTask/jcdijet', color=colors[2], style=24, rebin=Rebin) #Herwig = dataset("Herwig 7.0",NFIN=0,range=(4,5),filename="RootFiles/Herwig7.root",directory='/JJetJt',color=colors[3],style=24,rebin=Rebin) #Pythia_ALICE = dataset("ALICE Pythia6 Perugia2011",NFIN=0,range=(1,8),filename="CF_pPb_MC_legotrain/legotrain_610_20181010-1926_LHCb4_fix_CF_pPb_MC_ptHardMerged.root",directory='AliJJetJtTask/AliJJetJtHistManager',color=colors[4],style=24,rebin=Rebin) #datasets = [Pythia] #inclusive,jetPt = Pythia.getHist('JetConeJtWeightBin',jetpt = True) #datasets.append(Mixed_FullJets_R04) inclusive, jetPt = Pythia.getHist('JetConeJtWeightBin', jetpt=True) datasets = [Pythia] incs = [inclusive] datasets.append(Pythia2) #datasets.append(Herwig) for data in datasets[1:]: incs.append(data.getHist('JetConeJtWeightBin', jetpt=False)) names = [data.name() for data in datasets] signals = [ data.getSubtracted('JetConeJtWeightBin', 'BgJtWeightBin', jetpt=False) for data in datasets ] graphs = [data.getGraphs() for data in datasets] gausRMS = [x[0] for x in graphs] gammaRMS = [x[1] for x in graphs] gausYield = [x[2] for x in graphs] gammaYield = [x[3] for x in graphs] for graphs in (gausRMS, gammaRMS, gausYield, gammaYield): for g in graphs: n = g.GetN() xs = g.GetX() ys = g.GetY() for i, x, y, jetpt in zip(range(n), xs, ys, JetPtCenter[4:]): g.SetPoint(i, jetpt, y) gausRMS[0].Print() #pythiaN = [(gGausRMSPythia,"Pythia6"),(gausRMS[0],"Pythia8 4C"),(gausRMS[1],"Pythia8 Monash"),(gausRMS[2],"Herwig 7.0")] #pythiaW = [(gGammaRMSPythia,"Pythia6"),(gammaRMS[0],"Pythia8 4C"),(gammaRMS[1],"Pythia8 Monash"),(gammaRMS[2],"Herwig 7.0")] pythiaN = [(gausRMS[0], "Pythia8 4C"), (gausRMS[1], "Pythia8 Monash")] pythiaW = [(gammaRMS[0], "Pythia8 4C"), (gammaRMS[1], "Pythia8 Monash")] #Fig 3, NArrow and Wide RMS without Pythia drawWithErrors2Combined(gGausRMS, gGausRMSerr, gGammaRMS, gGammaRMSerr, 35, 135, 0, 0, 1.5, 0, r'$p_\mathrm{T,jet}$ (GeV/c)', r'$\sqrt{\left<j_\mathrm{T}^{2}\right>}$ (GeV/c)', "RMS", "_triggered", "PythonFigures/RMSWithSystematics", 1, -1, wideE=0.041, narrowE=0.051) #Fig 3, NArrow and Wide RMS with Pythia Comparison drawWithErrors2Combined(gGausRMS, gGausRMSerr, gGammaRMS, gGammaRMSerr, 35, 135, 0, 0, 1.9, 0, r'$p_\mathrm{T,jet}$ (GeV/c)', r'$\sqrt{\left<j_\mathrm{T}^{2}\right>}$ (GeV/c)', "", "_triggered", "PythonFigures/RMSWithSystematics_Pythia", 1, -1, pythiaN=pythiaN, pythiaW=pythiaW, wideE=0.041, narrowE=0.051, titleLoc=(95, 1.5)) #Fig 5 with pT,trigger on X-axis drawWithErrors2Combined( gGausRMS2, gGausRMSerr2, gGammaRMS2, gGammaRMSerr2, 0, 50, 0, 0, 2.2, 0, r'$p_\mathrm{T,trigger}$ (GeV/c)', r'$\sqrt{\left<j_\mathrm{T}^{2}\right>}$ (GeV/c)', "", "_triggered", "PythonFigures/RMSWithSystematics_DihadronTriggerPt", 1, -1, jussiN=gGausRMSJussi, jussiW=gGammaRMSJussi, wideE=0.041, narrowE=0.051) #Fig 5 with pT,jet on X-axis drawWithErrors2Combined(gGausRMS, gGausRMSerr, gGammaRMS, gGammaRMSerr, 1, 135, 0, 0, 2.2, 0, r'$p_\mathrm{T,jet}$ (GeV/c)', r'$\sqrt{\left<j_\mathrm{T}^{2}\right>}$ (GeV/c)', "", "_triggered", "PythonFigures/RMSWithSystematics_DihadronJetPt", 1, -1, jussiN=gGausRMSJussi2, jussiW=gGammaRMSJussi2, wideE=0.041, narrowE=0.051)
def main(args): fileList = glob('/data/nawoods/lepsForSIP/*.root') files = {int(f.split('_M')[1].split('.')[0]) : f for f in fileList} checkers = {m : MuonSIPChecker('m={}'.format(m), [f]) for m,f in files.iteritems()} sipRMS = Graph(len(fileList), type='errors') sipHists = [] dxyRMS = Graph(len(fileList), type='errors') dxyHists = [] dzRMS = Graph(len(fileList), type='errors') dzHists = [] ipHists = [] ipErrHists = [] fracFailing = Graph(len(fileList), type='errors') for i, m in enumerate(sorted(files.keys())): checkers[m].processSample() checkers[m].hists['sip'].Sumw2() sipRMS.SetPoint(i, float(m), checkers[m].hists['sip'].GetRMS()) sipRMS.SetPointError(i, 0., checkers[m].hists['sip'].GetRMSError()) sipHists.append(checkers[m].hists['sip']) sipHists[-1].color = getColor(m) sipHists[-1].title = "m_{{H}} = {}".format(m) sipHists[-1].drawstyle = 'hist' sipHists[-1].legendstyle = 'L' sipHists[-1].linewidth = 2 sipHists[-1].scale(1./sipHists[-1].integral()) ipHists.append(checkers[m].hists['ip']) ipHists[-1].color = getColor(m) ipHists[-1].title = "m_{{H}} = {}".format(m) ipHists[-1].drawstyle = 'hist' ipHists[-1].legendstyle = 'L' ipHists[-1].linewidth = 2 ipHists[-1].scale(1./ipHists[-1].integral()) ipErrHists.append(checkers[m].hists['ipErr']) ipErrHists[-1].color = getColor(m) ipErrHists[-1].title = "m_{{H}} = {}".format(m) ipErrHists[-1].drawstyle = 'hist' ipErrHists[-1].legendstyle = 'L' ipErrHists[-1].linewidth = 2 ipErrHists[-1].scale(1./ipErrHists[-1].integral()) checkers[m].hists['dxy'].Sumw2() dxyRMS.SetPoint(i, float(m), checkers[m].hists['dxy'].GetRMS()) dxyRMS.SetPointError(i, 0., checkers[m].hists['dxy'].GetRMSError()) dxyHists.append(checkers[m].hists['dxy']) dxyHists[-1].color = getColor(m) dxyHists[-1].title = "m_{{H}} = {}".format(m) dxyHists[-1].drawstyle = 'hist' dxyHists[-1].legendstyle = 'L' dxyHists[-1].linewidth = 2 dxyHists[-1].scale(1./dxyHists[-1].integral()) checkers[m].hists['dz'].Sumw2() dzRMS.SetPoint(i, float(m), checkers[m].hists['dz'].GetRMS()) dzRMS.SetPointError(i, 0., checkers[m].hists['dz'].GetRMSError()) dzHists.append(checkers[m].hists['dz']) dzHists[-1].color = getColor(m) dzHists[-1].title = "m_{{H}} = {}".format(m) dzHists[-1].drawstyle = 'hist' dzHists[-1].legendstyle = 'L' dzHists[-1].linewidth = 2 dzHists[-1].scale(1./dzHists[-1].integral()) fracFailing.SetPoint(i, float(m), 1. - float(checkers[m].nPassSIP) / checkers[m].nTot) cSIP = Canvas(1000,1000) draw(sipHists, cSIP, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}', ytitle='arb.') legSIP = Legend(sipHists, cSIP, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04) legSIP.Draw("same") cSIP.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sips.png') cSIPLog = Canvas(1000,1000) draw(sipHists, cSIPLog, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}', ytitle='arb.', logy=True) legSIPLog = Legend(sipHists, cSIPLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03) legSIPLog.Draw("same") cSIPLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sipsLog.png') cSIPRMS = Canvas(1000, 1000) sipRMS.color = 'b' sipRMS.drawstyle = 'PE' sipRMS.legendstyle = 'PE' draw(sipRMS, cSIPRMS, xtitle="m_{H}", ytitle="RMS(SIP_{3D})", xlimits=(0.,2600.)) cSIPRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sipRMS.png') cIP = Canvas(1000,1000) draw(ipHists, cIP, xtitle='IP_{3D}', ytitle='arb.') legIP = Legend(ipHists, cIP, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04) legIP.Draw("same") cIP.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ips.png') cIPLog = Canvas(1000,1000) draw(ipHists, cIPLog, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}', ytitle='arb.', logy=True) legIPLog = Legend(ipHists, cIPLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03) legIPLog.Draw("same") cIPLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipsLog.png') cIPErr = Canvas(1000,1000) draw(ipErrHists, cIPErr, xtitle='#sigma_{IP_{3D}}', ytitle='arb.') legIPErr = Legend(ipErrHists, cIPErr, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04) legIPErr.Draw("same") cIPErr.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipErrs.png') cIPErrLog = Canvas(1000,1000) draw(ipErrHists, cIPErrLog, xtitle='#sigma_{IP_{3D}}', ytitle='arb.', logy=True) legIPErrLog = Legend(ipErrHists, cIPErrLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03) legIPErrLog.Draw("same") cIPErrLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipErrsLog.png') cFail = Canvas(1000, 1000) fracFailing.color = 'b' fracFailing.drawstyle = 'PE' fracFailing.legendstyle = 'PE' draw(fracFailing, cSIPRMS, xtitle="m_{H}", ytitle="Fraction failing SIP", xlimits=(0.,2600.)) cSIPRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/fracFailing.png') cDXY = Canvas(1000,1000) draw(dxyHists, cDXY, xtitle='#Delta_{xy}', ytitle='arb.') legDXY = Legend(dxyHists, cDXY, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04) legDXY.Draw("same") cDXY.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dxys.png') cDXYRMS = Canvas(1000, 1000) dxyRMS.color = 'b' dxyRMS.drawstyle = 'PE' dxyRMS.legendstyle = 'PE' draw(dxyRMS, cDXYRMS, xtitle="m_{H}", ytitle="RMS(#Delta_{xy})", xlimits=(0.,2600.)) cDXYRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dxyRMS.png') cDZ = Canvas(1000,1000) draw(dzHists, cDZ, xtitle='#Delta_{z}', ytitle='arb.') legDZ = Legend(dzHists, cDZ, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04) legDZ.Draw("same") cDZ.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dzs.png') cDZRMS = Canvas(1000, 1000) dzRMS.color = 'b' dzRMS.drawstyle = 'PE' dzRMS.legendstyle = 'PE' draw(dzRMS, cDZRMS, xtitle="m_{H}", ytitle="RMS(#Delta_{z})", xlimits=(0.,2600.)) cDZRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dzRMS.png')
def main(): print('Number of arguments: ', len(sys.argv), 'arguments.') print('Argument list:', str(sys.argv)) filename = "rootFiles/legotrain_CF_pPb_2305_20190109_LHC13bcde_minimal.root" separate = 0 start = 2 end = 6 n_figs = end - start Mixed_FullJets_R04 = datasetMixed( "Full jets R=0.4", NFIN=0, range=(1, 5), filename=filename, directory='AliJJetJtTask/AliJJetJtHistManager', directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager', color=2, style=24, rebin=2) compareHistsWithRatio( Mixed_FullJets_R04, ['JtWeightBin', 'JtWeightLeadingRefBin', 'JtWeightLeadingRefBin'], [ 'Jet axis ref.', 'leading ref. (xlong 0.0-0.2)', 'leading ref. (xlong 0.2-0.4)' ], step=1, start=1, extras=['', 'Xlong00', 'Xlong01']) plt.savefig("PythonFigures/JetVsLeadingRefConst.pdf", format='pdf') #Save figure plt.show() sets = compareHistsWithRatio( Mixed_FullJets_R04, [ 'JetConeJtWeightBin', 'JetConeJtWeightLeadingRefBin', 'JetConeJtWeightLeadingRefBin', 'JetConeJtWeightLeadingRefBin', 'JetConeJtWeightLeadingRefBin' ], [ 'Jet axis ref.', 'leading ref.(xlong 0.0-0.2)', 'leading ref.(xlong 0.2-0.4)', 'leading ref.(xlong 0.4-0.6)', 'leading ref. (xlong 0.6-1.0)' ], step=1, extras=['', 'Xlong00', 'Xlong01', 'Xlong02', 'Xlong03']) plt.savefig("PythonFigures/JetVsLeadingRefJetCone.pdf", format='pdf') #Save figure plt.show() JtJet = sets[0][0] JtLeadingxlong00 = sets[1][0] JtLeadingxlong01 = sets[2][0] JtLeadingxlong02 = sets[3][0] JtLeadingxlong03 = sets[4][0] JtLeading = [h.clone() for h in sets[1][0]] for h, s, s2, s3 in zip(JtLeading, sets[2][0], sets[3][0], sets[4][0]): h.Add(s, 1) h.Add(s2, 1) h.Add(s3, 1) jetPt = sets[0][1] jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt]) jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt]) FullJets_fit = [] FullJets_parameters = [] FullJets_gausRMS = [] FullJets_gammaRMS = [] FullJets_gausYield = [] FullJets_gammaYield = [] for jT, title in zip( (JtJet, JtLeading, JtLeadingxlong00, JtLeadingxlong01, JtLeadingxlong02), ("Jet ref.", "Leading ref", "Leading ref.(xlong 0.0-0.2)", "Leading ref.(xlong 0.2-0.4)", "Leading ref.(xlong 0.4-0.6)", "Leading ref.(xlong 0.6-1.0)")): gausRMS = [] gammaRMS = [] gausRMSe = [] gammaRMSe = [] gausYield = [] gammaYield = [] gausYielde = [] gammaYielde = [] fits = [] parameters = [] for h, i in zip(jT, range(Njets)): fit, d = defs.fitJtHisto(h, '', 1, i, 8, title, draw=False) fits.append(fit) parameters.append(d) gausRMS.append(d['gausRMS']) gausRMSe.append(d['gausRMSe']) gammaRMS.append(d['gammaRMS']) gammaRMSe.append(d['gammaRMSe']) gausYield.append(d['gausYield']) gausYielde.append(d['gausYielde']) gammaYield.append(d['gammaYield']) gammaYielde.append(d['gammaYielde']) gausRMSg = Graph(len(gausRMS) - 2) gammaRMSg = Graph(len(gammaRMS) - 2) gausYieldg = Graph(len(gausYield) - 2) gammaYieldg = Graph(len(gammaYield) - 2) for h, he, g in zip((gausYield, gammaYield), (gausYielde, gammaYielde), (gausYieldg, gammaYieldg)): for x, xe, a, e, i in zip(jetPtCenter[2:], jetPtErrors[2:], h[2:], he[2:], range(len(gausRMS) - 2)): g.SetPoint(i, x, a) g.SetPointError(i, xe, xe, e, e) for a, b, c, d, e, f, i in zip(gausRMS[2:], gammaRMS[2:], gausRMSe[2:], gammaRMSe[2:], jetPtCenter[2:], jetPtErrors[2:], range(len(gausRMS) - 2)): gausRMSg.SetPoint(i, e, a) gausRMSg.SetPointError(i, f, f, c, c) gammaRMSg.SetPoint(i, e, b) gammaRMSg.SetPointError(i, f, f, d, d) FullJets_gausRMS.append(gausRMSg) FullJets_gammaRMS.append(gammaRMSg) FullJets_gausYield.append(gausYieldg) FullJets_gammaYield.append(gammaYieldg) FullJets_fit.append(fits) FullJets_parameters.append(parameters) print(gausRMS[2:]) print(gammaRMS[2:]) print(jetPtCenter[2:]) drawWithErrors2Combined(FullJets_gausRMS, FullJets_gammaRMS, [ "Jet ref.", "Leading ref.", "Leading ref.(xlong 0.0-0.2)", "Leading ref.(xlong 0.2-0.4)", "Leading ref.(xlong 0.4-0.6)" ], 15, 500, 1, 0, 1.85, 0, r'jet $p_T$', r'$\sqrt{\left<j_T^2\right>}$', 'Pythia', 'PythonFigures/JetVsLeadingRefJetConeFits') if (separate > 0): fig = plt.figure(1) ax = fig.add_subplot(1, 1, 1) ax.set_xscale('log') ax.set_yscale('log') ax.text(0.2, 0.0005, d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] + '\n Jet Cone', fontsize=7) rplt.errorbar(signal[separate], xerr=False, emptybins=False, axes=ax, label="Jet axis reference", fmt='o') #Plot jT histogram, rplt.errorbar(signal2[separate], xerr=False, emptybins=False, axes=ax, label="Leading track reference", fmt='o') ax.text( 0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:' '\n' r' {:02d}-{:02d} GeV'.format(jetPt[separate][0], jetPt[separate][1])) ax.set_xlim([0.1, 12]) ax.set_ylim([5e-6, 1.5e3]) ax.legend(loc='lower left') plt.savefig( "PythonFigures/MixedFullJetsR04JetConeJtLeadingRefJetPt{0}.pdf". format(separate), format='pdf') #Save figure plt.show() #Draw figure on screen else: n_rows = n_figs // 4 print(n_rows) fig, axs = defs.makegrid(4, 2, xlog=True, ylog=True, d=d, shareY=False, figsize=(10, 5)) axs = axs.reshape(8) #axs[1].text(0.12,0.002,d['system'] +'\n'+ d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7) ratios = [] for jT, jT2, pT, ax, i in zip(JtJet[start:], JtLeading[start:], jetPt[start:], axs[0:4], range(0, 9)): jT.SetMarkerColor(1) jT.SetMarkerStyle(24) jT.SetLineColor(1) #jT.SetMarkerSize(mSize) jT2.SetMarkerColor(2) jT2.SetMarkerStyle(25) #jT2.SetMarkerSize(mSize) jT2.SetLineColor(2) ratio = jT2.Clone() ratio.Divide(jT) ratios.append(ratio) plot = rplt.errorbar(jT, xerr=False, emptybins=False, axes=ax, label="Jet axis reference", fmt='o', fillstyle='none', ecolor='black') #Plot jT histogram, line = plot.get_children()[0] line.set_markersize(mSize) line.set_markerfacecolor('none') plot = rplt.errorbar(jT2, xerr=False, emptybins=False, axes=ax, label="Leading track reference", fmt='o', fillstyle='none', ecolor='red') #Plot jT histogram, line = plot.get_children()[0] line.set_markersize(mSize) line.set_markerfacecolor('none') #line.set_color(color) ax.text( 0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:' '\n' r' {:02d}-{:02d} GeV'.format(pT[0], pT[1])) ax.set_xlim([0.1, 22]) #Set x-axis limits ax.set_ylim([5e-5, 2e3]) #Set y-axis limits ax.set_xticklabels(ax.get_xticklabels(), horizontalalignment='left') for ratio, ax, i in zip(ratios, axs[4:], range(0, 9)): plot = rplt.errorbar(ratio, xerr=False, emptybins=False, axes=ax, fmt='o', fillstyle='none', ecolor='black') #Plot jT histogram, line = plot.get_children()[0] line.set_markersize(mSize) line.set_markerfacecolor('none') ax.set_yscale('linear') ax.set_xlim([0.1, 22]) #Set x-axis limits ax.set_ylim([0, 5]) #Set y-axis limits handles, labels = axs[0].get_legend_handles_labels() handles = [ container.ErrorbarContainer(h, has_xerr=False, has_yerr=True) if isinstance(h, container.ErrorbarContainer) else h for h in handles ] axs[0].legend(handles, labels, loc='lower left', numpoints=1) axs[4].set_ylabel('Ratio') axs[7].set_ylabel('Ratio') plt.savefig( "PythonFigures/MixedFullJetsR04JetConeJtLeadingRefPtFrom{}To{}.pdf" .format(start, end), format='pdf') #Save figure plt.show() #Draw figure on screen
def draw_to_canvas(self): """ Draw this figure to a canvas, which is then returned. """ if len(self._plottables) == 0: raise IndexError("No plottables defined") c = Canvas(width=self.style.canvasWidth, height=self.style.canvasHeight, size_includes_decorations=True) if self.legend.position == 'seperate': legend_width = .2 pad_legend = Pad(1 - legend_width, 0, 1., 1., name="legend") pad_legend.SetLeftMargin(0.0) pad_legend.SetFillStyle(0) # make this pad transparent pad_legend.Draw() else: legend_width = 0 pad_plot = Pad( 0., 0., 1 - legend_width, 1., name="plot", ) pad_plot.SetMargin(*self.style.plot_margins) pad_plot.Draw() pad_plot.cd() # awkward hack around a bug in get limits where everything fails if one plottable is shitty... xmin, xmax, ymin, ymax = None, None, None, None for pdic in self._plottables: try: limits = get_limits(pdic['p'], logx=self.plot.logx, logy=self.plot.logy) # Beware: Python 2 evaluates min/max of None in an undefined way with no error! Wow... xmin = min([xmin, limits[0] ]) if xmin is not None else limits[0] xmax = max([xmax, limits[1] ]) if xmax is not None else limits[1] ymin = min([ymin, limits[2] ]) if ymin is not None else limits[2] ymax = max([ymax, limits[3] ]) if ymax is not None else limits[3] except (TypeError, ValueError): # some plottables do not work with this rootpy function (eg. graph without points, tf1) # TODO: should be fixed upstream pass # overwrite these ranges if defaults are given if self.plot.xmin is not None: xmin = self.plot.xmin if self.plot.xmax is not None: xmax = self.plot.xmax if self.plot.ymax is not None: ymax = self.plot.ymax if self.plot.ymin is not None: ymin = self.plot.ymin if not all([val is not None for val in [xmin, xmax, ymin, ymax]]): raise TypeError( "unable to determine plot axes ranges from the given plottables" ) colors = get_color_generator(self.plot.palette, self.plot.palette_ncolors) # draw an empty frame within the given ranges; frame_from_plottable = [ p for p in self._plottables if p.get('use_as_frame') ] if len(frame_from_plottable) > 0: frame = frame_from_plottable[0]['p'].Clone('__frame') frame.Reset() frame.SetStats(0) frame.xaxis.SetRangeUser(xmin, xmax) frame.yaxis.SetRangeUser(ymin, ymax) frame.GetXaxis().SetTitle(self.xtitle) frame.GetYaxis().SetTitle(self.ytitle) self._theme_plottable(frame) frame.Draw() else: frame = Graph() frame.SetName("__frame") # add a silly point in order to have root draw this frame... frame.SetPoint(0, 0, 0) frame.GetXaxis().SetLimits(xmin, xmax) frame.GetYaxis().SetLimits(ymin, ymax) frame.SetMinimum(ymin) frame.SetMaximum(ymax) frame.GetXaxis().SetTitle(self.xtitle) frame.GetYaxis().SetTitle(self.ytitle) self._theme_plottable(frame) # Draw this frame: 'A' should draw the axis, but does not work if nothing else is drawn. # L would draw a line between the points but is seems to do nothing if only one point is present # P would also draw that silly point but we don't want that! frame.Draw("AL") xtick_length = frame.GetXaxis().GetTickLength() ytick_length = frame.GetYaxis().GetTickLength() for i, pdic in enumerate(self._plottables): obj = pdic['p'] if isinstance(obj, ROOT.TLegendEntry): _root_color = Color(pdic['color']) _root_markerstyle = MarkerStyle(pdic['markerstyle']) obj.SetMarkerStyle(_root_markerstyle('root')) obj.SetMarkerColor(_root_color('root')) elif isinstance(obj, (ROOT.TH1, ROOT.TGraph, ROOT.TF1)): self._theme_plottable(obj) obj.SetMarkerStyle(pdic.get('markerstyle', 'circle')) if pdic.get('color', None): obj.color = pdic['color'] else: try: color = next(colors) except StopIteration: log.warning("Ran out of colors; defaulting to black") color = 1 obj.color = color xaxis = obj.GetXaxis() yaxis = obj.GetYaxis() # Set the title to the given title: obj.title = self.title # the xaxis depends on the type of the plottable :P if isinstance(obj, ROOT.TGraph): # SetLimit on a TH1 is simply messing up the # lables of the axis to screw over the user, presumably... xaxis.SetLimits(xmin, xmax) yaxis.SetLimits(ymin, ymax) # for unbinned data # 'P' plots the current marker, 'L' would connect the dots with a simple line # see: https://root.cern.ch/doc/master/classTGraphPainter.html for more draw options drawoption = 'Psame' elif isinstance(obj, ROOT.TH1): obj.SetStats(0) xaxis.SetRangeUser(xmin, xmax) yaxis.SetRangeUser(ymin, ymax) drawoption = 'same' elif isinstance(obj, ROOT.TF1): # xaxis.SetLimits(xmin, xmax) # yaxis.SetLimits(ymin, ymax) # for unbinned data drawoption = 'same' obj.Draw(drawoption) # Its ok if obj is non; then we just add it to the legend. else: raise TypeError("Un-plottable type given.") pad_plot.SetTicks() pad_plot.SetLogx(self.plot.logx) pad_plot.SetLogy(self.plot.logy) pad_plot.SetGridx(self.plot.gridx) pad_plot.SetGridy(self.plot.gridy) # do we have legend titles? if any([pdic.get('legend_title') for pdic in self._plottables]): leg = self._create_legend() longest_label = 0 for pdic in self._plottables: if not pdic.get('legend_title', False): continue leg.AddEntry(pdic['p'], pdic['legend_title']) if len(pdic['legend_title']) > longest_label: longest_label = len(pdic['legend_title']) # Set the legend position # vertical: if self.legend.position.startswith('t'): leg_hight = leg.y2 - leg.y1 leg.y2 = 1 - pad_plot.GetTopMargin() - ytick_length leg.y1 = leg.y2 - leg_hight elif self.legend.position.startswith('b'): leg_hight = leg.y2 - leg.y1 leg.y1 = pad_plot.GetBottomMargin() + ytick_length leg.y2 = leg.y1 + leg_hight # horizontal: if self.legend.position[1:].startswith('l'): leg_width = 0.3 leg.x1 = pad_plot.GetLeftMargin() + xtick_length leg.x2 = leg.x1 + leg_width elif self.legend.position[1:].startswith('r'): leg_width = 0.3 leg.x2 = 1 - pad_plot.GetRightMargin() - xtick_length leg.x1 = leg.x2 - leg_width if self.legend.position == 'seperate': with pad_legend: leg.Draw() else: leg.Draw() if self.plot.logx: pad_plot.SetLogx(True) if self.plot.logy: pad_plot.SetLogy(True) pad_plot.Update( ) # needed sometimes with import of canvas. maybe because other "plot" pads exist... return c
# Find best fit point within axes point_bf = Graph( 1, drawstyle='p', markerstyle=34, markercolor='black', markersize=2, legendstyle='p', title="Best fit", ) best_fit = [ (getattr(p, xpoi), getattr(p, ypoi)) for p in scan.copy_tree( '{}==0 & 0.8<{}<1.2 & 0.9<{}<1.3'.format(zparam, xpoi, ypoi), ) ] point_bf.SetPoint(1, *best_fit[0]) # Make contours: 68 and 95% cont_1sig = prof.Clone() cont_1sig.linewidth = 2 cont_1sig.linecolor = "black" cont_1sig.legendstyle = 'l' cont_1sig.title = "68% CL" cont_2sig = cont_1sig.Clone() cont_2sig.linestyle = 2 cont_2sig.legendstyle = 'l' cont_2sig.title = "95% CL" cont_1sig.SetContour(1, np.array([chi2_2df_one_sigma])) cont_2sig.SetContour(1, np.array([chi2_2df_two_sigma]))
Hist(100, -5, 5, color='salmon', drawstyle='hist').FillRandom(F1('TMath::Gaus(x, 2, 1)'), 500)) stack.Add( Hist(100, -5, 5, color='powderblue', drawstyle='hist').FillRandom(F1('TMath::Gaus(x, 2, 0.6)'), 300)) objects.append(stack) # create some random histograms for i, (mu, sigma, n, c, s) in enumerate(zip(mus, sigmas, events, colors, styles)): hist = Hist(100, -5, 5, color=c, fillstyle=s, drawstyle='hist' if i % 2 == 0 else '') hist.FillRandom(F1('TMath::Gaus(x,{0},{1})'.format(mu, sigma)), n) objects.append(hist) # create a graph graph = Graph(10, drawstyle='P') for i in range(10): x = -2 + i * 4 / 10. graph.SetPoint(i, x, 40 + 10 * sin(x)) objects.append(graph) draw(objects, xtitle='Some Variable [Units]', ytitle='Events', ypadding=0.05) # see rootpy.plotting.utils.get_limits for details on what arguments are # supported for setting the axes ranges. wait()
# ROOT.gStyle.SetOptStat(0) fitfile = root_open('%s/MaxLikeFit.root' % basedir) fit = fitfile.fit_s pars = asrootpy(fit.floatParsFinal()) fitted = None if args.conly: fitted = ROOT.TArrow(pars['charmSF'].value, 2, pars['charmSF'].value, 1, 0.025, '|>') fitted.SetLineWidth(3) fitted.SetLineColor(ROOT.kBlue) fitted.SetFillColor(ROOT.kBlue) else: fitted = Graph(1) fitted.SetPoint(0, pars['charmSF'].value, pars['lightSF'].value) fitted.markerstyle = 20 fitted.markersize = 3 fitted.markercolor = '#009600' def addlabels(h): h.xaxis.title = 'charm SF' h.yaxis.title = 'light SF' h.xaxis.SetTitleOffset(0.9) h.yaxis.SetTitleOffset(1.2 if args.conly else 1.) addlabels(cbias) addlabels(failing) addlabels(ccover)