def MakePlot(PlotList, Mode): colors = [ ROOT.kRed, ROOT.kBlue, ROOT.kGreen, ROOT.kOrange, ROOT.kCyan, ROOT.kMagenta ] MG = TMultiGraph() MG.SetTitle( "Varying {};Center of Mass Angle in Degrees;Cross Section in mb/sr". format(Mode)) MG.SetTitle("MG_{}".format(Mode)) MG.SetName("MG_{}".format(Mode)) legend = ROOT.TLegend(0.65, .65, .9, .9) Zipper = zip(PlotList, colors) for plot, color in Zipper: plot.SetMarkerColor(ROOT.kWhite) plot.SetLineColor(color) plot.SetFillColor(ROOT.kWhite) plot.SetLineWidth(2) MG.Add(plot, "L") legend.AddEntry(plot, plot.GetName()) MG.Draw("AL") canvas.SetLogy() MG.GetXaxis().SetTitle("Center of Mass Angle in Degrees") MG.GetYaxis().SetTitle("Cross Section in mb/sr") MG.Draw() legend.Draw() canvas.SaveAs("vary_{}.png".format(Mode))
def evaluateResolutionVariation(model, bcid, prefix, suffix, vtxres, scaling, \ legend=False): from array import array from ROOT import TFile, TMultiGraph, TGraphErrors, gStyle, TCanvas, \ TLegend, TLatex names = [pre+'_'+model+'_'+bcid+'_'+suf for (pre, suf) in zip(prefix, \ suffix)] xVal = {name: array('d', [0.0]*len(vtxres)) for name in names} xErr = {name: array('d', [0.0]*len(vtxres)) for name in names} yVal = {name: array('d', [0.0]*len(vtxres)) for name in names} yErr = {name: array('d', [0.0]*len(vtxres)) for name in names} for name, scale in zip(names, scaling): for i, vr in enumerate(vtxres): f = TFile('results/'+name+'_'+vr+'.root') yVal[name][i] = f.Get('h_overlapInt').GetMean() * 100.0 yErr[name][i] = f.Get('h_integ').GetMeanError() * 100.0 xVal[name][i] = f.Get('h_vtxRes').GetMean() * scale * 1.0e4 multi = TMultiGraph('overlapIntegralBcid'+bcid, '') graphs = [] for i, name in enumerate(names): graph = TGraphErrors(len(vtxres), xVal[name], yVal[name], xErr[name], \ yErr[name]) graph.SetName(name) graph.SetMarkerStyle(20) graph.SetMarkerColor(1+i) multi.Add(graph) graphs.append(graph) gStyle.SetOptStat(0) canvas = TCanvas(model+'_'+bcid, '', 600, 600) multi.Draw('AP') canvas.Update() multi.GetXaxis().SetTitle('vertex resolution [#mum]') multi.GetXaxis().SetLabelSize(0.025) multi.GetXaxis().SetRangeUser(11, 69) multi.GetYaxis().SetTitle('overlap integral [a.u.]') multi.GetYaxis().SetLabelSize(0.025) multi.GetYaxis().SetRangeUser(0.77, 1.43) if legend: leg = TLegend(0.55, 0.15, 0.88, 0.3) leg.SetBorderSize(0) for i, name in enumerate(names): entry = leg.AddEntry(name, legend[i], 'P') entry.SetMarkerStyle(20) entry.SetMarkerColor(1+i) leg.Draw() drawCMS(wip=True) text = TLatex() text.SetNDC() text.SetTextFont(62) text.SetTextSize(0.04) text.SetTextAlign(21) text.DrawLatex(0.5, 0.92, 'Vertex Resolution Study: '+model+', BCID '+bcid) canvas.Modified() canvas.Update() canvas.SaveAs('plots/'+canvas.GetName()+'.pdf') canvas.SaveAs('plots/'+canvas.GetName()+'.C')
def FIT_XS(): is_fit = True gaexs_list_fit, geeff_list_fit, gexs_list_fit, func_list = fit_xs(label_list, iter_old, old_xs_list, tfunc_list, par_list, par_range_list, xmin_list, xmax_list, is_fit) for f, label, gaexs, geeff, gexs, xtitle, xs_ytitle, eff_ytitle in zip(func_list, label_list, gaexs_list_fit, geeff_list_fit, gexs_list_fit, xtitle_list, xs_ytitle_list, eff_ytitle_list): xs_mbc = TCanvas('xs_mbc_' + label + '_' + iter_old + '_fit', '', 700, 600) set_canvas_style(xs_mbc) xs_mbc.cd() if not label == 'DDPIPI': set_graph_style(gaexs, xtitle, xs_ytitle) gaexs.Draw('ap') else: set_graph_style(gaexs, xtitle, xs_ytitle) set_graph_style(gexs, xtitle, xs_ytitle) mg = TMultiGraph() mg.Add(gaexs) mg.Add(gexs) mg.Draw('ap') chi2 = f.GetChisquare() if label == 'DDPIPI': ndf = f.GetNDF() + 1 else: ndf = f.GetNDF() pt = TPaveText(0.15, 0.8, 0.55, 0.9, "BRNDC") set_pavetext(pt) pt.Draw() line = '#chi^{2}/ndf = ' + str(round(chi2, 3)) + '/' + str(round(ndf, 3)) + ' = ' + str(round(chi2/ndf, 3)) with open('./txts/likelihood_' + label + '.txt', 'w') as f: f.write(str(chi2) + '\n' + str(ndf)) pt.AddText(line) xs_mbc.SaveAs('./figs/xs_' + label + '_' + iter_old + '_fit.pdf') raw_input('Press <Enter> to end...') return func_list
def DivideGraphs(self, g1, g2, interpolationMethod="lin"): """ Divide 2 graphs g1 and g2, by each other applying an interpolation between the points for the denominator @param g1: graph 1 @param g2: graph 2 @param interpolationMethod: method used for interpolation between the two graphs @return: The ratio graphs """ #calculate x range xmin = max(g1.GetX()[0], g2.GetX()[0]) xmax = min(g1.GetX()[g1.GetN() - 1], g2.GetX()[g2.GetN() - 1]) # create new TGraphErors for result1 result1 = self.MakeGraphDivision(g1, g2, xmin, xmax, interpolationMethod) result1.SetMarkerColor(1) result1.SetMarkerStyle(20) # create new TGraphErors for result2 result2 = self.MakeGraphDivision(g2, g1, xmin, xmax, interpolationMethod) result2.SetMarkerColor(2) result2.SetMarkerStyle(20) result = TMultiGraph("result", " ") result.Add(result1) result.Add(result2) result.Draw("AP") result.GetXaxis().SetRangeUser(xmin, xmax) result.GetXaxis().SetTitle("p_{T} [Gev/c]") result.GetXaxis().SetTitleOffset(1.2) result.GetYaxis().SetTitleOffset(1.2) return result
def makeNoisePlot(outputdir, allgraphs, groups_to_plot, namegroups_to_plot, suffix, whats_to_plot, names_to_plot, xtitle): # gROOT.ProcessLine('.L ~/CMS_style/tdrstyle.C') # gROOT.ProcessLine('setTDRStyle()') c1=TCanvas('c1', 'c1', 600,600) leg=defaultLegend(x1=0.35,y1=0.6,x2=0.5,y2=0.90) mg=TMultiGraph() for k,group in enumerate(groups_to_plot): for i,what in enumerate(whats_to_plot): mg.Add(allgraphs[group][what], 'P') leg.AddEntry(allgraphs[group][what], namegroups_to_plot[k] + ' ' + names_to_plot[i], 'LP') mg.Draw('a') mg.GetXaxis().SetTitle(xtitle) mg.GetYaxis().SetTitle('Noise (GeV)') mg.GetXaxis().SetTitle(xtitle) if 'EB' in groups_to_plot[0]: mg.GetYaxis().SetRangeUser(0., 1.0) elif 'EE' in groups_to_plot[0]: mg.GetYaxis().SetRangeUser(0., 15.) leg.Draw('same') #c1.SetLogy() c1.SaveAs('{}/Noise_{}{}.pdf'.format(outputdir,groups_to_plot[0][:2],suffix)) c1.SaveAs('{}/Noise_{}{}.png'.format(outputdir,groups_to_plot[0][:2],suffix)) c1.SaveAs('{}/Noise_{}{}.C'.format(outputdir,groups_to_plot[0][:2],suffix)) c1.SaveAs('{}/Noise_{}{}.root'.format(outputdir,groups_to_plot[0][:2],suffix))
def ROCMGDraw(TGraphArray, c1): c1.Clear() colorArray = [1, 2, 3, 4, 6, 7] AOC = 0 leg = TLegend(0.1, 0.7, 0.48, 0.9) mg = TMultiGraph() title_text = [] l_count = 0 for TGraphInstance, title in TGraphArray: print TGraphInstance, title TGraphInstance.SetLineColor(colorArray[l_count]) mg.Add(TGraphInstance) AOC = TGraphInstance.Integral(0, -1) + .5 leg.AddEntry(TGraphInstance, "{} AOC: {}".format(title, AOC)) title_text.append(title) l_count = l_count + 1 title_text = "_".join(title_text) yEqualsX = TLine(0, 0, 1, 1) yEqualsX.SetLineStyle(7) TH2F_range = TH2F("range_{}".format(title_text), "range_{}".format(title_text), 10, 0, 1, 10, 0, 1) TH2F_range.Draw() mg.Draw("AL") leg.Draw("L") yEqualsX.Draw() title_text = title_text.replace(" ", "_") c1.SaveAs("output/ROC_{}.png".format(title_text)) c1.Clear()
def write_imposedattenuationgraphs(ordered_graphslinearity): if len(ordered_graphslinearity) == 40: sectors = [1, 2, 3, 4, 5] else: sectors = [6, 7, 8] colors = [1, 2, 3, 4, 5, 6, 7, 8, 9] for c, s in enumerate(sectors): plots = [x for x in ordered_graphslinearity if str(s) in x.filename[8]] mgraph = TMultiGraph() for counter, p in enumerate(plots): x = array('d', p.setattenvalues) y = array('d', p.normalizedsetmeancurrents) n = len(x) graph = TGraph(n, x, y) graph.SetMarkerColor(colors[counter]) graph.SetLineColor(colors[counter]) graph.SetMarkerStyle(20) graph.SetMarkerSize(1) mgraph.Add(graph) mgraph.SetTitle("PCBs type " + str(s)) mgraph.GetXaxis().SetRangeUser(0.0, 1.2) mgraph.GetXaxis().SetTitle("1/attenuation") mgraph.GetYaxis().SetTitle("i/area (uA/cm^{2})") mgraph.GetYaxis().SetTitleOffset(1.2) mgraph.Draw("APL") gPad.SaveAs("Overimposed_" + str(s) + ".pdf") gPad.Close()
def doSuperTGraph( data, canvas, obj): xmin=-1.8 xmax=1.8 gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) color=[601,417,920,633,910,433,400,619,1,922] mg = TMultiGraph(); leg = TLegend(0.58,0.75,0.89,0.89); i=0 for ivar in data['var']: if not os.path.exists(data['fold']+"/"+ivar+"_ll.root"): continue print '>>> Opening File :' , data['fold']+"/"+ivar+"_ll.root" inFile = TFile.Open ( data['fold']+"/"+ivar+"_ll.root" ," READ ") c1 = inFile.Get(canvas); gr = c1.GetListOfPrimitives().FindObject(obj) xaxis = gr.GetXaxis().GetTitle() yaxis = gr.GetYaxis().GetTitle() gr.SetLineColor(color[i]) mg.Add(gr) leg.AddEntry(gr,ivar,"l") i=i+1 print i c = TCanvas() c.cd() c.SetGrid() mg.Draw("al") line1 = TF1("line1","pol0",-100,100) line1.FixParameter(0,1.) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") line2 = TF1("line2","pol0",-100,100) line2.FixParameter(0,3.84) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.SetLineColor(2) line2.Draw("same") mg.SetTitle(";" +xaxis+";" +yaxis) mg.GetYaxis().SetRangeUser(0,10) leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(data['fold']+"combined10.png") c.SaveAs(data['fold']+"combined10.pdf") c.SaveAs(data['fold']+"combined10.root")
def main(): # print "reade ntuple for file ", sys.arg[1] # print "read geometry from file ", sys.argv[2] # ntuple = HGCalNtuple(sys.argv[1]) # planes = GeoUtils.read_planes(sys.argv[2]) # for plane in planes: # print_geo(ntuple, plane) print "read geometry from file: ", "fullgeometry_.txt" print "reading planes" planes = GeoUtils.read_planes("fullgeometry_.txt") c = TCanvas() mg = TMultiGraph() cells = planes[0].cells for cell in cells: x = array("d", cell.coordinates.vertices[:, 0]) x.append(x[0]) y = array("d", cell.coordinates.vertices[:, 1]) y.append(y[0]) gi = TGraph(len(x), x, y) gi.SetMarkerStyle(1) mg.Add(gi, "AL") # mg.Draw("AL") mg.Draw("A") c.Draw() c.SaveAs("hex0.png")
def doSuperTGraphAll( file_list, canvas, obj, output): gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) mg = TMultiGraph(); leg = TLegend(0.58,0.75,0.89,0.89); for iFile in file_list: if not os.path.exists(iFile['path']): print '>>> This File does not exist --> '+iFile['path']+'... check path ... ' continue print '>>> Opening File :' , iFile['path'] inFile = TFile.Open ( iFile['path'] ," READ ") c1 = inFile.Get(canvas); gr = c1.GetListOfPrimitives().FindObject(obj) xaxis = gr.GetXaxis().GetTitle() yaxis = gr.GetYaxis().GetTitle() gr.SetLineColor(iFile['color']) mg.Add(gr) leg.AddEntry(gr,iFile['legend'],"l") c = TCanvas() c.cd() c.SetGrid() mg.Draw("al") line1 = TF1("line1","pol0",-100,100) line1.FixParameter(0,1.) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") line2 = TF1("line2","pol0",-100,100) line2.FixParameter(0,3.84) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.SetLineColor(2) line2.Draw("same") mg.SetTitle(";" +xaxis+";" +yaxis) mg.GetYaxis().SetRangeUser(0,10) leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(output+"10.png") c.SaveAs(output+"10.pdf") c.SaveAs(output+"10.root")
def correctedCrossSectionsPlot(crossings, shapes, overDiff): uncorrected = {41: (3.2575816286, 0.00514858611944), \ 281: (3.26316215713, 0.00468789412223), \ 872: (3.27340775031, 0.00484925398906), \ 1783: (3.24986926821, 0.00460908436455), \ 2063: (3.26363843728, 0.0044071069983)} multi = TMultiGraph('sigmavis', '') graphs = [] n = len(shapes) + 1 for i, shape in enumerate([''] + list(shapes)): xval = array('d', [a + 0.08 * (i - 0.5 * n) for a in range(len(crossings))]) xerr = array('d', len(crossings) * [0]) yval = array('d', [uncorrected[int(bx)][0] for bx in crossings]) yerr = array('d', [uncorrected[int(bx)][1] for bx in crossings]) if shape: for j, bx in enumerate(crossings): yval[j] *= 1 + overDiff[shape][bx] yerr[j] *= 1 + overDiff[shape][bx] graph = TGraphErrors(len(crossings), xval, yval, xerr, yerr) graph.SetName('ge' + shape) graph.SetMarkerStyle(20) graph.SetMarkerColor(1 + i) multi.Add(graph) graphs.append(graph) gStyle.SetOptStat(0) hist = TH2F('hist', '', len(crossings), -0.5, len(crossings) - 0.5, 100, 3.23, 3.33) for i, bx in enumerate(crossings): hist.GetXaxis().SetBinLabel(i + 1, bx) canvas = TCanvas('c_' + multi.GetName(), '', 600, 600) hist.Draw('AXIS') multi.Draw('P') canvas.Update() hist.GetXaxis().SetLabelSize(0.035) hist.GetXaxis().SetNdivisions(len(crossings), False) hist.GetYaxis().SetTitle('#sigma_{vis} [b]') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.3) leg = TLegend(0.15, 0.82, 0.85, 0.85) leg.SetNColumns(len(shapes) + 1) leg.SetBorderSize(0) for i, shape in enumerate([''] + list(shapes)): entry = leg.AddEntry('ge' + shape, shapeNames[shape], 'P') entry.SetMarkerStyle(20) entry.SetMarkerColor(1 + i) leg.Draw() drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
def makeROC(fpr, tpr, thresholds,AUC,outfile,signal_label, background_label): c = TCanvas("c","c",700,600) gPad.SetMargin(0.15,0.07,0.15,0.05) gPad.SetLogy(0) gPad.SetGrid(1,1) gStyle.SetGridColor(15) mg = TMultiGraph() roc = TGraph(len(fpr),tpr,fpr) roc.SetLineColor(2) roc.SetLineWidth(3) roc.SetTitle(";Signal efficiency (%s); Background efficiency (%s)"%(signal_label, background_label)) roc.GetXaxis().SetTitleOffset(1.4) roc.GetXaxis().SetTitleSize(0.045) roc.GetYaxis().SetTitleOffset(1.4) roc.GetYaxis().SetTitleSize(0.045) roc.GetXaxis().SetRangeUser(0,1) roc.GetYaxis().SetRangeUser(0.000,1) mg.Add(roc) #roc.Draw("AL") tpr_diag = np.arange(0,1.09,0.1) fpr_diag = np.arange(0,1.09,0.1) roc_diag = TGraph(len(fpr_diag),tpr_diag,fpr_diag) roc_diag.SetLineStyle(2) roc_diag.SetLineWidth(3) roc_diag.SetLineColor(13) mg.Add(roc_diag) #roc_diag.Draw("AL same") mg.Draw("AL") mg.SetTitle(";Signal efficiency (%s); Background efficiency (%s)"%(signal_label, background_label)) latex = TLatex() latex.SetTextFont(42) latex.SetTextSize(0.05) latex.DrawLatexNDC(0.2,0.88,'AUC = %.3f'%AUC) c.SaveAs(outfile)
def plotMultiGraph(dataReadings, vals, title, xTitle, yTitle, outF): """ Plots several TGraphs using TMultiGraph """ mg = TMultiGraph() cv = TCanvas(outF, "cv", 1200, 1200) l = TLegend(0.9, 0.7, 1.0, 0.9) pad = TPad("p", "p", 0.05, 0.05, 1.0, 1.0) pad.cd() for a in xrange(len(vals)): print "vals[a] = {0}".format(vals[a]) l.AddEntry(vals[a], "Value %d" % (a + 1), "pl") mg.Add(vals[a]) mg.Draw("alp") pad.Update() mg.SetTitle(title + ";" + xTitle + ";" + yTitle) l.Draw() cv.cd() pad.Draw() mg.GetXaxis().SetNdivisions(len(dataReadings)) date = "" nReadings = len(dataReadings) divisor = nReadings / 10 + 1 # use to label no more than 10 bins, include first and last bins always for i in xrange(nReadings): if i % divisor == 0 or i == nReadings - 1: # If new date, print date and time if date != dataReadings[i]["date"]: date = dataReadings[i]["date"] mg.GetXaxis().SetBinLabel( mg.GetXaxis().FindBin(i), "#splitline{%s}{%s}" % (date, dataReadings[i]["time"])) else: mg.GetXaxis().SetBinLabel(mg.GetXaxis().FindBin(i), dataReadings[i]["time"]) mg.GetXaxis().SetTitleOffset(2.1) mg.GetYaxis().SetTitleOffset(2.1) pad.Update() cv.SaveAs(outF)
def print_to_pic(self): c = TCanvas() mg = TMultiGraph() for cell in self.cells: x = array("d", cell.coordinates.vertices[:, 0] / 10) x.append(x[0]) y = array("d", cell.coordinates.vertices[:, 1] / 10) y.append(y[0]) gi = TGraph(len(x), x, y) gi.SetMarkerStyle(1) mg.Add(gi, "AL") # mg.Draw("AL") mg.Draw("A") return mg
def plot_roc_curve(roc_b, roc_c, comp_roc_b, comp_roc_c, xlimits, ylimits, type, filename): canv = TCanvas("c1", "c1", 800, 600) mg = TMultiGraph() roc_b.SetLineColor(1) roc_c.SetLineColor(4) comp_roc_b.SetLineColor(1) comp_roc_c.SetLineColor(4) roc_b.SetMarkerColor(1) roc_c.SetMarkerColor(4) comp_roc_b.SetMarkerColor(1) comp_roc_c.SetMarkerColor(4) roc_b.SetMarkerStyle(20) roc_c.SetMarkerStyle(20) comp_roc_b.SetMarkerStyle(22) comp_roc_c.SetMarkerStyle(22) mg.Add(roc_b) mg.Add(roc_c) mg.Add(comp_roc_b) mg.Add(comp_roc_c) mg.SetTitle("; " + type + " efficiency; " + type + " fake rate") mg.Draw("ALP") mg.GetXaxis().SetLimits(xlimits[0], xlimits[1]) mg.SetMinimum(ylimits[0]) mg.SetMaximum(ylimits[1]) legend = TLegend(0.15, 0.88 - 0.08 * 4, 0.3, 0.88, '', 'NDC') legend.AddEntry(roc_b, "b-jets (GNN)", "lp") legend.AddEntry(roc_c, "c-jets (GNN)", "lp") legend.AddEntry(comp_roc_b, "b-jets (SV1)", "p") legend.AddEntry(comp_roc_c, "c-jets (SV1)", "p") legend.SetTextSize(0.025) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) canv.Clear() del canv
def plotMultiGraph(dataReadings, vals, title, xTitle, yTitle, outF): """ Plots several TGraphs using TMultiGraph """ mg = TMultiGraph() cv = TCanvas(outF, "cv", 1200, 1200) l = TLegend(0.9, 0.7, 1.0, 0.9) pad = TPad("p", "p", 0.05, 0.05, 1.0, 1.0) pad.cd() for rm in range(len(vals)): l.AddEntry(vals[rm], "RM%d" % (rm + 1), "pl") mg.Add(vals[rm]) mg.Draw("alp") pad.Update() mg.SetTitle(title + ";" + xTitle + ";" + yTitle) l.Draw() cv.cd() pad.Draw() mg.GetXaxis().SetNdivisions(len(dataReadings)) date = "" for i in range(len(dataReadings)): # If new date, print date and time if date != dataReadings[i]["date"]: date = dataReadings[i]["date"] mg.GetXaxis().SetBinLabel( mg.GetXaxis().FindBin(i), "#splitline{%s}{%s}" % (date, dataReadings[i]["time"])) else: mg.GetXaxis().SetBinLabel(mg.GetXaxis().FindBin(i), dataReadings[i]["time"]) mg.GetXaxis().SetTitleOffset(2.1) mg.GetYaxis().SetTitleOffset(2.1) pad.Update() cv.SaveAs(outF)
purGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Purity, _NumberOfProtonsErr, _PurityErr) purGraph.SetMarkerStyle(5) purGraph.SetLineColor(2) purGraph.SetMarkerColor(2) purGraph.SetMarkerSize(2) purGraph.GetXaxis().SetTitle("Mean N Proton") purGraph.GetYaxis().SetTitle("Purity") purGraph.SetTitle("Purity") MyFile = TFile( "effVsPurity_bs" + (str)(beamSpread) + "mrad_geo" + geoName + "_RestrictTracks" + (str)(restrictNTracks) + "_pitch" + (str)(pitch) + ".root", "RECREATE") mg = TMultiGraph() mg.SetTitle("Efficiency and Purity vs nProtons;Mean N Protons; (%)") mg.Add(effGraph, "lp") mg.Add(purGraph, "lp") mg.Draw("a") effGraph.Write() purGraph.Write() mg.Write() legend = TLegend(0.1, 0.7, 0.48, 0.9) legend.AddEntry(effGraph, "Efficiency", "lp") legend.AddEntry(purGraph, "Purity", "lp") legend.Draw("SAME") canvas1.Write("EffVsPurity")
rawfitresultList.At(i).getError()) tageffVsEtaGraph.SetLineColor(currentColor) linFunc.SetLineColor(currentColor) tageffVsEtaGraph.Fit(linFunc) graphHolder.Add(tageffVsEtaGraph) currentColor += 1 #tageffVsEtaGraph = TGraph(rawfitresultList.GetSize(),etaAvgValList,tageffValVList)#,etaAvgErrorList,tageffErrorList); #tageffVsEtaGraph. #ROOT.gSystem.ProcessEvents(); #img.FromPad(theCanvas); os.chdir("..") theCanvas = TCanvas() if (graphHolder.GetListOfGraphs().GetSize() == 1): graphHolder.SetTitle( "Tagging efficiency vs. Eta;Eta;Tagging Efficiency (omega)") else: graphHolder.SetTitle( "Tagging efficiency vs. Eta (multiple eta sets);Eta;Tagging Efficiency (omega)" ) graphHolder.Draw("AP") #raw_input("Press Enter to continue"); theCanvas.Print("tageffVsEtaGraph_%f.pdf" % time.time(), "pdf") print "SHIT"
def calc_punzi_FOM_vs_ctau(cutlist, labellist=[],mass_point=40,additional_string="",alpha=2,CL=5,FOM='punzi',header=""): file = {} nevt = {} tree = {} effs = {} chain = {} hist = {} eff_dict = { k:{} for k in cutlist} back_int = { k:{} for k in cutlist} back_int_weight = { k:{} for k in cutlist} back_eff = { k:{} for k in cutlist} punzi_dict = { k:{} for k in cutlist} graph = {} back_graph = {} ncuts = len(cutlist) if labellist == []: labellist=cutlist print NTUPLEDIR print "............." #prepare ctau ordered array for 1D plot mass_array = [] ctau_array = [] #for signal we have the normal efficiency for i, s in enumerate(sign): file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") # Read TFile tree[s] = file[s].Get("ntuple/tree") # Read TTree nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)# all gen events before cuts! #tree[s] = file[s].Get("skim") # Read TTree #nevt[s] = tree[s].GetEntries("")#if the tree is skimmed, this becomes a relative denominator #nevt[s] = (file[s].Get('c_nEvents')).GetBinContent(1)# all gen events before cuts! filename = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") if verbose_add: print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' if verbose_add: print filename if verbose_add: print "x-check: n gen events in counter, first bin:" if verbose_add: print (filename.Get('c_nEvents')).GetBinContent(1) if verbose_add: print "x-check: n entries in counter:" if verbose_add: print (filename.Get('c_nEvents')).GetEntries() effs[s] = [0]*(ncuts+1) effs[s] = [0]*(ncuts+1) weight = "1"#"EventWeight" var = "isMC" if samples[s]['mass'] not in mass_array: mass_array.append(samples[s]['mass']) if samples[s]['ctau'] not in ctau_array: ctau_array.append(samples[s]['ctau']) for j, c in enumerate(cutlist): tot_gen = nevt[s] n = tree[s].GetEntries("(" + cutlist[j] + ")") #wat?#test_op = cutlist[j] + " && number_of_matched_Jets>=1" #wat?#n = tree[s].GetEntries("(" + test_op + ")") ###BUGFIX: efficiency should be computed w.r.t. histo integral #hist[s+"_cut"+str(j)] = TH1F(s+"_cut"+str(j), ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) #hist[s+"_cut"+str(j)].Sumw2() #cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") #tree[s].Project(s+"_cut"+str(j), var, cutstring) #hist[s+"_cut"+str(j)].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) if verbose_add: print '\n' if verbose_add: print '**********************************************' if verbose_add: print "cut: ", c if verbose_add: print 'over signal ', s if verbose_add: print '\n' if verbose_add: print "signal num: ", n if verbose_add: print "signal den: ", tot_gen #if verbose_add: print "BUGFIX!!!!!!!!!!!" #if verbose: print "BUGFIX!!!!!!!!!!!" #if verbose_add: print "signal num from integral: ", hist[s+"_cut"+str(j)].Integral() #if verbose_add: print "signal den from generator: ", tot_gen #if verbose: print "BUGFIX!!!!!!!!!!!" if verbose_add: print ("signal eff %.2f") % (float(n)/(tot_gen)*100) if tot_gen==0: effs[s][j] = float(0.) else: effs[s][j] = (float(n)/(tot_gen)) eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j], 'nevents' : n} #sort mass array masses = np.array(mass_array) masses.sort() ctaus = np.array(ctau_array) ctaus.sort() #define multigraph mg = TMultiGraph() #leg = TLegend(0.78, 0.7, 0.98, 0.98) #leg2 = TLegend(0., 0.4, 0.98, 0.98) #leg2 = TLegend(0.3, 0.11, 0.65, 0.45)#DCMS,gen matching leg2 = TLegend(0.4, 0.11, 0.85, 0.45)#DCMS,summary plot leg2 = TLegend(0.4-0.3, 0.11+0.43, 0.85+0.05-0.3, 0.45+0.43)#EXO,summary plot leg2 = TLegend(0.4, 0.11, 0.85+0.05, 0.45)#EXO,summary plot leg3 = TLegend(0., 0.5, 0.5, 1.)#2 plots leg = TLegend(0., 0.4, 0.98, 0.98) leg.SetTextSize(0.03) leg2.SetTextSize(0.03) leg2.SetTextSize(0.025) leg.SetBorderSize(0) leg2.SetBorderSize(0) leg.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg2.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg3.SetTextSize(0.03) leg3.SetTextSize(0.025) leg3.SetBorderSize(0) leg3.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") #for background let's first consider the cut for j, c in enumerate(cutlist): print '\n' print "cut: ", c print 'over background' print '\n' #then loop over background integral = 0 weighted_integral = 0 back_tot_events = 0 for i, s in enumerate(back): chain[s] = TChain("ntuple/tree") #chain[s] = TChain("skim") #print "back: ", s back_file = {} for p, ss in enumerate(samples[s]['files']): back_file[ss] = TFile(NTUPLEDIR + ss + ".root", "READ") # Read TFile #?#if verbose: print "file: ", ss #?#if verbose: print "gen events: ", (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #?#if verbose: print "tree events: ", (back_file[ss].Get('ntuple/tree')).GetEntries() back_tot_events += (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #back_tot_events += (back_file[ss].Get('c_nEvents')).GetBinContent(1) chain[s].Add(NTUPLEDIR + ss + ".root") #print "MODIFIED WEIGHT!!!!!!" #weight = ("EventWeight*%s/5000." % str(back_tot_events)) weight = "EventWeight" #var = "nCHSJets" var = "isMC" hist[s] = TH1F(s, ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) hist[s].Sumw2() cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") chain[s].Project(s, var, "")#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) #if verbose: print "Hist content, no cut:" #if verbose: print hist[s].Print() #?#if verbose: print "events in the histo with get entries with empty project: ", hist[s].GetEntries() #?#if verbose: print "area under histo with empty project: ", hist[s].Integral() chain[s].Project(s, var, cutstring)#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) hist[s].Scale(samples[s]['weight'] if hist[s].Integral() >= 0 else 0) #?#if verbose: print "events in the histo with get entries after project: ", hist[s].GetEntries() #?#if verbose: print "area under histo after project: ", hist[s].Integral() if verbose: print "Hist content, with cut:" if verbose: print hist[s].Print() integral += hist[s].GetEntries() weighted_integral += hist[s].Integral() back_int[c] = integral back_int_weight[c] = weighted_integral if back_tot_events==0: back_eff[c] = float(0.) else: back_eff[c] = float(integral)/float(back_tot_events) if verbose: print "cut: ", c if verbose: print "back tot events (unweighted):", back_tot_events if verbose: print "back integral (unweighted): ", back_int[c] if verbose: print "back integral (weighted): ", back_int_weight[c] if verbose: print "back eff (unweighted): ", back_eff[c]*100 if FOM=="signaleff": punzi_dict[c]['back'] = {'back' : back_eff[c]*100} for i, s in enumerate(sign): if verbose: print "signal efficiency: ", eff_dict[c][s]['eff']*100 if FOM=="punzi": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']/(CL**2/2. + alpha*math.sqrt(back_int_weight[c]) + (CL/2.)*math.sqrt(CL**2 + 4*alpha*math.sqrt(back_int_weight[c]) + 4*back_int_weight[c]))} elif FOM=="signaleff": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']*100} elif FOM=="entries": punzi_dict[c][s] = {'sign': eff_dict[c][s]['nevents']} else: print "not punzi FOM, aborting!" exit() if FOM=="signaleff": dummy = TGraph()#len(ct),ct, np.array(ct)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) if header!="": leg2.AddEntry(dummy, header,'') leg3.AddEntry(dummy, header,'') #for each cut, we need a graph for j, c in enumerate(cutlist): #first let's build the ordered punzi vector w.r.t. masses, for a chosen ctau punzi_array = [] back_array = [] for la in ctaus: #la = str(a) if la== 0.001: st = CHANNEL+"_M"+str(mass_point)+"_ctau0" elif la==0.05 or la==0.1: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(str(la).replace("0.","0p")) else: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(int(la)) #st = "VBFH_M"+str(mass_point)+"_ctau"+str(a) punzi_array.append(punzi_dict[c][st]['sign']) mass = array('d', masses) ct = array('d', ctaus) p_array = array('d',punzi_array) #graph[c] = TGraph(len(mass),mass, np.array(p_array)) graph[c] = TGraph(len(ct),ct, np.array(p_array)) graph[c].SetMarkerStyle(markers[j])#21 graph[c].SetLineWidth(3) graph[c].SetMarkerSize(1.2) graph[c].SetMarkerColor(colors[j]) graph[c].SetLineColor(colors[j]) graph[c].SetFillColor(colors[j]) #graph[c].SetLogx() leg.AddEntry(graph[c],labellist[j],'PL') leg2.AddEntry(graph[c],labellist[j],'PL') leg3.AddEntry(graph[c],labellist[j],'PL') mg.Add(graph[c]) if FOM=="signaleff": #add plot for background for a in ctaus: back_array.append(punzi_dict[c]['back']['back']) mass = array('d', masses) ct = array('d', ctaus) e_array = array('d',back_array) #back_graph[c] = TGraph(len(mass),mass, np.array(e_array)) back_graph[c] = TGraph(len(ct),ct, np.array(e_array)) back_graph[c].SetMarkerStyle(0) back_graph[c].SetLineWidth(2) back_graph[c].SetMarkerSize(1.) back_graph[c].SetMarkerColor(colors[j]) back_graph[c].SetLineColor(colors[j]) back_graph[c].SetLineStyle(2) back_graph[c].SetFillColor(colors[j]) #back_graph[c].SetLogx() #leg.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#leg2.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#mg.Add(back_graph[c]) if FOM=="signaleff": dummy = TGraph(len(ct),ct, np.array(e_array)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) #w#leg2.AddEntry(dummy, 'cuts on bkg.','PL') #cmg = TCanvas("cmg", "cmg", 2000, 1400) #cmg = TCanvas("cmg", "cmg", 2000, 800)#best #cmg = TCanvas("cmg", "cmg", 1200, 1000) cmg = TCanvas("cmg", "cmg", 1300, 800)#DCMS cmg.cd() cmg.SetGrid() cmg.SetLogx() #if FOM=="signaleff": # cmg.SetLogx() #pad1 = TPad("pad1", "pad1", 0, 0., 0.85, 1.0) #pad1 = TPad("pad1", "pad1", 0, 0., 0.7, 1.0) #pad1.SetGrid() #pad1.SetLogx() if FOM=="signaleff": print "LOL" #pad1.SetLogy() #pad1.SetLogy() #pad1.Draw() #pad1.cd() #W#if FOM=="signaleff": #w#mg.SetMaximum(101) #mg.SetMinimum(1.e-50) mg.SetMinimum(0.)#!! mg.Draw("APL") mg.GetXaxis().SetTitleSize(0.05) mg.GetYaxis().SetTitleSize(0.05) mg.GetXaxis().SetTitle('c#tau_{#pi} (mm)') mg.GetYaxis().SetTitleOffset(0.9); if FOM=="punzi": mg.GetYaxis().SetTitle('Punzi significance @ '+str(alpha)+' #sigma, '+CHANNEL+' cuts') #mg.GetYaxis().SetTitleOffset(1.5) elif FOM=="signaleff": #mg.GetYaxis().SetTitle('Signal efficiency, '+CHANNEL+' cuts (%)') mg.GetYaxis().SetTitle('Signal gen-matching efficiency, '+CHANNEL+' (%)') elif FOM=="entries": mg.GetYaxis().SetTitle('Signal entries surviving cuts') else: print "not punzi FOM, aborting" latex = TLatex() latex.SetNDC() latex.SetTextSize(0.05) latex.SetTextColor(1) latex.SetTextFont(42) latex.SetTextAlign(33) latex.SetTextFont(62) latex.DrawLatex(0.25, 0.96, "CMS") latex.SetTextFont(52) latex.DrawLatex(0.66, 0.96, "Simulation Preliminary") cmg.Update() cmg.cd() leg2.SetTextSize(0.04) #leg.Clear()#????????? #w#leg2.Draw() cmgL = TCanvas("cmgL", "cmgL", 2000, 800)#DCMS cmgL.cd() #pad2 = TPad("pad2", "pad2", 0.85, 0., 1, 1.0) #pad2 = TPad("pad2", "pad2", 0.7, 0., 1, 1.0) #pad2.SetGrid() #pad2.SetLogx()macro/VBF_punzi_LLP_AOD.py #pad2.Draw() #pad2.cd() leg3.SetTextSize(0.04) #leg.Clear()#????????? leg3.Draw() cmgL.Update() if FOM=="punzi": cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".pdf") cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".png") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.png") elif FOM=="signaleff": cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") elif FOM=="entries": cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") else: print "not punzi FOM, aborting" if not options.bash: raw_input("Press Enter to continue...") cmg.Close()
pass #========Canvas Styling =============== canv = r.TCanvas("canv", "canv", 600, 600) #r.TStyle.SetCanvasBorderMode(0) r.TStyle().SetCanvasColor(r.kWhite) r.TStyle().SetCanvasDefX(0) r.TStyle().SetCanvasDefY(0) canv.SetLeftMargin(0.16) canv.SetRightMargin(0.06) canv.SetTopMargin(0.08) canv.SetBottomMargin(0.13) canv.cd() mg.Draw("AP SAME") leg.Draw() # For the legend leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetX1NDC(0.18) leg.SetX2NDC(0.60) leg.SetY1NDC(0.55) leg.SetY2NDC(0.90) leg.SetTextSize(0.03) # X Axis Style mg.GetXaxis().SetTitle("Current Drawn (#mu A)") mg.GetXaxis().SetTitleSize(0.06) mg.GetXaxis().SetLabelSize(0.05)
def printmultigraph(grs, sortk, plotoptions, outn, title, year, doext, ploterror, ymax): import CMS_lumi, tdrstyle import array #set the tdr style tdrstyle.setTDRStyle() #change the CMS_lumi variables (see CMS_lumi.py) CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" if year == 2018: CMS_lumi.extraText2 = "2018 pp data" if year == 2017: CMS_lumi.extraText2 = "2017 pp data" if year == 2016: CMS_lumi.extraText2 = "2016 pp data" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) CMS_lumi.writeTitle = 1 CMS_lumi.textTitle = title iPos = 11 if (iPos == 0): CMS_lumi.relPosX = 0.12 H_ref = 600 W_ref = 800 W = W_ref H = H_ref iPeriod = 0 # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref c = TCanvas("c", "c", 50, 50, W, H) #gStyle.SetOptStat(0) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.SetTickx(0) c.SetTicky(0) #canvassettings(c) mg = TMultiGraph() #mg = grs['main'] mg.SetTitle(title) #gStyle.SetTitleAlign(33) #gStyle.SetTitleX(0.99) leg = TLegend( 0.345, 0.68, 0.645, 0.88 ) #TLegend(1. - c.GetRightMargin() - 0.8, 1. - c.GetTopMargin() - 0.40,1. - c.GetRightMargin()- 0.60, 1. - c.GetTopMargin() -0.02) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetMargin(0.1) #ymax = 0; ratesFromFit = {} evVal = 15000 if doext: evVal = 50000 #f=TFile.Open(outn+".root","RECREATE") # for name,value in plotoptions.iteritems(): for name in sortk: if name != 'main': continue value = plotoptions[name] #print grs gr = grs[name] #print gr gr.SetName(title) #extrate = fitGraph(gr,evVal) #ratesFromFit[name] = extrate if doext: #print name, extrate[0], extrate[1] NN = gr.GetN() gr.Set(NN + 1) gr.SetPoint(NN + 1, 50000.0, extrate["rate"][0]) yErr = extrate["rate"][1] if not ploterror: yErr = 0.0 gr.SetPointError(NN + 1, 0.0, yErr) gr.SetMarkerColor(value['color']) gr.SetMarkerStyle(value['markst']) gr.SetLineColor(value['color']) gr.SetMarkerSize(1.15) #1.05 gr.SetMinimum(0.1) #gr.Write() mg.Add(gr) text = title #name #+plotoptions[name]['leg'] leg.AddEntry(gr, text, "p") continue mg.SetName(outn) mg.SetMinimum(0.1) mg.SetMaximum(ymax) #1.6*ymax mg.Draw("AP") mg.GetXaxis().SetRangeUser(2000, 20000) c.Update() graphAxis(mg) CMS_lumi.CMS_lumi(c, iPeriod, iPos) c.cd() c.Update() frame = c.GetFrame() frame.Draw() leg.Draw() c.SaveAs(outn + ".png") #c.SaveAs(outn+".C") del c return ratesFromFit
ccratio_plot.SetLineColor(1) ISS_negative_plot.SetLineColor(4) ISS_chargeconfused_plot.SetLineColor(6) ISS_positive_plot.SetLineColor(8) ccratio_plot.SetMarkerStyle(20) ISS_negative_plot.SetMarkerStyle(21) ISS_chargeconfused_plot.SetMarkerStyle(22) ISS_positive_plot.SetMarkerStyle(23) mg.SetTitle("; Rigidity (GV); ") #mg.Add(ccratio_plot) mg.Add(ISS_negative_plot) mg.Add(ISS_positive_plot) mg.Add(ISS_chargeconfused_plot) mg.Draw("ACP") grshade.SetFillStyle(3004) grshade.SetFillColor(2) grshade.Draw("F") grshade2.SetFillStyle(3016) grshade2.SetFillColor(1) grshade2.Draw("F") leg =TLegend(.7,.7,.9,.9,) leg.SetFillColor(0) #leg.AddEntry(ccratio_plot,"Charge Confusion Level","LP") leg.AddEntry(ISS_negative_plot,"ISS negative data","LP") leg.AddEntry(ISS_positive_plot,"ISS positive data","LP") leg.AddEntry(ISS_chargeconfused_plot,"Charge Confused Event","LP") leg.Draw()
canvas.Update() canvas.Print("metEfficiencyPlotWithRate_ff_W_munu_1000events.svg", "svg") canvas.Print("metEfficiencyPlotWithRate_ff_W_munu_1000events.png", "png") canvas.Print("metEfficiencyPlotWithRate_ff_W_munu_1000events.pdf", "pdf") metEfficiencyPlotWithRate = TMultiGraph("metEfficiencyPlotWithRate", "") metEfficiencyPlotWithRate.Add(efficiencyPlotWithRate_ff_H_WW_enuenu_1000events) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetMarkerColor(6) metEfficiencyPlotWithRate.Add(efficiencyPlotWithRate_ff_H_WW_munumunu_1000events) efficiencyPlotWithRate_ff_H_WW_munumunu_1000events.SetMarkerColor(2) metEfficiencyPlotWithRate.Add(efficiencyPlotWithRate_ff_W_enu_1000events) efficiencyPlotWithRate_ff_W_enu_1000events.SetMarkerColor(3) metEfficiencyPlotWithRate.Add(efficiencyPlotWithRate_ff_W_munu_1000events) efficiencyPlotWithRate_ff_W_munu_1000events.SetMarkerColor(4) efficiencyPlotWithRate_ff_W_munu_1000events.SetLineColor(1) metEfficiencyPlotWithRate.Draw("AP") metEfficiencyPlotWithRate.GetXaxis().SetTitle("Rate [Hz]") metEfficiencyPlotWithRate.GetXaxis().SetTitleOffset(1.2) metEfficiencyPlotWithRate.GetYaxis().SetTitle("% accepted events") metEfficiencyPlotWithRate.GetYaxis().SetTitleOffset(1.2) metEfficiencyPlotWithRate.GetYaxis().SetRangeUser(0, 1.1) line_200kHz.Draw() label_200kHz.Draw() metEfficiencyPlotWithRate_legend = TLegend(0.58 , 0.13, 0.9, 0.317) metEfficiencyPlotWithRate_legend.SetHeader("Physical process") metEfficiencyPlotWithRate_legend.AddEntry(efficiencyPlotWithRate_ff_H_WW_munumunu_1000events, "H #rightarrow WW #rightarrow #mu#nu_{#mu}#mu#nu_{#mu}", "P") metEfficiencyPlotWithRate_legend.AddEntry(efficiencyPlotWithRate_ff_H_WW_enuenu_1000events, "H #rightarrow WW #rightarrow e#nu_{e}e#nu_{e}", "P") metEfficiencyPlotWithRate_legend.AddEntry(efficiencyPlotWithRate_ff_W_munu_1000events, "W #rightarrow #mu#nu_{#mu}", "P") metEfficiencyPlotWithRate_legend.AddEntry(efficiencyPlotWithRate_ff_W_enu_1000events, "W #rightarrow e#nu_{e}", "P") metEfficiencyPlotWithRate_legend.Draw() text.Draw()
def plotROCfromgraph(graphs, xlabel, ylabel, legendNames, destination, year, xlog=False, ylog=False, additionalInformation=None): GeneralSettings() #Make sure single curves also pass try: len(graphs) except: graphs = [graphs] #Create Canvas Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) tdr.setTDRStyle() #Create TGraph mgraph = TMultiGraph() for i, graph in enumerate(graphs): graph.SetMarkerSize(1.5) graph.SetLineColor(TColor.GetColor(GetLineColor(graphs.index(graph)))) graph.SetMarkerColor(TColor.GetColor(GetLineColor( graphs.index(graph)))) graph.SetMarkerStyle(GetMarker(graphs.index(graph))) mgraph.Add(graph) mgraph.Draw("APLine") mgraph.SetTitle(";" + xlabel + ";" + ylabel) cl.CMS_lumi(Canv, 4, 11, year, 'Simulation', False) xmax = GetXMax(graphs) xmin = GetXMin(graphs) ymax = GetYMax(graphs) ymin = GetYMin(graphs) if xlog: Canv.SetLogx() mgraph.GetXaxis().SetRangeUser(0.3 * xmin, 30 * xmax) else: mgraph.GetXaxis().SetRangeUser(0.7 * xmin, 1.3 * xmax) if ylog: Canv.SetLogy() mgraph.GetYaxis().SetRangeUser(0.3 * ymin, 10 * ymax) else: mgraph.GetYaxis().SetRangeUser(0.5 * ymin, 1.2 * ymax) #Write extra text if additionalInformation is not None: lastYpos = 0.8 lastCorrectedYpos = None extraText = TLatex() for info in additionalInformation: try: extraTextString = info[0] extraTextXpos = info[1] extraTextYpos = info[2] extraTextSize = info[3] except: print("Wrong Format for additionalInformation. Stopping") pass if extraTextSize is None: extraTextSize = 0.03 if extraTextXpos is None: extraTextXpos = 0.2 if extraTextYpos is None: if lastYpos is None: extraTextYpos = lastCorrectedYpos - 0.05 else: extraTextYpos = 0.8 extraText.SetNDC() extraText.SetTextAlign(12) extraText.SetTextSize(extraTextSize) extraText.DrawLatex(extraTextXpos, extraTextYpos, extraTextString) lastYpos = info[2] lastCorrectedYpos = extraTextYpos if legendNames: legend = TLegend(0.7, .7, .9, .9) for g, n in zip(graphs, legendNames): legend.AddEntry(g, n) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Save everything savePlots(Canv, destination)
def main(): filename = read_file_name("NY_OUTPUT.txt") can = TCanvas("can","can") can.SetGrid() mg = TMultiGraph() nn = 9 GR = [] NAME = [] px,py = array('d'), array('d') f = open(filename[2],'r') indicator = 0 for line in f: if(indicator == 0): indicator = indicator + 1 continue Name, Total, Pos, Neg, TNum = line.split() name = Find_Loca(Name) name = Name.replace(Name[name:],"") # print(name) px.append((indicator-1)%9); py.append(float(TNum)) if((indicator)%9 == 0): NAME.append(name) gr = TGraph( nn, px, py ) GR.append(gr) px,py = array('d'), array('d') indicator = indicator + 1 # print(GR); print(len(GR)) for i in range(len(GR)): GR[i].SetLineWidth(2) if "water" in NAME[i]: GR[i].SetLineWidth(5); GR[i].SetLineColor(1) ;GR[i].SetMarkerColor(1) if "wine" in NAME[i]: GR[i].SetMarkerColor(2);GR[i].SetLineColor(2) if "beer" in NAME[i]: GR[i].SetMarkerColor(5);GR[i].SetLineColor(5) if "tea" in NAME[i]: GR[i].SetMarkerColor(4);GR[i].SetLineColor(4) if "coffee" in NAME[i]: GR[i].SetMarkerColor(3);GR[i].SetLineColor(3) if "juice" in NAME[i]: GR[i].SetMarkerColor(7);GR[i].SetLineColor(7) if "COLA" in NAME[i]: GR[i].SetMarkerColor(6);GR[i].SetLineColor(6) GR[i].GetXaxis().SetTitle("days") GR[i].SetMarkerStyle(20) # GR[i].Fit("pol4","q") mg.Add(GR[i]) mg.Draw("ALP") leg = TLegend(0.65, 0.65, 0.9, 0.8) leg.SetBorderSize(0) leg.SetFillColor(10) for i in range(len(GR)): leg_entry = leg.AddEntry(GR[i], NAME[i],"l") leg.Draw() mg.SetTitle("Total tweets counts at NY") mg.GetHistogram().GetXaxis().SetTitle("days") mg.GetHistogram().GetXaxis().SetTitleOffset(1) mg.GetHistogram().GetXaxis().SetLabelSize(0.03) mg.GetHistogram().GetYaxis().SetTitle("Counts") mg.GetHistogram().GetYaxis().SetTitleOffset(1.3) mg.GetHistogram().GetYaxis().SetLabelSize(0.03) mg.GetHistogram().GetXaxis().SetBinLabel(5,"Mon") mg.GetHistogram().GetXaxis().SetBinLabel(16,"Tue") mg.GetHistogram().GetXaxis().SetBinLabel(28,"Wed") mg.GetHistogram().GetXaxis().SetBinLabel(40,"Thu") mg.GetHistogram().GetXaxis().SetBinLabel(51,"Fri") mg.GetHistogram().GetXaxis().SetBinLabel(63,"Sat") mg.GetHistogram().GetXaxis().SetBinLabel(73,"Sun") mg.GetHistogram().GetXaxis().SetBinLabel(84,"Mon") mg.GetHistogram().GetXaxis().SetBinLabel(96,"Tue") # for i in range(len(GR)): # mg.GetHistogram().GetXaxis().SetBinLabel(i,DAYS) # mg.GetHistogram().GetXaxis().SetLabel("tt") can.Modified() can.Update() # can.GetFrame().SetBorderSize( 12 ) can.Print("Total_tweet_NY.pdf")
def make_time_rod_evo(error_dict, rod_dict, results, doLock): c2 = TCanvas( 'c2', 'c2', 1000, 600) leg = TLegend(0.18,0.85,0.45,0.55) leg.SetLineColor(0) leg.SetFillStyle(0) leg.SetShadowColor(0) leg.SetBorderSize(0) leg.SetNColumns(2) R15 = TLine(431,0,431,60) R15.SetLineColorAlpha(kPink+10,0.4) R15.SetLineWidth(4) R16 = TLine(1820,0,1820,60) R16.SetLineColorAlpha(kMagenta+10,0.4) R16.SetLineWidth(4) R17 = TLine(3376,0,3376,60) R17.SetLineColorAlpha(kGreen-3,0.4) R17.SetLineWidth(4) TS1 = TLine(431,0,432,60) TS1.SetLineColorAlpha(kPink+10,0.5) TS1.SetLineWidth(5) TS2 = TLine(1415,0,1415,60) TS2.SetLineColorAlpha(kMagenta+3,0.5) TS2.SetLineWidth(5) leg2 = TLegend(0.18,0.45,0.35,0.55) leg2.SetLineColor(0) leg2.SetFillStyle(0) leg2.SetShadowColor(0) leg2.SetBorderSize(0) gStyle.SetLegendTextSize(0.030) leg2.AddEntry(R15, "End of 2015", 'lf') leg2.AddEntry(R16, "End of 2016", 'lf') leg2.AddEntry(R17, "End of 2017", 'lf') #leg2.AddEntry(TS2, "TS2", 'lf') for key,val in rod_dict.items(): TS1.SetY2(val*0.5) TS2.SetY2(val+1) R15.SetY2(val*0.3) R16.SetY2(val*0.5) R17.SetY2(val*0.8) times = {} times.clear() for e in error_bits: times['0x'+e] = [0] for error in results: pos_rod = error.text.find("ROD") + 4 pos_lock = error.text.find("Lock") + 15 pos_buff = error.text.find("buffer") + 17 if error.msgID == 'TRT::ROD05Module': rod = '0x'+str(error.text[pos_rod:pos_rod+6]) else: rod = str(error.text[pos_rod:pos_rod+8]) lock = str(error.text[pos_lock:pos_lock+3]) buff = str(error.text[pos_buff:pos_buff+3]) if key == rod and doLock and lock != '0xf': times[lock].append(error.sb_total_time) leg.Clear() mg = TMultiGraph() for e in error_bits: errs = [] for i,x in enumerate(times['0x'+e]): errs.append(i+0.0) errs.append(errs[-1]) #times['0x'+e].append(1800.0) times['0x'+e].append(results[-1].sb_total_time) gr = TGraph(len(times['0x'+e]), array(times['0x'+e]), array(errs)) gr.SetMarkerSize(0.7) if bin(int('0x'+e, 16))[2:].zfill(4) == '0111': leg.AddEntry(gr,'GOL 3',"lp"); elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011': leg.AddEntry(gr,'GOL 2',"lp"); elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101': leg.AddEntry(gr,'GOL 1',"lp"); elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110': leg.AddEntry(gr,'GOL 0',"lp"); else: leg.AddEntry(gr,bin(int('0x'+e, 16))[2:].zfill(4),"lp"); mg.Add(gr,"pl"); mg.SetTitle("; Hours of stable beams; # of rocketio io lock errors"); mg.Draw("PMC PLC a"); R15.Draw() R16.Draw() R17.Draw() #TS1.Draw() #TS2.Draw() AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal") leg.Draw() leg2.Draw() AtlasStyle.myText(0.4, 0.88, kBlack, "ROD: " + key) leg.SetMargin(0.5) gPad.Modified() mg.GetXaxis().SetLimits(0,results[-1].sb_total_time) mg.SetMinimum(0.) mg.SetMaximum(val+1) c2.Update() c2.Print("plots/time_"+key+".pdf") c2.Clear()
def plotROC(xdata, ydata, xlabel, ylabel, legendNames, destination, year, xerror=None, yerror=None, xlog=False, ylog=False, additionalInformation=None): GeneralSettings() #Make sure single curves also pass try: len(xdata[0]) except: xdata = [xdata] ydata = [ydata] legendNames = [legendNames] xerror = [xerror] yerror = [yerror] #Create Canvas Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) tdr.setTDRStyle() #Create TGraph graphs = [] for x, y, xe, ye in zip(xdata, ydata, xerror, yerror): tmpgraph = None if xe is None and ye is None: tmpgraph = TGraph(len(x), x, y) elif xe is None or ye is None: NullErrors = np.zeros(len(x)) if xe is not None: tmpgraph = TGraphErrors(len(x), x, y, xe, NullErrors) if ye is not None: tmpgraph = TGraphErrors(len(x), x, y, NullErrors, ye) else: tmpgraph = TGraphErrors(len(x), x, y, xe, ye) graphs.append(tmpgraph) mgraph = TMultiGraph() for i, graph in enumerate(graphs): graph.SetMarkerSize(1.5) graph.SetLineColor(TColor.GetColor(GetLineColor(graphs.index(graph)))) graph.SetMarkerColor(TColor.GetColor(GetLineColor( graphs.index(graph)))) graph.SetMarkerStyle(GetMarker(graphs.index(graph))) mgraph.Add(graph) mgraph.Draw("APLine") mgraph.SetTitle(";" + xlabel + ";" + ylabel) cl.CMS_lumi(Canv, 4, 11, 'Simulation', False) if xlog: Canv.SetLogx() mgraph.GetXaxis().SetRangeUser(0.3 * GetNestedMin(xdata), 30 * GetNestedMax(xdata)) else: mgraph.GetXaxis().SetRangeUser(0.7 * GetNestedMin(xdata[0]), 1.3 * GetNestedMax(xdata)) if ylog: Canv.SetLogy() mgraph.GetYaxis().SetRangeUser(0.3 * GetNestedMin(ydata), 10 * GetNestedMax(ydata)) else: mgraph.GetYaxis().SetRangeUser(0.5 * GetNestedMin(ydata), 1.2 * GetNestedMax(ydata)) #Write extra text if additionalInformation is not None: lastYpos = 0.8 lastCorrectedYpos = None extraText = TLatex() for info in additionalInformation: try: extraTextString = info[0] extraTextXpos = info[1] extraTextYpos = info[2] extraTextSize = info[3] except: print("Wrong Format for additionalInformation. Stopping") pass if extraTextSize is None: extraTextSize = 0.03 if extraTextXpos is None: extraTextXpos = 0.2 if extraTextYpos is None: if lastYpos is None: extraTextYpos = lastCorrectedYpos - 0.05 else: extraTextYpos = 0.8 extraText.SetNDC() extraText.SetTextAlign(12) extraText.SetTextSize(extraTextSize) extraText.DrawLatex(extraTextXpos, extraTextYpos, extraTextString) lastYpos = info[2] lastCorrectedYpos = extraTextYpos if legendNames: legend = TLegend(0.7, .7, .9, .9) for g, n in zip(graphs, legendNames): legend.AddEntry(g, n) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Save everything savePlots(Canv, destination)
def plot(tgr, n): #(List, layer, tgrDict): H = 1600 W = 800 #print "----- Creating Third TCanvas -----" c = TCanvas("c", "Canvas", W, H) ymax = 0.0 c.SetLeftMargin(0.15) c.SetRightMargin(0.06) c.SetTopMargin(0.09) c.SetBottomMargin(0.14) #gPad.SetGrid() gPad.SetTicks() #gPad.SetLogy() mg = TMultiGraph() tgr.SetMarkerColor(kGreen + 3) tgr.SetMarkerStyle(21) tgr.SetMarkerSize(1.5) mg.Add(tgr, 'AP') mg.Draw("a") l = TLegend(0.42, 0.15, 0.82, 0.35) l.SetFillColor(0) l.SetBorderSize(0) l.SetTextSize(0.03) l.SetNColumns(1) l.AddEntry(tgr, "CMS (13TeV)", "p") mg.SetTitle('') #mg.SetMaximum(ymax*1.1) mg.GetXaxis().SetTitle('Instantaneous Luminosity 10^{34} cm^{-2} s^{-1}') mg.GetXaxis().SetLabelFont(42) mg.GetXaxis().SetLabelOffset(0.007) mg.GetXaxis().SetLabelSize(0.043) mg.GetXaxis().SetTitleSize(0.03) mg.GetXaxis().SetTitleOffset(1.56) mg.GetXaxis().SetTitleFont(42) mg.GetYaxis().SetTitle('rate (Hz/cm^{2})') mg.GetYaxis().SetLabelFont(42) mg.GetYaxis().SetLabelOffset(0.008) mg.GetYaxis().SetLabelSize(0.02) mg.GetYaxis().SetTitleSize(0.03) mg.GetYaxis().SetTitleOffset(1.37) mg.GetYaxis().SetTitleFont(42) pv = TPaveText(.08, 0.94, .45, 0.94, "NDC") pv.AddText('CMS Preliminary Rack {}'.format(n)) pv.SetFillStyle(0) pv.SetBorderSize(0) pv.SetTextSize(0.04) pv.Draw() fun1 = TF1("fun1", "pol1", 6000, 16000) fit1 = tgr.Fit("fun1", "R") # "FQ") offset1 = fun1.GetParameter(0) slope1 = fun1.GetParameter(1) l.AddEntry(tgr, 'The p0 value is {0:.6f}'.format(offset1)) l.AddEntry(tgr, 'The p1 value is {0:.6f}'.format(slope1)) l.Draw("a") c.SaveAs("rack{}.png".format(n)) c.SaveAs("rack{}.pdf".format(n)) c.SaveAs("rack{}.C".format(n)) return
def Draw_2D_Comp(rootfile_name, var_x, var_y, min, max, WP_list, leg, isTgraph=False): gStyle.SetErrorX(0.5) ## Creating a multigraph for the canvas if we are looking at TGraphs if isTgraph: stack = TMultiGraph() args = "AP" ## Creating a stack for the canvas if we are looking at TPofiles else: stack = THStack("stack", var_x.name + var_y.name) args = "nostack " stack.SetMinimum(min) stack.SetMaximum(max) for wp in WP_list: ## Generating the graph name graph_name = "{}_vs_{}_{}".format(var_x.name, var_y.name, wp.name) if isTgraph: graph_name += "_res" ## Loading the graph using its name and file location graph = GetGraphFromFile(rootfile_name, graph_name) if graph == -1: continue ## Setting the colors specific to the working point graph.SetLineColor(wp.colour) graph.SetMarkerColor(wp.colour) graph.SetMarkerStyle(wp.marker) ## Adding the legend entry leg.AddEntry(graph, wp.name, "p") ## Adding the object to the stack stack.Add(graph) del graph ## Checking to see if any graphs were found for this variable nhists = stack.GetListOfGraphs().GetSize( ) if isTgraph else stack.GetNhists() if nhists == 0: print("\n\n\nNo graphs found for working point {}\n\n\n".format( wp.name)) return -1 ## Drawing the stack on the currrent canvas stack.Draw(args) leg.Draw() ## Setting axis labels stack.GetXaxis().SetTitle(var_x.x_label + " " + var_x.units) stack.GetYaxis().SetTitle(var_y.x_label + " " + var_y.units) ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) return stack
def closureTest_plots(filename): f = BareRootFile(filename) tree = f.Get('closureTest') gStyle.SetStatX(0.9) gStyle.SetStatY(0.9) gStyle.SetStatW(0.2) gStyle.SetStatH(0.14) hist1 = TH1F('hist1', '', 55, 0.9, 2.0) hist2 = TH1F('hist2', '', 55, 0.9, 2.0) condition = ('fit_overlapDiff>=0 && temp_overlapDiff>=0 && ' 'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2') tree.Draw('temp_chisq/temp_dof>>hist1', condition) tree.Draw('fit_chisq/fit_dof>>hist2', condition) for i, hist in [(0, hist1), (1, hist2)]: hist.SetLineColor(colors[i]) hist.SetLineWidth(3) maxi = max(hist1.GetMaximum(), hist2.GetMaximum()) * 1.1 plot = SingleHistBase(hist1, 'hist_numberPerChisq', fill=None, workinprogress=wip) gStyle.SetOptStat(10) plot._xtitle = '#chi^{2}/d.o.f.' plot._ytitle = 'number of toys' plot.yrange(0.0, maxi) leg = TLegend(0.65, 0.75, 0.89, 0.85) leg.SetBorderSize(0) leg.AddEntry(hist1, 'DG fit', 'L') leg.AddEntry(hist2, 'SupDG fit', 'L') plot.draw() hist2.Draw('SAMEH') leg.Draw() plot.save_pdf() plot.Close() hist3 = TH2F('hist3', '', 31, -0.05, 3.05, 31, -0.05, 3.05) tree.Draw('100*temp_overlapDiff:100*fit_overlapDiff>>hist3', condition) one = TF1('one', 'x', -10.0, 10.0) one.SetLineColor(1) plot = SingleHistBase(hist3, 'correctionDGvsSupDG', fill=None, workinprogress=wip) plot.add(one) plot._drawoption = 'BOX' plot._xtitle = 'correction [%] from SupDG fit' plot._ytitle = 'correction [%] from DG fit' plot._above = True plot.draw() plot.save_pdf() plot.Close() hist4 = TH2F('hist4', '', 22, 0.95, 1.5, 22, 0.95, 1.5) tree.Draw('temp_chisq/temp_dof:fit_chisq/fit_dof>>hist4', condition) plot = SingleHistBase(hist4, 'chisqDGvsSupDG', fill=None, workinprogress=wip) plot.add(one) plot._drawoption = 'BOX' plot._xtitle = '#chi^{2}/d.o.f. of SupDG fit' plot._ytitle = '#chi^{2}/d.o.f. of DG fit' plot._above = True plot.draw() plot.save_pdf() plot.Close() gStyle.SetStatX(0.9) gStyle.SetStatY(0.83) gStyle.SetStatW(0.3) gStyle.SetStatH(0.08) #bins_csq = [(0.0, 1.1), (1.1, 1.3), (1.3, 1.6), (1.6, 2.0)] #bins_cor = [(0.0, 0.5), (0.5, 1.0), (1.0, 1.5), (1.5, 2.0), (2.0, 2.5)] #bins_csq = [(1.07, 1.13), (1.06, 1.11), (1.3, 1.5), (1.08, 1.17), (1.1, 1.2)] #bins_cor = [(0.3, 0.8), (0.9, 1.2), (0.1, 0.5), (0.4, 0.7), (0.3, 1.1)] bins_csq = [(0.99, 1.06), (0.98, 1.07), (0.99, 1.10), (1.02, 1.06), (1.00, 1.06), (1.00, 1.04)] bins_cor = [(0.9, 1.9), (0.4, 1.6), (0.6, 1.5), (0.6, 1.9), (1.0, 1.3), (0.3, 1.5)] means = { mod: [[0.0 for __ in bins_cor] for __ in bins_csq] for mod in ('DG', 'SupDG') } meane = { mod: [[0.0 for __ in bins_cor] for __ in bins_csq] for mod in ('DG', 'SupDG') } rmses = { mod: [[0.0 for __ in bins_cor] for __ in bins_csq] for mod in ('DG', 'SupDG') } rmser = { mod: [[0.0 for __ in bins_cor] for __ in bins_csq] for mod in ('DG', 'SupDG') } #for i, (csq_lo, csq_hi) in enumerate(bins_csq): # for j, (cor_lo, cor_hi) in enumerate(bins_cor): for i, ((csq_lo, csq_hi), (cor_lo, cor_hi)) in enumerate(zip(bins_csq, bins_cor)): j = i name = 'hist_{{0}}_{0}csq{1}_{2}cor{3}' \ .format(csq_lo, csq_hi, cor_lo, cor_hi) fields = '100*({0}_overlapDiff-toy_overlapDiff)>>hist' condition = ( '100*{{0}}_overlapDiff>={0} && 100*{{0}}_overlapDiff<{1} && ' '{{0}}_chisq/{{0}}_dof>={2} && {{0}}_chisq/{{0}}_dof<{3} && ' 'fit_overlapDiff>=0 && temp_overlapDiff>=0 && ' 'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2').format( cor_lo, cor_hi, csq_lo, csq_hi) xtitle = 'correction [%] from {0} fit #minus true correction [%]' line1 = '{0} < correction < {1}'.format(cor_lo, cor_hi) line2 = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi) gStyle.SetOptStat(2210) for prefix, modname in (('temp', 'DG'), ('fit', 'SupDG')): hist = TH1F('hist', '', 41, -2.05, 2.05) hist.StatOverflows() tree.Draw(fields.format(prefix), condition.format(prefix)) plot = SingleHistBase(hist, name.format(modname), fill=None, workinprogress=wip) gStyle.SetOptStat(2210) plot._xtitle = xtitle.format(modname) plot._ytitle = 'number of toys' plot.xrange(-2.05, 2.05) plot.yrange(0.0, plot._graph.GetMaximum() * 1.2) pave = plot.add_pave(0.6, 0.83, 0.9, 0.9, border=True) pave(line1) pave(line2) plot.draw() plot.save_pdf() means[modname][i][j] = plot._graph.GetMean() meane[modname][i][j] = plot._graph.GetMeanError() rmses[modname][i][j] = plot._graph.GetRMS() rmser[modname][i][j] = plot._graph.GetRMSError() plot.Close() multi = TMultiGraph('multi', '') for k, modname in enumerate(('DG', 'SupDG')): for i, (csq_lo, csq_hi) in enumerate(bins_csq): xval = array( 'd', [j - 0.35 + k * 0.4 + i * 0.1 for j in range(len(bins_cor))]) xerr = array('d', [0.0] * len(bins_cor)) yval = array('d', means[modname][i]) yerr = array('d', rmses[modname][i]) graph = TGraphErrors(len(bins_cor), xval, yval, xerr, yerr) graph.SetName('graph{0}{1}'.format(k, i)) graph.SetMarkerStyle(22 + k) graph.SetMarkerColor(colors[i]) graph.SetLineColor(colors[i]) multi.Add(graph) minvalues = [ means[mod][i][j] - rmses[mod][i][j] for j in range(len(bins_cor)) for i in range(len(bins_csq)) for mod in ('DG', 'SupDG') ] maxvalues = [ means[mod][i][j] + rmses[mod][i][j] for j in range(len(bins_cor)) for i in range(len(bins_csq)) for mod in ('DG', 'SupDG') ] mini, maxi = min(minvalues), max(maxvalues) mini, maxi = mini - 0.1 * (maxi - mini), maxi + 0.3 * (maxi - mini) hist = TH2F('axishist', '', len(bins_cor), -0.5, len(bins_cor) - 0.5, 100, mini, maxi) for j, (cor_lo, cor_hi) in enumerate(bins_cor): hist.GetXaxis().SetBinLabel(j + 1, '{0}% #minus {1}%'.format(cor_lo, cor_hi)) leg1 = TLegend(0.53, 0.78, 0.63, 0.86) leg1.SetBorderSize(0) dgmarker = TMarker(0.0, 0.0, 22) supdgmarker = TMarker(0.0, 0.0, 23) leg1.AddEntry(dgmarker, 'DG', 'P') leg1.AddEntry(supdgmarker, 'SupDG', 'P') leg2 = TLegend(0.65, 0.75, 0.89, 0.89) leg2.SetBorderSize(0) csqmarker = TMarker(0.0, 0.0, 1) for i, (csq_lo, csq_hi) in enumerate(bins_csq): title = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi) entry = leg2.AddEntry(csqmarker, title, 'L') entry.SetMarkerColor(colors[i]) entry.SetLineColor(colors[i]) zero = TF1('zero', '0.0', -1.0, 10.0) zero.SetLineColor(1) zero.SetLineStyle(2) plot = SingleHistBase(hist, name='differenceDoubleDifferential', fill=None, workinprogress=wip) plot._xtitle = 'correction from fit' plot._ytitle = 'correction [%] from fit #minus true correction [%]' plot.xrange(-0.5, len(bins_cor) - 0.5) plot.yrange(mini, maxi) plot._drawoption = 'AXIS' plot.draw() plot.xaxis().SetNdivisions(len(bins_cor), False) plot.xaxis().SetLabelSize(0.03) zero.Draw('SAME') multi.Draw('P') leg1.Draw() leg2.Draw() plot.save_pdf() plot.Close() bcid = (41, 281, 872, 1783, 2063) DGcor1 = array('d', [0.809, 0.392, 0.846, 0.731, 0.497]) DGerr1 = array('d', [0.548, 0.567, 0.984, 0.984, 1.018]) DGcor2 = array('d', [1.145, 0.799, 1.58, 1.465, 1.281]) DGerr2 = array('d', [0.432, 0.395, 0.656, 0.656, 0.649]) DGxval = array('d', [j - 0.1 for j in range(5)]) SupDGcor1 = array('d', [0.823, 0.761, 1.458, 0.986, 1.012]) SupDGerr1 = array('d', [0.513, 0.513, 0.499, 0.513, 0.499]) SupDGcor2 = array('d', [0.978, 0.916, 1.532, 1.141, 1.086]) SupDGerr2 = array('d', [0.489, 0.489, 0.493, 0.489, 0.493]) SupDGxval = array('d', [j + 0.1 for j in range(5)]) xerr = array('d', [0.0] * 5) for fill, values in [ (4266, { 'DGcor': [1.021, 1.057, 0.968, 1.084, 1.114], 'DGerr': [(e**2 + 0.74**2)**0.5 for e in (0.118, 0.124, 0.119, 0.117, 0.119)], 'SupDGcor': [1.402, 1.411, 1.164, 1.549, 1.589], 'SupDGerr': [(e**2 + 0.45**2)**0.5 for e in (0.106, 0.110, 0.108, 0.106, 0.115)], 'bcids': [51, 771, 1631, 2211, 2674] }), (4954, { 'DGcor': [0.799, 0.398, 0.845, 0.724, 0.502], 'DGerr': [(e**2 + 0.79**2)**0.5 for e in (0.137, 0.124, 0.122, 0.130, 0.116)], 'SupDGcor': [0.794, 0.694, 1.642, 0.983, 0.993], 'SupDGerr': [(e**2 + 0.50**2)**0.5 for e in (0.126, 0.112, 0.186, 0.102, 0.144)], 'bcids': [41, 281, 872, 1783, 2063] }), (4937, { 'DGcor': [0.649, 0.494, 0.575, 0.527, 0.602], 'DGerr': [(e**2 + 0.85**2)**0.5 for e in (0.127, 0.115, 0.120, 0.125)], 'SupDGcor': [0.377, 0.611, 1.137, 0.453, 1.840], 'SupDGerr': [(e**2 + 0.56**2)**0.5 for e in (0.100, 0.105, 0.288, 0.161, 0.207)], 'bcids': [81, 875, 1610, 1690, 1730] }), (6016, { 'DGcor': [0.146, 0.394, 0.377, 0.488, 0.184], 'DGerr': [(e**2 + 1.15**2)**0.5 for e in (0.110, 0.114, 0.118, 0.123, 0.109)], 'SupDGcor': [0.760, 0.953, 1.048, 0.847, 0.373], 'SupDGerr': [(e**2 + 0.79**2)**0.5 for e in (0.219, 0.094, 0.189, 0.098, 0.169)], 'bcids': [41, 281, 872, 1783, 2063] }) ]: bcid = values['bcids'] DGcor = array('d', values['DGcor']) DGerr = array('d', values['DGerr']) DGxvl = array('d', [j - 0.1 for j in range(len(bcid))]) SupDGcor = array('d', values['SupDGcor']) SupDGerr = array('d', values['SupDGerr']) SupDGxvl = array('d', [j + 0.1 for j in range(len(bcid))]) xerr = array('d', [0.0] * len(bcid)) maxi = max(max([v + e for v, e in zip(DGcor, DGerr)]), max([v + e for v, e in zip(SupDGcor, SupDGerr)])) mini = min(min([v - e for v, e in zip(DGcor, DGerr)]), min([v - e for v, e in zip(SupDGcor, SupDGerr)])) maxi, mini = maxi + 0.2 * (maxi - mini), mini - 0.1 * (maxi - mini) graphDG = TGraphErrors(len(bcid), DGxvl, DGcor, xerr, DGerr) graphDG.SetName('graphDG') graphSupDG = TGraphErrors(len(bcid), SupDGxvl, SupDGcor, xerr, SupDGerr) graphSupDG.SetName('graphSupDG') multi = TMultiGraph('multi', '') for i, graph in [(0, graphDG), (1, graphSupDG)]: graph.SetMarkerStyle(22 + i) graph.SetMarkerColor(colors[i]) graph.SetLineColor(colors[i]) multi.Add(graph) leg = TLegend(0.15, 0.80, 0.5, 0.83) leg.SetNColumns(2) leg.SetBorderSize(0) leg.AddEntry(graphDG, 'DG fit', 'PL') leg.AddEntry(graphSupDG, 'SupDG fit', 'PL') axishist = TH2F('axishist', '', len(bcid), -0.5, len(bcid) - 0.5, 100, mini, maxi) for i, bx in enumerate(bcid): axishist.GetXaxis().SetBinLabel(i + 1, '{0}'.format(bx)) plot = SingleHistBase(axishist, name='Fill{0}biased'.format(fill), fill=fill, workinprogress=wip) plot._xtitle = 'BCID' plot._ytitle = 'correction [%] from fit' plot.xrange(-0.5, len(bcid) - 0.5) plot.yrange(mini, maxi) plot._drawoption = 'AXIS' plot.draw() plot.xaxis().SetNdivisions(len(bcid), False) plot.xaxis().SetLabelSize(0.03) multi.Draw('P') leg.Draw() plot.save_pdf() plot.Close() print print 'Fill', fill for bx, cor, err in zip(bcid, SupDGcor, SupDGerr): print 'BCID {0}:\t{1:.2f} +- {2:.2f}'.format(bx, cor, err) print