def MakeCutflowPlot(samples, histograms, save_tag, legend_entries={}): c = TCanvas("c_{}".format(save_tag), "c_{}".format(save_tag), 800, 700) c.SetBottomMargin(0.2) l = TLegend(0.65, 0.55, 0.85, 0.85) l.SetFillColor(0) l.SetBorderSize(0) frame_cutflow = TH1F("frame_cutflow", "frame_cutflow", histograms[samples[0]].GetNbinsX(), histograms[samples[0]].GetXaxis().GetXmin(), histograms[samples[0]].GetXaxis().GetXmax()) for bin in xrange(1, histograms[samples[0]].GetNbinsX() + 1): frame_cutflow.GetXaxis().SetBinLabel(bin, histograms[samples[0]].GetXaxis().GetBinLabel(bin)) frame_cutflow.GetXaxis().SetNdivisions(frame_cutflow.GetXaxis().GetNbins(), 0, 0, False) frame_cutflow.GetYaxis().SetTitle("Fraction of events remaining") frame_cutflow.SetMaximum(1.1) frame_cutflow.Draw() style_counter = 0 for sample in samples: histograms[sample].SetLineColor(seaborn.GetColorRoot("cubehelixlarge", style_counter, len(samples))) histograms[sample].SetLineWidth(2) histograms[sample].SetLineStyle(1) histograms[sample].Draw("hist same") if sample in legend_entries: l.AddEntry(histograms[sample], legend_entries[sample], "l") else: l.AddEntry(histograms[sample], sample, "l") style_counter += 1 l.Draw() c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/{}.pdf".format(c.GetName())) c.SetLogy() c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/{}_log.pdf".format(c.GetName()))
def saveHistos(self, norm): ''' This is to save the histograms of the sample in a plot ''' if debug: print('Info in Sample.saveHistos()') c = TCanvas(self.name, self.name, 800, 600) c.DivideSquare(len(self.histos.keys())) for i, what in enumerate(self.histos.keys()): h = self.histos[what] pad = c.cd(i + 1) pad.SetLogx(self.histoDefs[what].logX) pad.SetLogy(self.histoDefs[what].logY) if norm and h.Integral() != 0: hdrawn = h.DrawNormalized('LPE') else: hdrawn = h.Draw('PLE') norm_suffix = '_norm' if norm else '' c.SaveAs('./plots/' + self.label + suffix + '/' + c.GetName() + norm_suffix + '.png') c.SaveAs('./plots/' + self.label + suffix + '/' + c.GetName() + norm_suffix + '.pdf') c.SaveAs('./plots/' + self.label + suffix + '/' + c.GetName() + norm_suffix + '.C')
def radialResidualPlots(crossings, shapes, chiSq, dof): kBird() gStyle.SetOptStat(0) components = ('X1', 'Y1', 'X2', 'Y2') for shape in shapes: for bx in crossings: f = TFile.Open('DataAnalysisBunch' + bx + shape + '_new_StronRescale.root') if not f: continue for comp in components: dataHist = f.Get('dataHist' + comp) modelHist = f.Get('modelHist' + comp) nbinsx = dataHist.GetXaxis().GetNbins() nbinsy = dataHist.GetYaxis().GetNbins() radialDat = TH1D('radialDat_'+shape+bx+comp, '', nbinsx/2, 0.0, \ dataHist.GetXaxis().GetXmax()) radialMod = TH1D('radialMod_'+shape+bx+comp, '', nbinsx/2, 0.0, \ dataHist.GetXaxis().GetXmax()) hist = TH1D('radialRes_'+shape+bx+comp, '', nbinsx/2, 0.0, \ dataHist.GetXaxis().GetXmax()) radialDat.Sumw2() for xbin in range(nbinsx + 1): for ybin in range(nbinsy + 1): r = (dataHist.GetXaxis().GetBinCenter(xbin)**2 + \ dataHist.GetYaxis().GetBinCenter(ybin)**2) ** 0.5 radialDat.Fill(r, dataHist.GetBinContent(xbin, ybin)) radialMod.Fill(r, modelHist.GetBinContent(xbin, ybin)) for rbin in range(nbinsx / 2 + 1): err = radialDat.GetBinError(rbin) if err > 0.0: pull = (radialDat.GetBinContent(rbin) - \ radialMod.GetBinContent(rbin)) / err else: pull = 0.0 hist.SetBinContent(rbin, pull) canvas = TCanvas('c_' + hist.GetName(), '', 600, 600) hist.Draw('HF') canvas.Update() hist.SetFillColor(4) hist.SetLineColor(1) hist.GetXaxis().SetTitle('r [cm]') hist.GetXaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitle('Pulls') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.1) hist.GetYaxis().SetRangeUser(-1.5, 5.0) pave = TPaveText(0.15, 0.79, 0.42, 0.88, 'NDC') pave.SetTextFont(42) pave.SetTextSize(0.025) pave.AddText('Scan ' + comp + ', BX ' + bx) pave.AddText(shapeNames[shape] + ' fit') redChiSq = chiSq[shape][bx] / dof[shape][bx] pave.AddText('#chi^{2}/d.o.f. = %6.4f' % (redChiSq)) pave.Draw('same') drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
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 correctionPlot(crossings, shapes, overDiff): nShapes = len(shapes) hist = makeShapesCrossingsHist(crossings, shapes, 'corrections') for i, bx in enumerate(crossings): for j, shape in enumerate(shapes): if overDiff[shape][bx]: correction = -100.0 * overDiff[shape][bx] hist.SetBinContent(i + 1, nShapes - j, correction) else: hist.SetBinContent(i + 1, nShapes - j, -1e6) canvas = TCanvas('c_' + hist.GetName(), '', 600, 600) hist.Draw('TEXTCOLZ') canvas.Update() hist.GetXaxis().SetNdivisions(len(crossings), False) hist.GetYaxis().SetNdivisions(nShapes, False) hist.GetZaxis().SetTitle('correction on overlap integral [%]') hist.GetZaxis().SetLabelSize(0.025) hist.GetZaxis().SetTitleOffset(0.5) hist.GetZaxis().SetRangeUser(-1.2, 0.0) hist.GetZaxis().CenterTitle() hist.GetZaxis().SetNdivisions(1, False) palette = hist.GetListOfFunctions().FindObject('palette') palette.SetX2NDC(0.929) drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
def exampleDataPlot(bx, shape, comp): kBird() f = TFile.Open('DataAnalysisBunch' + bx + shape + '_new_StronRescale.root') if f: hist = f.Get('dataHist' + comp) hist.SetTitle('') hist.SetName(bx + shape + '_dataHist' + comp) canvas = TCanvas('c_' + hist.GetName(), '', 600, 600) canvas.SetFrameFillColor(0) hist.Draw("COLZ") canvas.Update() hist.GetXaxis().SetTitle('x [cm]') hist.GetXaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitle('y [cm]') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.3) hist.GetZaxis().SetTitle('Number of Vertices') hist.GetZaxis().SetLabelSize(0.025) hist.GetZaxis().SetTitleOffset(0.7) hist.GetZaxis().SetRangeUser(0.0, 240.0) hist.GetZaxis().CenterTitle() hist.GetZaxis().SetNdivisions(1, False) palette = hist.GetListOfFunctions().FindObject('palette') palette.SetX2NDC(0.929) pave = TPaveText(0.65, 0.82, 0.88, 0.88, 'NDC') pave.SetTextFont(42) pave.SetTextSize(0.025) pave.AddText('Scan ' + comp + ', BX ' + bx) pave.AddText('Measured data') pave.Draw('same') drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
def chiSqPlot(crossings, shapes, chiSq, dof): nShapes = len(shapes) hist = makeShapesCrossingsHist(crossings, shapes, 'chisq') for i, bx in enumerate(crossings): for j, shape in enumerate(shapes): if chiSq[shape][bx]: redChiSq = chiSq[shape][bx] / dof[shape][bx] hist.SetBinContent(i + 1, nShapes - j, redChiSq) canvas = TCanvas('c_' + hist.GetName(), '', 600, 600) hist.Draw('TEXTCOLZ') canvas.Update() hist.GetXaxis().SetNdivisions(len(crossings), False) hist.GetYaxis().SetNdivisions(nShapes, False) hist.GetZaxis().SetTitle('#chi^{2} / d.o.f.') hist.GetZaxis().SetLabelSize(0.025) hist.GetZaxis().SetTitleOffset(0.5) hist.GetZaxis().SetRangeUser(1.00, 1.12) hist.GetZaxis().CenterTitle() hist.GetZaxis().SetNdivisions(1, False) palette = hist.GetListOfFunctions().FindObject('palette') palette.SetX2NDC(0.929) drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
class ViewPane(object): nviews = 0 def __init__(self, name, projection, nx, xmin, xmax, ny, ymin, ymax, dx=600, dy=600): self.projection = projection tx = 50 + self.__class__.nviews * (dx + 10) ty = 50 self.canvas = TCanvas(name, name, tx, ty, dx, dy) TH1.AddDirectory(False) self.hist = TH2F(name, name, nx, xmin, xmax, ny, ymin, ymax) TH1.AddDirectory(True) self.hist.Draw() self.hist.SetStats(False) self.registered = dict() self.locked = dict() self.__class__.nviews += 1 def register(self, obj, layer, clearable=True): self.registered[obj] = layer if not clearable: self.locked[obj] = layer #TODO might need to keep track of views in objects def clear(self): self.registered = dict(self.locked.items()) def draw(self): self.canvas.cd() for obj, layer in sorted(self.registered.items(), key=operator.itemgetter(1)): obj.draw(self.projection) self.canvas.Update() def zoom(self, xmin, xmax, ymin, ymax): self.hist.GetXaxis().SetRangeUser(xmin, xmax) self.hist.GetYaxis().SetRangeUser(ymin, ymax) self.canvas.Update() def unzoom(self): self.hist.GetXaxis().UnZoom() self.hist.GetYaxis().UnZoom() self.canvas.Modified() self.canvas.Update() def save(self, outdir, filetype): fname = '{outdir}/{name}.{filetype}'.format(outdir=outdir, name=self.canvas.GetName(), filetype=filetype) self.canvas.SaveAs(fname)
def plot1D(): """On a TCanvas, plot 1D xsec""" outdir = os.path.join(outdir_1D_root, q2wbin) if not os.path.isdir(outdir): os.makedirs(outdir) #cname='1D_q2wbin_%d'%d_q2w['q2wbinnum'].tolist()[0] #ctitle='1D:%s'%q2wbin cname = ctitle = '1D' c1D = TCanvas(cname, ctitle) c1D.Divide(3, 3) npads = 9 hname = [] hname = [ 'h1_1M1', 'h1_1M2', 'h1_3M2', #TODO: h1_1M2->h1_2M2 'h1_1THETA', 'h1_2THETA', 'h1_3THETA', 'h1_1ALPHA', 'h1_2ALPHA', 'h1_3ALPHA' ] htitle = [] htitle = [ VARS_TITLE[0][M1], VARS_TITLE[0][M2], VARS_TITLE[1][M2], VARS_TITLE[0][THETA], VARS_TITLE[1][THETA], VARS_TITLE[2][THETA], VARS_TITLE[0][ALPHA], VARS_TITLE[1][ALPHA], VARS_TITLE[2][ALPHA] ] hxtitle = ['GeV', 'GeV', 'GeV', '#circ', '#circ', '#circ'] activepads = [1, 4, 2] EF_UNP_sel = (d_q2w['SEQ'] == EF) & (d_q2w['POL'] == UNP) SF_UNP_sel = (d_q2w['SEQ'] == SF) & (d_q2w['POL'] == UNP) d_q2w_EF_UNP = d_q2w[EF_UNP_sel] d_q2w_SF_UNP = d_q2w[SF_UNP_sel] for ipad in range(0, npads): if ipad + 1 not in activepads: continue c1D.cd(ipad + 1) h1_exp = d_q2w_EF_UNP.iloc[0][hname[ipad]] h1_sim = d_q2w_SF_UNP.iloc[0][hname[ipad]] h1_exp.SetTitle('%s:%s' % (htitle[ipad], q2wbin)) h1_exp.SetXTitle('%s[%s]' % (htitle[ipad], hxtitle[ipad])) h1_sim.SetLineColor(1) h1_exp.DrawNormalized("ep", 10000) h1_sim.DrawNormalized("ep same", 10000) csavename = ('%s/%s') % (outdir, c1D.GetName()) c1D.SaveAs(('%s.png') % (csavename)) print('>>>convert %s.png %s.pdf') % (csavename, csavename) rc = subprocess.call( ['convert', '%s.png' % csavename, '%s.pdf' % csavename]) if rc != 0: print '.png to .pdf failed for %s' % csavename
def MakeBasicPlots(samples, sample_output_files, legend_entries = {}): rebin = { "h_CA15Jet_msd":5, } plots_1D = ["h_CA15Jet_msd", "h_CA15Jet_doublecsv", "h_CA15Jet_tau21", "h_CA15Jet_tau32", "h_nminusone_Max_CA15Puppijet0_tau21DDT", "h_nminusone_Min_CA15CHSjet0_doublecsv"] plots_2D = ["h_CA15Jet_msd_vs_doublecsv","h_CA15Jet_msd_vs_tau21","h_CA15Jet_msd_vs_tau32","h_CA15Jet_doublecsv_vs_tau21","h_CA15Jet_tau21_vs_tau32"] for sample in samples: f = TFile(sample_output_files[sample], "READ") os.system("mkdir -pv /uscms/home/dryu/DAZSLE/data/EventSelection/figures/CA15_{}/".format(sample)) for plot in plots_1D: h = f.Get(plot) if plot in rebin: h.Rebin(rebin[plot]) c = TCanvas("c_{}_{}".format(plot.replace("h_", ""), sample), "c_{}_{}".format(plot.replace("h_", ""), sample), 800, 600) h.DrawNormalized() c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/CA15_{}/{}.pdf".format(sample, c.GetName())) for plot in plots_2D: h = f.Get(plot) c = TCanvas("c_{}_{}".format(plot.replace("h_", ""), sample), "c_{}_{}".format(plot.replace("h_", ""), sample), 800, 600) h.Draw("colz") c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/CA15_{}/{}.pdf".format(sample, c.GetName())) f.Close() # All 1D plots on the same canvas for plot in plots_1D: c = TCanvas("c_{}_all".format(plot.replace("h_", "")), "c_{}_all".format(plot.replace("h_", "")), 800, 600) c.SetRightMargin(0.2) l = TLegend(0.81, 0.4, 0.99, 0.9) l.SetFillColor(0) l.SetBorderSize(1) style_counter = 0 for sample in samples: f = TFile(sample_output_files[sample], "READ") h = f.Get(plot) if plot in rebin: h.Rebin(rebin[plot]) h.SetMaximum(h.GetMaximum() * 1.3) h.SetName(h.GetName() + "_" + sample) h.SetDirectory(0) h.SetMarkerColor(seaborn.GetColorRoot("cubehelixlarge", style_counter, len(samples))) h.SetMarkerStyle(20 + style_counter) h.SetLineColor(seaborn.GetColorRoot("cubehelixlarge", style_counter, len(samples))) if style_counter == 0: if plot == "h_CA15Jet_msd": h.GetXaxis().SetRangeUser(0., 600.) h.DrawNormalized("hist") h.DrawNormalized("hist same") h.DrawNormalized("pe same") if sample in legend_entries: l.AddEntry(h, legend_entries[sample], "pl") else: l.AddEntry(h, sample, "pl") style_counter += 1 l.Draw() c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/{}_CA15.pdf".format(c.GetName())) c.SetLogy() c.SaveAs("/uscms/home/dryu/DAZSLE/data/EventSelection/figures/{}_CA15_log.pdf".format(c.GetName()))
def MakeCSVEfficiencyPlot(samples, histograms, save_tag, legend_entries={}): c = TCanvas("c_{}".format(save_tag), "c_{}".format(save_tag), 800, 600) l = TLegend(0.65, 0.55, 0.85, 0.85) l.SetFillColor(0) l.SetBorderSize(0) frame_csv = TH1F("frame_csv", "frame_csv", 100, histograms[samples[0]].GetXaxis().GetXmin(), histograms[samples[0]].GetXaxis().GetXmax()) frame_csv.GetXaxis().SetTitle("Double b-tag cut") frame_csv.GetYaxis().SetTitle("Efficiency") frame_csv.SetMaximum(1.1) frame_csv.Draw("axis") efficiency_tgraphs = {} style_counter = 0 for sample in samples: total_events = histograms[sample].Integral( 0, histograms[sample].GetNbinsX() + 1) efficiency_tgraphs[sample] = TGraphErrors( histograms[sample].GetNbinsX()) efficiency_tgraphs[sample].SetName("csv_efficiency_{}".format(sample)) for bin in xrange(1, histograms[sample].GetNbinsX() + 1): pass_events = histograms[sample].Integral( bin, histograms[sample].GetNbinsX() + 1) efficiency = 1. * pass_events / total_events defficiency = max( sqrt(efficiency * (1. - efficiency) / total_events), 1. / total_events) efficiency_tgraphs[sample].SetPoint( bin - 1, histograms[sample].GetXaxis().GetBinLowEdge(bin), efficiency) efficiency_tgraphs[sample].SetPointError(bin - 1, 0., defficiency) efficiency_tgraphs[sample].SetMarkerStyle(20 + style_counter) efficiency_tgraphs[sample].SetMarkerSize(1) efficiency_tgraphs[sample].SetMarkerColor( seaborn.GetColorRoot("cubehelixlarge", style_counter, len(samples))) efficiency_tgraphs[sample].SetLineStyle(1) efficiency_tgraphs[sample].SetLineWidth(1) efficiency_tgraphs[sample].SetLineColor( seaborn.GetColorRoot("cubehelixlarge", style_counter, len(samples))) efficiency_tgraphs[sample].Draw("pl") if sample in legend_entries: l.AddEntry(efficiency_tgraphs[sample], legend_entries[sample], "pl") else: l.AddEntry(efficiency_tgraphs[sample], sample, "pl") style_counter += 1 l.Draw() c.SaveAs( "/uscms/home/dryu/DAZSLE/data/EventSelection/figures/{}.pdf".format( c.GetName()))
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 plotR2(seq_pol_sell): """On a TCanvas, plot R2 for a list of particular SEQ and POL selections Keyword arguments: seq_pol_sell -- A List of DataFrame selections based on SEQ and POL """ l = TLine(0, 0, 180, 0) # will be used for all hR2 objects for seq_pol_sel in seq_pol_sell: d_q2w_seq_pol = d_q2w[seq_pol_sel] #print dq2w_seq_pol seq = d_q2w_seq_pol.iloc[0]['SEQ'] pol = d_q2w_seq_pol.iloc[0]['POL'] outdir_seq_pol = os.path.join(outdir_q2w, SEQ_NAME[seq], POLS_NAME[pol]) if not os.path.isdir(outdir_seq_pol): os.makedirs(outdir_seq_pol) for pob in range(0, NPOBS): if pob == A: continue for var in range(0, NVARS): if var == PHI or var == ALPHA: continue hR2_name = 'hR2_%s_1%s' % (POBS_NAME[pob], VARS_NAME[var]) hR2 = d_q2w_seq_pol.iloc[0][hR2_name] cR2 = TCanvas(hR2_name, hR2_name) hR2.SetLineColor(gROOT.ProcessLine("%s" % POLS_COLOR[pol])) hR2.SetTitle("") # will be made "prettier" later hR2.Draw("ep") #make Title of hR2 "pretty" l.Draw("same") pt = TPaveText(0.3, 0.85, 0.7, 1.0, "NDC") q2wt = pt.AddText('[Q^{2}][W] = %s' % q2wbin) q2wt.SetTextColor(gROOT.ProcessLine("kBlue")) vart = pt.AddText( ("%s,%s: %s^{%s} vs. %s") % (SEQ_NAME[seq], POLS_NAME[pol], POBS_NAME[pob], VARS_TITLE[0][var], VARS_TITLE[0][var])) vart.SetTextSize(0.05) pt.Draw() csavename = ('%s/%s') % (outdir_seq_pol, cR2.GetName()) cR2.SaveAs(('%s.png') % (csavename)) print('>>>convert %s.png %s.pdf') % (csavename, csavename) rc = subprocess.call( ['convert', '%s.png' % csavename, '%s.pdf' % csavename]) if rc != 0: print '.png to .pdf failed for %s' % csavename
def PlotPosteriors(ListOfPosteriors, outputname = ""): RepeatIteration = False if (outputname != "" ): outputname = "_"+outputname c = TCanvas("Posteriors"+outputname,"Posteriors"+outputname,0,0,1600, 1600) c.Divide(math.ceil(pow(len(ListOfPosteriors),0.5)),math.ceil(pow(len(ListOfPosteriors),0.5))) legends = [] for i in range(len(ListOfPosteriors)): ListOfPosteriors[i].SetMaximum(ListOfPosteriors[i].GetMaximum()*2.0) #ListOfPosteriors[i].Fit("gaus") fit = ListOfPosteriors[i].GetFunction("gaus") chi2 = fit.GetChisquare() p1 = fit.GetParameter(1) #p0 = fit.GetParameter(0) p2 = fit.GetParameter(2) FitIntegral = fit.Integral(p1-10*p2,p1+10*p2) # fit integral , get mean plus minus 10 sigma PriorIntegral = ListOfPosteriors[i].Integral("width") Percentage = round((100*PriorIntegral/FitIntegral),0) c.cd(i+1) gPad.SetFrameFillColor(10) if (Percentage < 90): gPad.SetFillColor(kRed-4) RepeatIteration = True else: gPad.SetFillColor(8) leg = TLegend(0.1,0.5,0.85,0.9) leg.SetFillStyle(0) leg.AddEntry(None,"MeanHist = "+str(round(ListOfPosteriors[i].GetMean(),0))+", RMShist = "+str(round(ListOfPosteriors[i].GetRMS(),0))+", MeanFit = "+str(round(p1,0))+", #sigma_{fit} = "+str(round(p2,0)),"") leg.AddEntry(ListOfPosteriors[i],"Posterior ","l") leg.AddEntry(fit,"Fit ","l") leg.AddEntry(None,"#chi^{2}/NDF = "+str(round(chi2/len(ListOfPosteriors),2)),"") leg.AddEntry(None,"Integral Prior/Fit = "+str(round(Percentage,0))+" %","") leg.SetBorderSize(0) legends.append(leg) ListOfPosteriors[i].SetTitle("Posterior in bin "+str(i+1)) gStyle.SetOptStat(0) ListOfPosteriors[i].Draw() legends[i].Draw("same") if (round(chi2/len(ListOfPosteriors),2)) > 20.0: RepeatIteration = True #c.Update() c.cd(1) gStyle.SetOptStat(0) #gPad.Modified() #c.Update() PrintCan(c,c.GetName()+"_posteriors") return RepeatIteration
def residualPlots(crossings, shapes, chiSq, dof): kBird() components = ('X1', 'Y1', 'X2', 'Y2') for shape in shapes: for bx in crossings: f = TFile.Open('DataAnalysisBunch' + bx + shape + '_new_StronRescale.root') if not f: continue for comp in components: hist = f.Get('res' + comp) for xbin in range(hist.GetXaxis().GetNbins() + 1): for ybin in range(hist.GetYaxis().GetNbins() + 1): if hist.GetBinContent(xbin, ybin) < -4.99999: hist.SetBinContent(xbin, ybin, -4.99999) if hist.GetBinContent(xbin, ybin) == 0.0: hist.SetBinContent(xbin, ybin, -10.0) hist.SetTitle('') hist.SetName(bx + shape + '_res' + comp) canvas = TCanvas('c_' + hist.GetName(), '', 600, 600) hist.Draw('COLZ') canvas.Update() hist.GetXaxis().SetTitle('x [cm]') hist.GetXaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitle('y [cm]') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.3) hist.GetZaxis().SetTitle('Pulls') hist.GetZaxis().SetLabelSize(0.025) hist.GetZaxis().SetTitleOffset(0.9) hist.GetZaxis().SetRangeUser(-5.0, 5.0) palette = hist.GetListOfFunctions().FindObject('palette') palette.SetX2NDC(0.929) pave = TPaveText(0.61, 0.79, 0.88, 0.88, 'NDC') pave.SetTextFont(42) pave.SetTextSize(0.025) pave.AddText('Scan ' + comp + ', BX ' + bx) pave.AddText(shapeNames[shape] + ' fit') redChiSq = chiSq[shape][bx] / dof[shape][bx] pave.AddText('#chi^{2}/d.o.f. = %6.4f' % (redChiSq)) pave.Draw('same') drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
def MakeOneDHist(histogramDirectory, histogramName,integrateDir): if arguments.verbose: print "Creating histogram", histogramName, "in directory", histogramDirectory HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetTextFont(42) HeaderLabel.SetTextSize(0.697674) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") CMSLabel.SetTextAlign(32) CMSLabel.SetTextFont(42) CMSLabel.SetTextSize(0.697674) CMSLabel.SetBorderSize(0) CMSLabel.SetFillColor(0) CMSLabel.SetFillStyle(0) if makeFancy: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC") LumiLabel.SetTextFont(62) LumiLabel.SetTextSize(0.7) LumiLabel.SetTextAlign(12) else: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC") LumiLabel.SetTextAlign(32) LumiLabel.SetTextFont(42) LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) canvasName = histogramName if integrateDir is "left": canvasName += "_CumulativeLeft" elif integrateDir is "right": canvasName += "_CumulativeRight" Canvas = TCanvas(canvasName) Histograms = [] RefIndex = -99 LegendEntries = [] colorIndex = 0 markerStyleIndex = 0 fillIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset']) inputFile = TFile(dataset_file) if arguments.generic: if histogramDirectory == "": histPath = histogramName else: histPath = histogramDirectory + "/" + histogramName HistogramObj = inputFile.Get(histPath) else: HistogramObj = inputFile.Get(source['channel'] + "Plotter/" + histogramDirectory + "/" + histogramName) if not HistogramObj: print "WARNING: Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = HistogramObj.Clone() Histogram.SetDirectory(0) inputFile.Close() Histogram.Sumw2() if arguments.verbose: print " Got histogram", Histogram.GetName(), "from file", dataset_file if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1: Histogram.Rebin(RebinFactor) # correct bin contents of object multiplcity plots if Histogram.GetName().startswith("num") and "PV" not in Histogram.GetName(): # include overflow bin for bin in range(2,Histogram.GetNbinsX()+2): content = Histogram.GetBinContent(bin) Histogram.SetBinContent(bin, content/float(bin-1)) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") xAxisLabelVar = xAxisLabel if "_pfx" in Histogram.GetName() or "_pfy" in Histogram.GetName() or "_sigma" in Histogram.GetName(): yAxisLabel = Histogram.GetYaxis().GetTitle() else: if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] xAxisLabelVar = xAxisLabel[0:unitBeginIndex] else: yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" if arguments.normalizeToUnitArea and arguments.makeSignificancePlots: unit = "Efficiency" else: unit = "Yield" if integrateDir is "left": yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" if integrateDir is "right": yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" nbins = Histogram.GetNbinsX() if not noOverFlow: Histogram.SetBinContent(nbins, Histogram.GetBinContent(nbins) + Histogram.GetBinContent(nbins+1)) # Add overflow Histogram.SetBinError(nbins, math.sqrt(math.pow(Histogram.GetBinError(nbins),2) + math.pow(Histogram.GetBinError(nbins+1),2))) # Set the errors to be the sum in quadrature if not noUnderFlow: Histogram.SetBinContent(1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) # Add underflow Histogram.SetBinError(1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) # Set the errors to be the sum in quadrature if not arguments.makeFancy and not arguments.generic: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") if len(splitTitle) > 1: histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = splitTitle[0] else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyleIndex = markerStyleIndex + 1 if markerStyleIndex is len(markerStyleList): markerStyleIndex = 0 fillIndex = fillIndex + 1 if 'scale' in source: Histogram.Scale(source['scale']) markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] else: markerStyle = markers[markerStyleList[markerStyleIndex]] fillStyle = 0 if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] else: markerStyle = markerStyle + fills[fillList[fillIndex]] Histogram.SetMarkerStyle(markerStyle) Histogram.SetMarkerSize(0.5) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) if arguments.normalizeToUnitArea and Histogram.Integral() > 0: Histogram.Scale(1./Histogram.Integral()) Histogram = MakeIntegralHist(Histogram, integrateDir) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) if 'reference' in source: if source['reference']: RefIndex = len(Histograms)-1 ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") # Legend.AddEntry(histogram,LegendEntries[legendIndex],"P") legendIndex = legendIndex+1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 for histogram in Histograms: currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin()) if(currentMax > finalMax): finalMax = currentMax finalMax = 1.5*finalMax if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots addOneToRatio = -1 if arguments.addOneToRatio: addOneToRatio = arguments.addOneToRatio yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.generic: plotting_options = "p,e" if arguments.plot_hist: plotting_options = "HIST" for histogram in Histograms: histogram.SetTitle(histoTitle) if arguments.verbose: print " Drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor()) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) histogram.SetMaximum(finalMax) if "_pfx" not in Histogram.GetName() and "_pfy" not in Histogram.GetName() and "_sigma" not in Histogram.GetName(): histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: plotting_options = plotting_options + " SAME" histCounter = histCounter + 1 #legend coordinates, empirically determined :-) x_left = 0.1677852 x_right = 0.9647651 y_min = 0.6765734 y_max = 0.9 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() # Deciding which text labels to draw and drawing them if arguments.makeFancy: HeaderLabel.Draw() LumiLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Comparisons = [] Canvas.cd(2) if RefIndex == -99: Reference = Histograms[0] else: Reference = Histograms[RefIndex] for Histogram in Histograms: if Histogram is Reference: continue if makeRatioPlots: makeRatio = functools.partial (ratioHistogram,Histogram, Reference) if arguments.ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, relErrMax = float(arguments.ratioRelErrMax)) if addOneToRatio != -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio)) Comparison = makeRatio() elif makeDiffPlots: Comparison = Reference.Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("X-ref") Comparison.SetLineColor(Histogram.GetLineColor()) Comparison.SetFillColor(Histogram.GetFillColor()) Comparison.SetFillStyle(Histogram.GetFillStyle()) Comparison.SetMarkerColor(Histogram.GetMarkerColor()) Comparison.SetMarkerStyle(Histogram.GetMarkerStyle()) Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) if addOneToRatio == -1: # it gets initialized to this dummy value of -1 Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange) else: Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) Comparisons.append(Comparison) option = "E0" for index,Comparison in enumerate(Comparisons): if index == 0: option += " SAME" Comparison.Draw(option) outputFile.cd(histogramDirectory) Canvas.Write() if arguments.verbose: print " Finished writing canvas: ", Canvas.GetName() if arguments.savePDFs: Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")
if xs < min_xs: min_xs = xs xs_graphs[sqrts] = TGraph(len(this_xss)) for i, mass in enumerate(sorted(this_xss.keys())): xs_graphs[sqrts].SetPoint(i, mass, this_xss[mass]) xs_graphs[8].SetMarkerStyle(20) xs_graphs[8].SetMarkerColor(seaborn_colors.get_root_color("Oranges_d", 1)) xs_graphs[8].SetLineColor(seaborn_colors.get_root_color("Oranges_d", 1)) xs_graphs[13].SetMarkerStyle(22) xs_graphs[13].SetMarkerColor(seaborn_colors.get_root_color("Blues_d", 3)) xs_graphs[13].SetLineColor(seaborn_colors.get_root_color("Blues_d", 3)) c = TCanvas("c_reference_xses", "Reference #sigma", 800, 600) c.SetLogy() frame = TH1F("frame", "frame", 100, 0., 1500.) frame.GetXaxis().SetTitle("m_{Z'} [GeV]") frame.GetYaxis().SetTitle("#sigma(pp#rightarrow Z') [pb]") frame.SetMinimum(min_xs / 10.) frame.SetMaximum(max_xs * 10.) frame.Draw() xs_graphs[8].Draw("cp") xs_graphs[13].Draw("cp") l = TLegend(0.7, 0.7, 0.88, 0.88) l.SetFillStyle(0) l.SetBorderSize(0) l.AddEntry(xs_graphs[8], "#sqrt{s}=8 TeV", "pl") l.AddEntry(xs_graphs[13], "#sqrt{s}=13 TeV", "pl") l.Draw() c.SaveAs("plots/{}.pdf".format(c.GetName()))
def plotR2(h5, seql, poll): norm = 50000 for var in range(0, NVARS): if var == PHI or var == ALPHA: continue for pobs in range(0, NPOBS): if pobs == A: continue for seq in seql: outdir_seq = os.path.join(outdir_q2w, SEQ_NAME[seq]) if not os.path.isdir(outdir_seq): os.makedirs(outdir_seq) cname = ('R2_%s_1%s') % (POBS_NAME[pobs], VARS_NAME[var]) l = TLine(0, 0, 180, 0) cR2 = TCanvas(cname, cname) #"RvVar", "RvVar") hR2 = {} #pltnum=0 for pol in poll: outdir_pol = os.path.join(outdir_seq, POLS_NAME[pol]) if not os.path.isdir(outdir_pol): os.makedirs(outdir_pol) if pol != AVG: hR2[(pol)] = h5[(seq, pol, pobs)].Projection(var) hR2[(pol)].Scale(1 / math.pi) hR2[(pol)].Scale(1 / norm) hR2[(pol)].SetLineColor( gROOT.ProcessLine("%s" % POLS_COLOR[pol])) hR2[(pol)].SetMarkerStyle( gROOT.ProcessLine("kFullCircle")) elif pol == AVG: hR2[(AVG)] = hR2[(POS)].Clone("avg") hR2[(AVG)].Add(hR2[(NEG)]) hR2[(AVG)].Scale(0.5) if pobs == D: hR2[(AVG)].SetMinimum(-0.003) hR2[(AVG)].SetMaximum(0.003) #Make Titles nice hR2[(pol)].SetTitle("") #hR2[(NEG)].SetTitle("") #hR2[(AVG)].SetTitle("") #cR2 = {} #l = TLine(0,0,180,0) #cname = ('R2%sV%s')%(VARS_NAME[var],VARS_NAME[var]) #if pltnum==0: hR2[(pol)].Draw("ep") #else: # hR2[(pol)].Draw("ep same") # hR2[(NEG)].Draw("ep same") #hR2[(AVG)].Draw("ep same") l.Draw("same") pt = TPaveText(0.3, 0.85, 0.7, 1.0, "NDC") q2wt = pt.AddText('[Q^{2}][W] = %s' % q2wdir.GetName()) q2wt.SetTextColor(gROOT.ProcessLine("kBlue")) vart = pt.AddText( ("%s,%s: %s^{%s} vs. %s") % (SEQ_NAME[seq], POLS_NAME[pol], POBS_NAME[pobs], VARS_TITLE[0][var], VARS_TITLE[0][var])) vart.SetTextSize(0.05) pt.Draw() csavename = ('%s/%s') % (outdir_pol, cR2.GetName()) cR2.SaveAs(('%s.png') % (csavename)) print('>>>convert %s.png %s.pdf') % (csavename, csavename) rc = subprocess.call([ 'convert', '%s.png' % csavename, '%s.pdf' % csavename ]) if rc != 0: print '.png to .pdf failed for %s' % csavename
class GQSummaryPlot: def __init__(self, name): self._name = name self._analyses = [] self._dijet_data = {} self._legend_entries = {} self._graphs = {} self._limit_fills = {} self._GoMs = [] self._vtype = "vector" self._style = { "default": { "line_color": 1, "line_width": 402, "line_style": 1, "marker_style": 20, "marker_size": 0, "marker_color": 1, "fill_style": 3004, "fill_color": 0, } } # style = dict of <analysis name>:{"line_color":1, "marker_style":20, etc} # See the default option in __init__ for the full list of options def set_style(self, style): self._style.update(style) def set_vtype(self, vtype): vtype = vtype.lower() if not vtype in ["vector", "axial"]: raise ValueError( "[set_vtype] Argument vtype must be 'vector' or 'axial'") self._vtype = vtype def add_data(self, dijet_data, name, legend, max_gom=False, max_gq=False): self._analyses.append(name) self._dijet_data[name] = dijet_data self._legend_entries[name] = legend self._graphs[name] = dijet_data.get_graph() if max_gom: self._limit_fills[name] = self.create_limit_gom_fill( dijet_data.get_graph(), max_gom) if max_gq: self._limit_fills[name] = self.create_limit_gq_fill( dijet_data.get_graph(), max_gq) def set_width_curves(self, GoMs): self._GoMs = GoMs def style_graph(self, graph, name): if not name in self._style: print "[style_graph] ERROR : Analysis {} is not present in the style dict. Please add.".format( name) sys.exit(1) if "line_color" in self._style[name]: graph.SetLineColor(self._style[name]["line_color"]) else: graph.SetLineColor(self._style["default"]["line_color"]) if "line_style" in self._style[name]: graph.SetLineStyle(self._style[name]["line_style"]) else: graph.SetLineStyle(self._style["default"]["line_style"]) if "line_width" in self._style[name]: graph.SetLineWidth(self._style[name]["line_width"]) else: graph.SetLineWidth(self._style["default"]["line_width"]) if "marker_color" in self._style[name]: graph.SetMarkerColor(self._style[name]["marker_color"]) else: graph.SetMarkerColor(self._style["default"]["marker_color"]) if "marker_style" in self._style[name]: graph.SetMarkerStyle(self._style[name]["marker_style"]) else: graph.SetMarkerStyle(self._style["default"]["marker_style"]) if "marker_size" in self._style[name]: graph.SetMarkerSize(self._style[name]["marker_size"]) else: graph.SetMarkerSize(self._style["default"]["marker_size"]) if "fill_style" in self._style[name]: graph.SetFillStyle(self._style[name]["fill_style"]) else: graph.SetFillStyle(self._style["default"]["fill_style"]) if "fill_color" in self._style[name]: graph.SetFillColor(self._style[name]["fill_color"]) else: graph.SetFillColor(self._style["default"]["fill_color"]) # Create a polygon TGraph corresponding to the excluded range including an upper limit from Gamma/M # This is pretty ugly. Can it be improved? def create_limit_gom_fill(self, limit_graph, max_gom): tf_gom = TF1( "tmp_tf1_gq_{}".format(max_gom), lambda x, this_gom=max_gom: gom_to_gq(this_gom, x[0], self._vtype), 0.1, 10000., 0) # # Calculate new graph that stays at or below the gom curve new_limit_points = {} limit_x = limit_graph.GetX() limit_y = limit_graph.GetY() for i in xrange(limit_graph.GetN() - 1): x1 = limit_x[i] x2 = limit_x[i + 1] y1 = limit_y[i] y2 = limit_y[i + 1] gom1 = tf_gom.Eval(x1) gom2 = tf_gom.Eval(x2) if (y1 < gom1 and y2 > gom2) or (y1 > gom1 and y2 < gom2): # Calculate intersection of interpolation with GOM using bisection xlow = x1 xhigh = x2 ylow = y1 yhigh = y2 gomlow = tf_gom.Eval(xlow) gomhigh = tf_gom.Eval(xhigh) for j in xrange(20): xmid = (xlow + xhigh) / 2. ymid = (ylow + yhigh) / 2. gommid = tf_gom.Eval(xmid) if (ylow < gomlow and ymid < gommid) or (ylow > gomlow and ymid > gommid): xlow = xmid ylow = ymid gomlow = gommid elif (yhigh < gomhigh and ymid < gommid) or (yhigh > gomhigh and yhigh > gomhigh): xhigh = xmid yhigh = ymid gomhigh = gommid int_x = (xhigh + xlow) / 2. int_y = (yhigh + ylow) / 2. new_limit_points[int_x] = int_y # Move any old points above the GOM to the GOM for i in xrange(limit_graph.GetN()): if limit_y[i] > tf_gom.Eval(limit_x[i]): new_limit_points[limit_x[i]] = tf_gom.Eval(limit_x[i]) else: new_limit_points[limit_x[i]] = limit_y[i] # New graph: limit points new_graph = TGraph(len(new_limit_points) + 10000) for i, x in enumerate(sorted(new_limit_points.keys())): new_graph.SetPoint(i, x, new_limit_points[x]) # New graph: upper boundary corresponding to GOM xmin = min(new_limit_points.keys()) xmax = max(new_limit_points.keys()) for i in xrange(10001): this_x = xmax + (xmin - xmax) * i / 10000. new_graph.SetPoint( len(new_limit_points) + i, this_x, tf_gom.Eval(this_x)) return new_graph def create_limit_gq_fill(self, limit_graph, max_gq): # Calculate new graph that stays at or below max_gq new_limit_points = {} limit_x = limit_graph.GetX() limit_y = limit_graph.GetY() for i in xrange(limit_graph.GetN() - 1): x1 = limit_x[i] x2 = limit_x[i + 1] y1 = limit_y[i] y2 = limit_y[i + 1] if (y1 < max_gq and y2 > max_gq) or (y1 > max_gq and y2 < max_gq): # Calculate intersection of interpolation with gq int_x = (max_gq - y1) * (x2 - x1) / (y2 - y1) + x1 int_y = max_gq new_limit_points[int_x] = int_y # Move any old points above gq to gq for i in xrange(limit_graph.GetN()): if limit_y[i] > max_gq: new_limit_points[limit_x[i]] = max_gq else: new_limit_points[limit_x[i]] = limit_y[i] # New graph: limit points new_graph = TGraph(len(new_limit_points) + 3) for i, x in enumerate(sorted(new_limit_points.keys())): new_graph.SetPoint(i, x, new_limit_points[x]) # New graph: upper boundary corresponding to gq xmin = min(new_limit_points.keys()) xmax = max(new_limit_points.keys()) new_graph.SetPoint(len(new_limit_points), xmax, max_gq) new_graph.SetPoint(len(new_limit_points) + 1, xmin, max_gq) new_graph.SetPoint( len(new_limit_points) + 2, xmin, new_limit_points[xmin]) return new_graph def draw( self, logx=False, logy=False, x_title="M_{Z'} [GeV]", y_title="g'_{q}", x_range=[40., 7000.], y_range=[0, 1.45], canvas_dim=[1800, 1200], legend_coords=[0.12, 0.28, 0.42, 0.9], draw_cms=None, legend_text_size=0.028, legend_ncolumns=None, legend_obsexp=False, # Add a solid and dotted line to legend for obs and exp draw_Z_constraint=False, gom_x=None, # x coordinate for Gamma/M labels model_label=False, # Add a string specifying the model on the plot gom_fills=False # Draw limit fills including upper boundaries ): canvas_name = "c_{}_{}_{}{}".format(self._name, ("logx" if logx else "linearx"), ("logy" if logy else "lineary"), ("_gomfills" if gom_fills else "")) self._canvas = TCanvas(canvas_name, canvas_name, canvas_dim[0], canvas_dim[1]) ROOT.gStyle.SetPadTickX(1) ROOT.gStyle.SetPadTickY(1) self._canvas.SetLeftMargin(0.09) self._canvas.SetBottomMargin(0.12) self._canvas.SetTopMargin(0.075) self._canvas.SetRightMargin(0.035) if logx: self._canvas.SetLogx() if logy: self._canvas.SetLogy() self._canvas.SetTicks(1, 1) self._canvas.cd() self._legend = TLegend(legend_coords[0], legend_coords[1], legend_coords[2], legend_coords[3]) self._legend.SetFillStyle(0) self._legend.SetBorderSize(0) self._legend.SetTextSize(legend_text_size) if legend_ncolumns: self._legend.SetNColumns(legend_ncolumns) # Legend headers and obs/exp lines self._legend.SetHeader("95% CL exclusions") if legend_obsexp: self._g_obs_dummy = TGraph(10) self._g_obs_dummy.SetLineStyle(1) self._g_obs_dummy.SetLineColor(1) self._g_obs_dummy.SetLineWidth(402) self._g_obs_dummy.SetMarkerStyle(20) self._g_obs_dummy.SetMarkerSize(0) self._g_obs_dummy.SetFillStyle(3004) self._g_obs_dummy.SetFillColor(1) self._legend.AddEntry(self._g_obs_dummy, "Observed", "lf") self._g_exp_dummy = TGraph(10) self._g_exp_dummy.SetLineStyle(2) self._g_exp_dummy.SetLineColor(1) self._g_exp_dummy.SetLineWidth(402) self._g_exp_dummy.SetMarkerStyle(20) self._g_exp_dummy.SetMarkerSize(0) self._legend.AddEntry(self._g_exp_dummy, "Expected", "l") self._frame = TH1D("frame", "frame", 100, x_range[0], x_range[1]) self._frame.SetDirectory(0) self._frame.GetYaxis().SetRangeUser(y_range[0], y_range[1]) self._frame.GetXaxis().SetTitle(x_title) self._frame.GetYaxis().SetTitle(y_title) self._frame.Draw("axis") if logx: self._frame.GetXaxis().SetMoreLogLabels() self._frame.GetXaxis().SetNdivisions(10) self._frame.GetXaxis().SetNoExponent(True) self._frame.GetXaxis().SetTitleOffset(1.) self._frame.GetXaxis().SetTitleSize(0.05) self._frame.GetXaxis().SetLabelSize(0.04) self._frame.GetYaxis().SetTitleOffset(0.8) self._frame.GetYaxis().SetTitleSize(0.05) self._frame.GetYaxis().SetLabelSize(0.04) #if logy: # self._frame.GetYaxis().SetMoreLogLabels() # Draw limit fills first, if any for name, limit_fill in self._limit_fills.iteritems(): self._limit_fills[name].SetFillStyle(3003) self._limit_fills[name].SetFillColor( self._style[name]["fill_color"]) self._limit_fills[name].Draw("F") for analysis_name in self._analyses: self.style_graph(self._graphs[analysis_name], analysis_name) self._graphs[analysis_name].Draw("lp") if self._legend_entries[analysis_name] != False: self._legend.AddEntry(self._graphs[analysis_name], self._legend_entries[analysis_name], "l") if draw_Z_constraint: self._tf_Z_constraint = TF1("Z_constraint", gq_Z_constraint, x_range[0], x_range[1], 0) self._tf_Z_constraint.SetNpx(1000) self._tf_Z_constraint.SetLineColor(15) ROOT.gStyle.SetLineStyleString(9, "40 20") self._tf_Z_constraint.SetLineStyle(9) self._tf_Z_constraint.SetLineWidth(2) self._tf_Z_constraint.Draw("same") self._legend.AddEntry(self._tf_Z_constraint, "Z width", "l") # Lines at fixed Gamma / M self._GoM_tf1s = {} self._GoM_labels = {} for i, GoM in enumerate(self._GoMs): self._GoM_tf1s[GoM] = TF1( "tf1_gq_{}".format(GoM), lambda x, this_gom=GoM: gom_to_gq(this_gom, x[0], self._vtype), x_range[0], x_range[1], 0) # self._GoM_tf1s[GoM].SetLineColor(ROOT.kGray + 1) self._GoM_tf1s[GoM].SetLineStyle(ROOT.kDashed) self._GoM_tf1s[GoM].SetLineWidth(1) self._GoM_tf1s[GoM].Draw("same") # TLatex for Gamma / M if gom_x: label_x = gom_x else: if logx: label_xfrac = 0.05 else: label_xfrac = 0.864 label_x = (x_range[1] - x_range[0]) * label_xfrac + x_range[0] if logy: label_y = self._GoM_tf1s[GoM].Eval(label_x) * 0.85 gom_text = "#Gamma/M_{{Z'}} = {}%".format(int(GoM * 100)) else: # label_y = self._GoM_tf1s[GoM].Eval(label_x) - 0.085 # For labels under the line label_y = self._GoM_tf1s[GoM].Eval( label_x) + 0.05 # For labels over the line gom_text = "#frac{{#Gamma}}{{M_{{Z'}}}} = {}%".format( int(GoM * 100)) self._GoM_labels[GoM] = TLatex(label_x, label_y, gom_text) if logy: self._GoM_labels[GoM].SetTextSize(0.028) else: self._GoM_labels[GoM].SetTextSize(0.033) self._GoM_labels[GoM].SetTextColor(ROOT.kGray + 1) self._GoM_labels[GoM].Draw("same") # Vector label if model_label: self._model_label = TLatex(model_label["x"], model_label["y"], model_label["text"]) self._model_label.SetTextSize(0.04) self._model_label.SetTextColor(1) self._model_label.Draw("same") # Legend last, to be on top of lines self._legend.Draw() if draw_cms: CMSLabel(self._canvas, extra_text=draw_cms, halign="left", valign="top", in_frame=False) def save(self, folder, exts=["pdf"]): for ext in exts: self._canvas.SaveAs("{}/{}.{}".format(folder, self._canvas.GetName(), ext))
def main(reader_name, tags, lut_path, ptmin, ptmax, ymin=None, ymax=None, tag_name=None, logx=False, logy=False, leg_pos=[0.74, 0.2, 0.90, 0.4], particles=None, eta=0, dnch_deta=100, rmin=None, add_eta_label=True, add_alice3_label=True, save=None, background=False, use_p_over_z=True, aod=None, study_label="ALICE 3 study"): gROOT.LoadMacro(reader_name) gROOT.LoadMacro("style.C") reader_name = reader_name.split(".")[-2] reader = getattr(__import__('ROOT', fromlist=[reader_name]), reader_name) style = getattr(__import__('ROOT', fromlist=["style"]), "style") style() p = { "el": "e", "pi": "#pi", "ka": "K", "pr": "p", "de": "d", "tr": "t", "he3": "^{3}He" } charge = {"el": 1, "pi": 1, "ka": 1, "pr": 1, "de": 1, "tr": 1, "he3": 2} p_colors = { "el": "#e41a1c", "pi": "#377eb8", "ka": "#4daf4a", "pr": "#984ea3", "de": "#ff7f00", "tr": "#999999", "he3": "#a65628" } if particles is not None: to_remove = [] for i in p: if i not in particles: to_remove.append(i) for i in to_remove: p.pop(i) latex = TLatex() latex.SetTextAlign(33) canvas = reader_name canvas = canvas.replace("lutRead_", "") canvas = TCanvas(canvas, canvas, 800, 800) canvas.Divide(2, 2) drawn = [canvas] drawn_graphs = {} drawn_frames = {} if ymin is None: if "_dca" in reader_name: ymin = 0.1 elif "_pt" in reader_name: ymin = 1. elif "_eff" in reader_name: ymin = 0. if ymax is None: if "_dca" in reader_name: ymax = 1e4 elif "_pt" in reader_name: ymax = 100. elif "_eff" in reader_name: ymax = 115. def adjust_pad(): if logx: gPad.SetLogx() if logy: gPad.SetLogy() counter = 1 leg = None if tag_name is not None: leg = TLegend(*leg_pos) if add_eta_label: label = f"#eta = {int(eta)}" label += " dN_{Ch}/d#eta =" label += f" {int(dnch_deta)}" if rmin is not None: label += " R_{min} = " + rmin else: leg.SetHeader() leg.SetHeader(label) leg.SetLineColor(0) drawn.append(leg) def draw_study_label(x=0.5, y=0.9): latex = TLatex() latex.SetTextAlign(13) drawn.append(latex.DrawLatexNDC(x, y, " ".join(study_label))) for i in p: c = f"{canvas.GetName()}_{i}" c = TCanvas(c, c, 800, 800) drawn.append(c) adjust_pad() frame = c.DrawFrame(ptmin, ymin, ptmax, ymax, "") frame.SetDirectory(0) drawn_frames[i] = frame g_list = [] extra = {} cols = [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33' ] for k, j in enumerate(tags): lut = f"{lut_path}/lutCovm.{i}.{j}.dat" if j == "": lut = f"{lut_path}/lutCovm.{i}.dat" if not path.isfile(lut): print("LUT file", lut, "does not exist") return g = reader(lut, eta, dnch_deta) if g.GetN() <= 0: print("Skipping", g.GetName(), "because empty graph") continue if len(g_list) == 0: frame.GetXaxis().SetTitle(g.GetXaxis().GetTitle()) frame.GetYaxis().SetTitle(g.GetYaxis().GetTitle()) if use_p_over_z: for j in range(g.GetN()): if "_pt" in reader_name: g.SetPoint(j, g.GetPointX(j) / charge[i], g.GetPointY(j) / charge[i]) else: g.SetPoint(j, g.GetPointX(j) / charge[i], g.GetPointY(j)) frame.GetXaxis().SetTitle("#it{p}_{T}/z (GeV/#it{c})") col = TColor.GetColor(cols[len(g_list)]) g.SetLineColor(col) g.SetLineStyle(1) g.SetLineWidth(3) g.Draw("samel") if aod is not None: f_aod = TFile(aod, "READ") if "_eff" in reader_name: extra[g.GetName()] = f_aod.Get( "qa-tracking-efficiency-kaon/pt/num") extra[g.GetName()].Divide( f_aod.Get("qa-tracking-efficiency-kaon/pt/num"), f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1, "B") extra[g.GetName()].Scale(100) extra[g.GetName()].Draw("SAME") extra[g.GetName()].SetDirectory(0) elif "_pt" in reader_name: extra[g.GetName()] = f_aod.Get( "qa-tracking-efficiency-kaon/pt/num") extra[g.GetName()].Divide( f_aod.Get("qa-tracking-efficiency-kaon/pt/num"), f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1, "B") extra[g.GetName()].Scale(100) extra[g.GetName()].Draw("SAME") extra[g.GetName()].SetDirectory(0) f_aod.Close() print("Drawing", g.GetName()) if tag_name is not None and counter == 1: leg.AddEntry(g, tag_name[k], "l") g_list.append(g) drawn_graphs[i] = g_list if len(g_list) <= 0: print("Nothing drawn!") continue drawn.append(latex.DrawLatexNDC(0.9, 0.9, p[i])) if leg is not None: leg.Draw() draw_study_label(.4, .91) gPad.Update() canvas.cd(counter) clone = c.DrawClonePad() if counter != 1: l = gPad.GetListOfPrimitives() for i in l: cn = i.ClassName() if cn == "TLegend": l.Remove(i) elif cn == "TLatex": if "ALICE" in i.GetTitle(): l.Remove(i) drawn.append(clone) c.SaveAs(f"/tmp/{c.GetName()}.png") gPad.Update() counter += 1 canvas_all_species = None if len(tags) == 1: canvas_all_species = TCanvas("all_spec_" + canvas.GetName(), "all_spec_" + canvas.GetName(), 800, 800) drawn.append(canvas_all_species) canvas_all_species.cd() drawn_graphs_all_spec = {} leg_all_spec = TLegend(*leg_pos) leg_all_spec.SetNColumns(2) leg_all_spec.SetLineColor(0) drawn.append(leg_all_spec) for i in drawn_graphs: if canvas_all_species.GetListOfPrimitives().GetEntries() == 0: drawn_frames[i].Draw() g_list = [] for j in drawn_graphs[i]: g_list.append(j.Clone()) g_list[-1].SetName(g_list[-1].GetName() + "_color") g_list[-1].SetLineColor(TColor.GetColor(p_colors[i])) g_list[-1].Draw("same") leg_all_spec.AddEntry(g_list[-1], p[i], "L") drawn_graphs_all_spec[i] = g_list for i in drawn_graphs_all_spec: drawn_graphs[i + "_allspec"] = drawn_graphs_all_spec[i] leg_all_spec.Draw() if add_alice3_label: draw_study_label() latex = TLatex() latex.SetTextAlign(13) latex.SetTextSize(0.04) if tag_name is not None: drawn.append(latex.DrawLatexNDC(0.5, 0.80, tag_name[0])) drawn.append( latex.DrawLatexNDC( 0.4, 0.82, f"#eta = {int(eta)}" + "\n dN_{Ch}/d#eta =" + f" {int(dnch_deta)}" + ("\n R_{min} = " + rmin if rmin is not None else ""))) adjust_pad() canvas_all_species.Update() canvas_all_species.SaveAs(f"/tmp/{canvas_all_species.GetName()}.png") if save is None: canvas.SaveAs(f"/tmp/lut_{canvas.GetName()}.root") else: fo = TFile(save, "RECREATE") fo.cd() canvas.Write() if canvas_all_species is not None: canvas_all_species.Write() for i in drawn_graphs: for j in drawn_graphs[i]: j.Write() if not background: input("Done, press enter to continue")
def main(options, args): from ROOT import gSystem, gROOT, gStyle gROOT.SetBatch() gSystem.Load("libRooFitCore") if options.doWebPage: from lip.Tools.rootutils import loadToolsLib, apply_modifs loadToolsLib() from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList from ROOT import kWhite, kBlue, kOpenSquare if options.doWebPage: from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot rootglobestyle.setTDRStyle() gStyle.SetMarkerSize(1.5) gStyle.SetTitleYOffset(1.5) gStyle.SetPadLeftMargin(0.16) gStyle.SetPadRightMargin(0.05) gStyle.SetPadTopMargin(0.05) gStyle.SetPadBottomMargin(0.13) gStyle.SetLabelFont(42, "XYZ") gStyle.SetLabelOffset(0.007, "XYZ") gStyle.SetLabelSize(0.05, "XYZ") gStyle.SetTitleSize(0.06, "XYZ") gStyle.SetTitleXOffset(0.9) gStyle.SetTitleYOffset(1.24) gStyle.SetTitleFont(42, "XYZ") ## ## Read files ## options.outdir = "%s_m%1.0f" % (options.outdir, options.mH) if options.fp: options.outdir += "_fp" ncat = options.ncat cats = options.cats if cats is "": categories = ["_cat%d" % i for i in range(0, ncat)] else: categories = ["_cat%s" % i for i in cats.split(",")] if options.mva: clables = { "_cat0": ("MVA > 0.89", ""), "_cat1": ("0.74 #leq MVA", "MVA < 0.89"), "_cat2": ("0.545 #leq MVA", "MVA < 0.74"), "_cat3": ("0.05 #leq MVA", "MVA < 0.545"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } else: clables = { "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"), "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"), "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"), "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } helper = Helper() fin = TFile.Open(options.infile) helper.files.append(fin) ws = fin.Get("cms_hgg_workspace") mass = ws.var("CMS_hgg_mass") mass.SetTitle("m_{#gamma#gamma}") mass.setUnit("GeV") mass.setRange(100., 150.) mass.setBins(100, "plot") mass.setBins(5000) print ws aset = RooArgSet(mass) helper.objs.append(mass) helper.objs.append(aset) fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8)) if not options.binned and not options.refit: finpdf = TFile.Open(options.infilepdf) helper.files.append(finpdf) wspdf = finpdf.Get("wsig") else: wspdf = ws for c in categories: processes = ["ggh", "vbf", "wzh"] if options.fp: processes = ["vbf", "wzh"] ### elif clables[c][0] == "Di-jet": ### processes = [ "vbf", "ggh" ] dsname = "sig_mass_m%1.0f%s" % (options.mH, c) print dsname print ws ds = ws.data("sig_%s_mass_m%1.0f%s" % (processes[0], options.mH, c)).Clone(dsname) for proc in processes[1:]: ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c))) helper.dsets.append(ds) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, ds) pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass, ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: if options.refit: if options.refitall and clables[c][0] != "Di-jet": rpdfs = [] for proc in processes: for ngaus in range(1, 4): pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus, ngaus == 3) pp.fitTo( ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)), RooFit.Strategy(0), *fitopt) rpdfs.append(pp) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs))) else: if options.refitall and clables[c][0] == "Di-jet": for ngaus in range(1, 5): pdf = build_pdf(ws, c, ngaus, ngaus == 5) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: for ngaus in range(1, 4): pdf = build_pdf(ws, c, ngaus, ngaus == 3) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p)) for p in processes) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs)) helper.add(pdf, pdf.GetName()) plot_pdf = pdf.Clone("pdf_%s" % dsname) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(ds) cdf = pdf.createCdf(aset) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) ### hmin, hmax, hm = get_FWHM( points ) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma%s" % c) helper.add((hmin, hmax, hm), "FWHM%s" % c) helper.add(ds.sumEntries(), "sumEntries%s" % c) # signal model integral # data integral for PAS tables data = ws.data("data_mass%s" % c) helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" % (options.mH - 10., options.mH + 10.)), "data_sumEntries%s" % c) del cdf del pdf dsname = "sig_mass_m%1.0f_combcat" % options.mH print dsname combined_ds = helper.dsets[0].Clone(dsname) for d in helper.dsets[1:]: combined_ds.append(d) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, combined_ds) pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass, combined_ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: #### pdf = build_pdf(ws,"_combcat") #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt ) #### plot_pdf = pdf.Clone( "pdf_%s" % dsname ) pdf = RooAddPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, RooArgList(*(helper.histos["hggpdfrel%s" % c] for c in categories))) plot_pdf = pdf cdf = pdf.createCdf(aset) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(combined_ds) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma_combcat") helper.add((hmin, hmax, hm), "FWHM_combcat") helper.add(plot_ds.sumEntries(), "sumEntries_combcat") mass.setRange("higgsrange", options.mH - 25., options.mH + 15.) del cdf del pdf del helper.dsets ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}") label = TLatex(0.7, 0.86, "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}") label.SetNDC(1) ## ## Make web page with plots ## if options.doWebPage: hth = HtmlHelper(options.outdir) hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set( "href", "../?C=M;O=D") hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set( "href", "./") tab = hth.body().add(HtmlTable()) ip = 0 for c in ["_combcat"] + categories: ### for c in categories: if options.doWebPage and ip % 4 == 0: row = tab.row() ip = ip + 1 dsname = "sig_mass_m%1.0f%s" % (options.mH, c) canv = TCanvas(dsname, dsname, 600, 600) helper.objs.append(canv) ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322) leg = TLegend(0.2, 0.96, 0.5, 0.55) #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] ) hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange")) helper.objs.append(hplotcompint) helper.objs.append(leg) plot_ds = helper.histos["plot_%s" % dsname] plot_pdf = helper.histos["pdf_%s" % dsname] wmin, wmax = helper.histos["eff_sigma%s" % c] hmin, hmax, hm = helper.histos["FWHM%s" % c] print hmin, hmax, hm style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0)) style_seff = ( RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), ) style_ds = (RooFit.MarkerStyle(kOpenSquare), ) plot_ds.plotOn(hplotcompint, RooFit.Invisible()) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.FillColor(19), RooFit.DrawOption("F"), *style_seff) seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.LineColor(15), *style_seff) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range("higgsrange"), *style) pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_ds.plotOn(hplotcompint, *style_ds) pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) iob = int(hplotcompint.numItems() - 1) leg.AddEntry(pointsleg, "Simulation", "pe") leg.AddEntry(pdfleg, "Parametric model", "l") leg.AddEntry(seffleg, "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl") clabel = TLatex(0.74, 0.65, "#scale[0.65]{#splitline{%s}{%s}}" % clables[c]) clabel.SetNDC(1) helper.objs.append(clabel) hm = hplotcompint.GetMaximum() * 0.5 * 0.9 ### hm = pdfleg.GetMaximum()*0.5 fwhmarrow = TArrow(hmin, hm, hmax, hm) fwhmarrow.SetArrowSize(0.03) helper.objs.append(fwhmarrow) fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC") fwhmlabel.SetFillStyle(0) fwhmlabel.SetLineColor(kWhite) reducedFWHM = (hmax - hmin) / 2.3548200 fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM) helper.objs.append(fwhmlabel) hplotcompint.SetTitle("") hplotcompint.GetXaxis().SetNoExponent(True) hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)") hplotcompint.GetXaxis().SetNdivisions(509) ## hplotcompint.GetYaxis().SetTitle("A.U."); ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4); hplotcompint.Draw() leg.Draw("same") label.Draw("same") clabel.Draw("same") fwhmarrow.Draw("<>") fwhmlabel.Draw("same") plot_ds.sumEntries() if options.doWebPage: hpl = HtmlPlot(canv, False, "", True, True, True) hpl.caption("<i>%s</i>" % canv.GetTitle()) row.cell(hpl) else: if os.path.isdir(options.outdir) is False: os.mkdir(options.outdir) for ext in "C", "png", "pdf": canv.SaveAs( os.path.join(options.outdir, "%s.%s" % (canv.GetName(), ext))) if "comb" in c: ip = 0 if options.doWebPage: print "Creating pages..." hth.dump() for f in helper.files: f.Close() gROOT.Reset() from pprint import pprint pprint(helper) print 'Summary statistics per event class' print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH sigTotal = 0. dataTotal = 0. for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] sigTotal += sigVal dataTotal += datVal for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] - helper.histos["eff_sigma%s" % c][0]) fwhm = (helper.histos["FWHM%s" % c][1] - helper.histos["FWHM%s" % c][0]) / 2.3548200 print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % ( sigVal, 100. * sigVal / sigTotal, datVal / (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm) print "Done."
def plotHistos(self, norm=False, sameCanvas=False): ''' Superimpose histograms for all samples, on the same canvas or on separate canvases ''' if sameCanvas: c = TCanvas(self.name, self.name, 6400, 4800) tosave = {c.GetName(): c} else: c = None tosave = {} legends = [] hMax = {} for j, what in enumerate(self.samples[0].histos.keys()): hMax[what] = [] leg = defaultLegend(x1=0.15, y1=0.7, x2=0.95, y2=0.95, mult=1.2) legends.append(leg) # do the actual plotting for i, sample in enumerate(self.samples): if i == 0: opt = 'histE' if sameCanvas: c.DivideSquare(len(sample.histos.keys())) else: opt = 'histEsame' for j, what in enumerate(sample.histos.keys()): h = sample.histos[what] graph_saver.append(h) if sameCanvas: pad = c.cd(j + 1) else: cname = '%s_%s' % (self.name, what) if cname not in tosave.keys(): tosave[cname] = TCanvas(cname, cname, 700, 600) pad = tosave[cname].cd() if i == 0: pad.SetLogx(sample.histoDefs[what].logX) pad.SetLogy(sample.histoDefs[what].logY) if norm and h.Integral(): hdrawn = h.DrawNormalized(opt) hMax[what].append(hdrawn) hdrawn.SetLineColor(self.colors[i]) hdrawn.SetMarkerColor(self.colors[i]) hdrawn.SetMarkerStyle(self.styles[i]) hdrawn.SetMarkerSize(3) hdrawn.SetLineWidth(2) legends[j].AddEntry(hdrawn, sample.legname, 'LP') else: h.Draw(opt) hMax[what].append(h) h.SetLineColor(self.colors[i]) h.SetMarkerColor(self.colors[i]) h.SetMarkerStyle(self.styles[i]) h.SetMarkerSize(4) h.SetLineWidth(2) legends[j].AddEntry(hdrawn, sample.legname, 'LP') if i == len(self.samples) - 1: legends[j].Draw('same') # compute the max of norm histo and set the range accordingly for j, what in enumerate(self.samples[0].histos.keys()): if len(hMax[what]) > 0: max = 0 for ih in hMax[what]: if (max < ih.GetMaximum()): max = ih.GetMaximum() if (sample.histoDefs[what].logY == True): #hMax[name][0].GetYaxis().SetRangeUser(0.01, max * 7) hMax[what][0].SetMaximum(max * 30) #print hMax[what][0].GetMaximum() else: #hMax[name][0].GetYaxis().SetRangeUser(0.01, max * 1.5) hMax[what][0].SetMaximum(max * 1.7) norm_suffix = '_norm' if norm else '' for cname, canv in tosave.items(): canv.SaveAs('./plots/' + self.label + suffix + '/' + cname + norm_suffix + '.png') canv.SaveAs('./plots/' + self.label + suffix + '/' + cname + norm_suffix + '.pdf') canv.SaveAs('./plots/' + self.label + suffix + '/' + cname + norm_suffix + '.C')
gr1.SetLineColor(30) gr1.SetLineWidth(1) gr1.SetMarkerStyle(21) gr1.SetMarkerColor(3) gr2.SetLineColor(38) gr2.SetLineWidth(1) gr2.SetMarkerStyle(29) gr2.SetMarkerColor(4) gr3.SetLineColor(12) gr3.SetLineWidth(1) gr3.SetMarkerStyle(31) gr3.SetMarkerColor(1) gr0.Draw('APL') gr1.Draw('PL') gr2.Draw('PL') gr3.Draw('PL') legend = ROOT.TLegend(0.1, 0.3, 0.48, 0.5) legend.AddEntry(gr0, 'DNN', "lp") legend.AddEntry(gr1, 'BDT', "lp") legend.AddEntry(gr2, 'MLP', "lp") legend.AddEntry(gr3, 'kNN', "lp") legend.Draw() c1.Update() c1.SaveAs("dataset_e90/%s.pdf" % (c1.GetName() + "_1M_100k"))
def plotOtherCoordinate(datafile, crossings, scans): gStyle.SetOptStat(0) f = TFile.Open(datafile) for bx in crossings: for coord in ('X', 'Y'): if 'X' in coord: other = 'Y' else: other = 'X' meanGraphs = [] rmsGraphs = [] for scan in scans: meanVal = array('d') meanErr = array('d') rmsVal = array('d') rmsErr = array('d') stepVal = array('d', [1.0 * a for a in range(1, 20)]) stepErr = array('d', 19 * [0.0]) for i in range(1, 20): hist = f.Get('scan' + coord + scan + 'Move_b' + bx + '_' + str(i)) funcGaus = TF1('funcGaus' + coord + scan, 'gaus', -10, 10) getattr(hist, 'Projection' + other)().Fit('funcGaus' + coord + scan) meanVal.append(funcGaus.GetParameter('Mean') * scaling) meanErr.append(funcGaus.GetParError(1) * scaling) rmsVal.append(funcGaus.GetParameter('Sigma') * scaling) rmsErr.append(funcGaus.GetParError(2) * scaling) meanGraph = TGraphErrors(19, stepVal, meanVal, stepErr, meanErr) rmsGraph = TGraphErrors(19, stepVal, rmsVal, stepErr, rmsErr) meanGraph.SetName('graph' + coord + scan + 'MeanBX' + bx) rmsGraph.SetName('graph' + coord + scan + 'RmsBX' + bx) meanGraphs.append(meanGraph) rmsGraphs.append(rmsGraph) meanMulti = TMultiGraph('multi' + coord + scan + 'MeanBX' + bx, '') rmsMulti = TMultiGraph('multi' + coord + scan + 'RmsBX' + bx, '') for i, gr in enumerate(meanGraphs): gr.SetMarkerStyle(3 + 19 * i) gr.SetMarkerSize(1) gr.SetMarkerColor(2 + i) meanMulti.Add(gr) for i, gr in enumerate(rmsGraphs): gr.SetMarkerStyle(3 + 19 * i) gr.SetMarkerSize(1) gr.SetMarkerColor(2 + i) rmsMulti.Add(gr) meanCanvas = TCanvas('canvasMean' + coord + 'ScanBX' + bx, '', 1000, 600) meanMulti.Draw('APE') meanCanvas.Update() meanMulti.GetYaxis().SetTitle('luminous region ' + other.lower() + '-mean [cm]') meanMulti.GetXaxis().SetTitle('scan point') meanMulti.GetYaxis().SetTitleOffset(1.3) meanMulti.GetYaxis().SetRangeUser(-0.01, 0.01) meanMulti.GetYaxis().SetTickLength(0.02) meanLeg = TLegend(0.4, 0.13, 0.6, 0.28) meanLeg.SetHeader(coord + ' Scan (BCID ' + bx + ')') meanLeg.SetBorderSize(0) meanLeg.SetNColumns(2) for i, gr in enumerate(meanGraphs): entry = meanLeg.AddEntry(gr.GetName(), 'Scan ' + scans[i], 'lep') entry.SetMarkerStyle(3 + 19 * i) entry.SetMarkerColor(2 + i) meanLeg.Draw() drawCMS() meanCanvas.Modified() meanCanvas.Update() meanCanvas.SaveAs('summaryPlots/' + meanCanvas.GetName() + '.pdf') meanCanvas.SaveAs('summaryPlots/' + meanCanvas.GetName() + '.C') rmsCanvas = TCanvas('canvasRms' + coord + 'ScanBX' + bx, '', 1000, 600) rmsMulti.Draw('APE') rmsCanvas.Update() rmsMulti.GetYaxis().SetTitle('luminous region ' + other.lower() + '-width [cm]') rmsMulti.GetXaxis().SetTitle('scan point') rmsMulti.GetYaxis().SetTitleOffset(1.3) rmsMulti.GetYaxis().SetRangeUser(-0.01, 0.04) rmsMulti.GetYaxis().SetTickLength(0.02) rmsLeg = TLegend(0.4, 0.13, 0.6, 0.28) rmsLeg.SetHeader(coord + ' Scan (BCID ' + bx + ')') rmsLeg.SetBorderSize(0) rmsLeg.SetNColumns(2) for i, gr in enumerate(rmsGraphs): entry = rmsLeg.AddEntry(gr.GetName(), 'Scan ' + scans[i], 'lep') entry.SetMarkerStyle(3 + 19 * i) entry.SetMarkerColor(2 + i) rmsLeg.Draw() drawCMS() rmsCanvas.Modified() rmsCanvas.Update() rmsCanvas.SaveAs('summaryPlots/' + rmsCanvas.GetName() + '.pdf') rmsCanvas.SaveAs('summaryPlots/' + rmsCanvas.GetName() + '.C')
def readRateFile(version, algoName, ptCutGev): folder = 'crab_omtf_nn_MC_analysis_SingleNeutrino_PU200_v2_' + version if version == "t74" or version == "t78" or version == "t80" or version == "t100" or version == "t104": folder = 'crab_omtf_nn_MC_analysis_SingleNeutrino_PU200_v3_' + version if folder in histFiles: histFile = histFiles.get(folder) else: histFile = TFile(fileDir + folder + '/results/omtfAnalysis2.root') histFiles[folder] = histFile print("\nreading file " + histFile.GetName()) rateDir = histFile.Get("L1MuonAnalyzerOmtf/rate") #rateDir.ls() algoDir = None #algoDir.ls() for obj in rateDir.GetListOfKeys(): if algoName == obj.GetName(): algoDir = obj.ReadObj() if algoDir is None: print("coiuld not find algo " + algoName) return print(" algoDir %s ptCutGev %f " % (algoDir.GetName(), ptCutGev)) name = version + "_" + algoDir.GetName() title = version + " " + algoDir.GetName().replace("_", " ") c1 = TCanvas('canvas_' + name, title, 200, 10, 700 * 2, 700) canvases.append(c1) c1.Divide(2, 1) c1.cd(1).SetGridx() c1.cd(1).SetGridy() c1.SetLogy() print('created canvas ' + c1.GetName()) legend = TLegend(0.5, 0.6, 0.8, 0.8) legend.SetBorderSize(0) legend.SetTextSize(0.027) legend.SetHeader(title) legends.append(legend) rateResult = getRate(algoDir, ptCutGev, name + "_total") rateOnThresh = rateResult[0] candPt_rateCumul = rateResult[1] rateCumuls.append(candPt_rateCumul) candPt_rateCumul.SetLineColor(kBlack) candPt_rateCumul.GetYaxis().SetTitle("#events") candPt_rateCumul.Draw("hist") candPt_rateCumul.GetYaxis().SetRangeUser(10, 20000) print("added candPt_rateCumul " + candPt_rateCumul.GetName()) legend.AddEntry(candPt_rateCumul, "total rate") print("total rateOnThresh %f" % (rateOnThresh)) rateCumulStack = THStack("rateCumulStack_" + name, title) rateCumulStacks.append(rateCumulStack) totalRate = 0 color = 2 thisAcceptedMuonsPts = [] for candCategory in candCategories: #categoryDir = histFile.Get("L1MuonAnalyzerOmtf/rate/" + algoName + "/" + candCategory) categoryDir = algoDir.Get(candCategory) print("categoryDir " + categoryDir.GetName()) rateResult = getRate(categoryDir, ptCutGev, name + "_" + candCategory) rateOnThresh = rateResult[0] rateVsCategory[candCategory].Fill(title + " " + str(ptCutGev) + " GeV", rateOnThresh) rateVsCategory[candCategory].SetFillColor(color) totalRate = totalRate + rateOnThresh print("%s rate %f " % (categoryDir.GetName(), rateOnThresh)) candPt_rateCumul = rateResult[1] #candPt_rateCumul.SetFillColor(color) candPt_rateCumul.SetLineColor(color) #rateCumulStack.Add(candPt_rateCumul) rateCumuls.append(candPt_rateCumul) print("added candPt_rateCumul " + candPt_rateCumul.GetName()) candPt_rateCumul.Draw("hist same") legend.AddEntry(candPt_rateCumul, candCategory) if rateResult.__len__() > 2: acceptedMuonsPt = rateResult[2] acceptedMuonsPt.SetLineColor(color) acceptedMuonsPts.append(acceptedMuonsPt) thisAcceptedMuonsPts.append(acceptedMuonsPt) color += 1 if color == 5: color = 6 legend.Draw() #rateCumulStack.Draw() c1.cd(2).SetGridx() c1.cd(2).SetGridy() first = True for acceptedMuonsPt in thisAcceptedMuonsPts: print "Drawing", acceptedMuonsPt.GetTitle() if first: acceptedMuonsPt.GetYaxis().SetRangeUser(0, 15) acceptedMuonsPt.Draw("hist") else: acceptedMuonsPt.Draw("hist same") first = False c1.Modified() c1.Update() print("totalRate %f" % (totalRate))
class GQSummaryPlot: def __init__(self, name): self._name = name self._analyses = [] self._dijet_data = {} self._legend_entries = {} self._graphs = {} self._limit_fills = {} self._GoMs = [] self._vtype = "vector" self._style = { "default": { "line_color": 1, "line_width": 402, "line_style": 1, "marker_style": 20, "marker_size": 0, "marker_color": 1, "fill_style": 3004, "fill_color": 0, "alpha": 1. } } self._tranparency = {} # style = dict of <analysis name>:{"line_color":1, "marker_style":20, etc} # See the default option in __init__ for the full list of options def set_style(self, style): self._style.update(style) def set_vtype(self, vtype): vtype = vtype.lower() if not vtype in ["vector", "axial"]: raise ValueError( "[set_vtype] Argument vtype must be 'vector' or 'axial'") self._vtype = vtype def add_data(self, dijet_data, name, legend, truncate_gq=False, truncate_gom=False, min_gom=False): self._analyses.append(name) self._dijet_data[name] = dijet_data self._legend_entries[name] = legend if truncate_gq and truncate_gom: raise ValueError( "[GQSummaryPlot::add_data] ERROR : Cannot specify both truncate_gq and truncate_gom." ) if truncate_gq: max_truncated_graphs = self.truncate_graph_gq( dijet_data.get_graph(), truncate_gq[1]) truncated_graphs = [] if truncate_gq[0] > 0: for tmpgraph in max_truncated_graphs: truncated_graphs.extend( self.truncate_graph_gq(tmpgraph, truncate_gq[0], invert=-1)) else: truncated_graphs = max_truncated_graphs # If the truncation deleted all points, abandon if len(truncated_graphs) == 0: print "[GQSummaryPlot::add_data] ERROR : Applying truncate_gq resulted in an empty graph! Remove from the input list." print "[GQSummaryPlot::add_data] ERROR : truncate_gq = {}".format( truncate_gq) dijet_data.get_graph().Print("all") sys.exit(1) # Save the new set of graphs for i, graph in enumerate(truncated_graphs): piece_name = name if i != 0: piece_name += str(i) self._analyses.append(piece_name) self._style[piece_name] = self._style[name] self._legend_entries[piece_name] = False self._graphs[piece_name] = truncated_graphs[i] elif truncate_gom: print "DEBUG : Truncating graph {} to range {}".format( name, truncate_gom) max_truncated_graphs = self.truncate_graph_gom( dijet_data.get_graph(), truncate_gom[1]) truncated_graphs = [] if truncate_gom[0] > 0: for tmpgraph in max_truncated_graphs: truncated_graphs.extend( self.truncate_graph_gom(tmpgraph, truncate_gom[0], invert=-1)) else: truncated_graphs = max_truncated_graphs # If the truncation deleted all points, abandon if len(truncated_graphs) == 0: print "[GQSummaryPlot::add_data] ERROR : Applying truncate_gom resulted in an empty graph! Remove from the input list." print "[GQSummaryPlot::add_data] ERROR : truncate_gom = {}".format( truncate_gom) dijet_data.get_graph().Print("all") sys.exit(1) # Save the new set of graphs for i, graph in enumerate(truncated_graphs): piece_name = name if i != 0: piece_name += str(i) self._analyses.append(piece_name) self._style[piece_name] = self._style[name] self._legend_entries[piece_name] = False self._graphs[piece_name] = truncated_graphs[i] else: self._graphs[name] = dijet_data.get_graph() #if max_gom_fill: # self._limit_fills[name] = self.create_limit_gom_fill(dijet_data.get_graph(), max_gom_fill) #if max_gq_fill: # self._limit_fills[name] = self.create_limit_gq_fill(dijet_data.get_graph(), max_gq_fill) # Add legend entry with no object def add_legend_only(self, name, legend_entry): self._legend_entries[name] = legend_entry self._analyses.append(name) self._graphs[name] = 0 def set_width_curves(self, GoMs): self._GoMs = GoMs def style_graph(self, graph, name): if not name in self._style: print "[style_graph] ERROR : Analysis {} is not present in the style dict. Please add.".format( name) sys.exit(1) if "line_color" in self._style[name]: if "alpha" in self._style[name]: graph.SetLineColorAlpha(self._style[name]["line_color"], self._style[name]["alpha"]) else: graph.SetLineColor(self._style[name]["line_color"]) else: if "alpha" in self._style[name]: graph.SetLineColorAlpha(self._style["default"]["line_color"], self._style["default"]["alpha"]) else: graph.SetLineColor(self._style["default"]["line_color"]) if "line_style" in self._style[name]: graph.SetLineStyle(self._style[name]["line_style"]) else: graph.SetLineStyle(self._style["default"]["line_style"]) if "line_width" in self._style[name]: graph.SetLineWidth(self._style[name]["line_width"]) else: graph.SetLineWidth(self._style["default"]["line_width"]) if "marker_color" in self._style[name]: if "alpha" in self._style[name]: graph.SetMarkerColorAlpha(self._style[name]["marker_color"], self._style[name]["alpha"]) else: graph.SetMarkerColor(self._style[name]["marker_color"]) else: if "alpha" in self._style[name]: graph.SetMarkerColorAlpha( self._style["default"]["marker_color"], self._style["default"]["alpha"]) else: graph.SetMarkerColor(self._style["default"]["marker_color"]) if "marker_style" in self._style[name]: graph.SetMarkerStyle(self._style[name]["marker_style"]) else: graph.SetMarkerStyle(self._style["default"]["marker_style"]) if "marker_size" in self._style[name]: graph.SetMarkerSize(self._style[name]["marker_size"]) else: graph.SetMarkerSize(self._style["default"]["marker_size"]) if "fill_style" in self._style[name]: graph.SetFillStyle(self._style[name]["fill_style"]) else: graph.SetFillStyle(self._style["default"]["fill_style"]) if "fill_color" in self._style[name]: if "alpha" in self._style[name]: graph.SetFillColorAlpha(self._style[name]["fill_color"], self._style[name]["alpha"]) else: graph.SetFillColor(self._style[name]["fill_color"]) else: if "alpha" in self._style[name]: graph.SetFillColorAlpha(self._style["default"]["fill_color"], self._style["default"]["alpha"]) else: graph.SetFillColor(self._style["default"]["fill_color"]) # Returns a set of graphs with a maximum g_q (or minimum; specify invert=-1) def truncate_graph_gq(self, limit_graph, max_gq, invert=1): # Calculate the sets of x values for the new graphs limit_x = limit_graph.GetX() limit_y = limit_graph.GetY() x_points = [[]] y_points = [[]] if invert * limit_y[0] < invert * max_gq: x_points[-1].append(limit_x[0]) y_points[-1].append(limit_y[0]) for i in xrange(1, len(limit_x)): if invert * limit_y[i - 1] < invert * max_gq and invert * limit_y[ i] < invert * max_gq: x_points[-1].append(limit_x[i]) y_points[-1].append(limit_y[i]) elif invert * limit_y[i - 1] > invert * max_gq and invert * limit_y[ i] < invert * max_gq: # limit crosses max_gq going down: new set print "Solving for bad-to-good crossing (max_gq={}).".format( max_gq) print "(m1, gq1) = ({}, {})".format(limit_x[i - 1], limit_y[i - 1]) print "(m2, gq2) = ({}, {})".format(limit_x[i], limit_y[i]) if len(x_points[-1]) >= 1: x_points.append([]) y_points.append([]) # Calculate crossing point x_cross_array = fsolve(lambda x: limit_graph.Eval(x) - max_gq, (limit_x[i - 1] + limit_x[i]) / 2.) if len(x_cross_array) != 1: raise ValueError("ERROR : Found more than one crossing!") x_cross = x_cross_array[0] print "Found crossing (m, gq) = ({}, {})".format( x_cross, limit_graph.Eval(x_cross)) ''' # Old method: analytical solution by hand # max_gq = limit_y[i-1] + (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) * dx slope = (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) dx = (max_gq - limit_y[i-1]) / slope x_cross = limit_x[i-1] + dx x_points[-1].append(x_cross) x_points[-1].append(limit_x[i]) y_points[-1].append(limit_graph.Eval(x_cross)) y_points[-1].append(limit_graph.Eval(limit_x[i])) ''' x_points[-1].append(x_cross) x_points[-1].append(limit_x[i]) y_points[-1].append(limit_graph.Eval(x_cross)) y_points[-1].append(limit_graph.Eval(limit_x[i])) elif invert * limit_y[i - 1] < invert * max_gq and invert * limit_y[ i] > invert * max_gq: # limit crosses max_gq going up: end this set with crossing value print "Solving for good-to-bad crossing (max_gq={}).".format( max_gq) print "(m1, gq1) = ({}, {})".format(limit_x[i - 1], limit_y[i - 1]) print "(m2, gq2) = ({}, {})".format(limit_x[i], limit_y[i]) # Calculate crossing point x_cross_array = fsolve(lambda x: limit_graph.Eval(x) - max_gq, (limit_x[i - 1] + limit_x[i]) / 2.) if len(x_cross_array) != 1: raise ValueError("ERROR : Found more than one crossing!") x_cross = x_cross_array[0] # max_gq = limit_y[i-1] + (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) * dx ''' # Old method: analytical solution by hand slope = (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) dx = (max_gq - limit_y[i-1]) / slope x_cross = limit_x[i-1] + dx ''' x_points[-1].append(x_cross) y_points[-1].append(limit_graph.Eval(x_cross)) print "Found crossing (m, gq) = ({}, {})".format( x_cross, limit_graph.Eval(x_cross)) else: # Both above limit: ignore point pass # Convert sets of points to graphs new_graphs = [] for igraph in xrange(len(x_points)): if len(x_points[igraph]) == 0: print "[gq_summary_plot::truncate_graph_gq] WARNING : Graph has zero points".format( self._name) print x_points print y_points else: new_graphs.append(TGraph(len(x_points[igraph]))) for ipoint in xrange(len(x_points[igraph])): new_graphs[igraph].SetPoint(ipoint, x_points[igraph][ipoint], y_points[igraph][ipoint]) return new_graphs # Returns a set of graphs with a maximum Gamma/M (or minimum; specify invert=-1) def truncate_graph_gom(self, limit_graph, max_gom, invert=1): # Calculate the sets of x values for the new graphs limit_x = limit_graph.GetX() limit_y = limit_graph.GetY() limit_gom = [ Gamma_qq_tot(limit_y[i], limit_x[i], "vector") / limit_x[i] for i in xrange(limit_graph.GetN()) ] x_points = [[]] y_points = [[]] if invert * limit_gom[0] < invert * max_gom: x_points[-1].append(limit_x[0]) y_points[-1].append(limit_y[0]) for i in xrange(1, len(limit_x)): if invert * limit_gom[i - 1] < invert * max_gom and invert * limit_gom[ i] < invert * max_gom: x_points[-1].append(limit_x[i]) y_points[-1].append(limit_y[i]) elif invert * limit_gom[ i - 1] > invert * max_gom and invert * limit_gom[ i] < invert * max_gom: # limit crosses max_gom going down: new set if len(x_points[-1]) >= 1: x_points.append([]) y_points.append([]) # Calculate crossing point print "Solving for good-to-bad crossing (max_gom={}).".format( max_gom) print "(m1, gq1, gom1) = ({}, {}, {})".format( limit_x[i - 1], limit_y[i - 1], limit_gom[i - 1]) print "(m2, gq2, gom2) = ({}, {}, {})".format( limit_x[i], limit_y[i], limit_gom[i]) x_cross_array = fsolve( lambda x: Gamma_qq_tot(limit_graph.Eval(x), x, "vector") / x - max_gom, (limit_x[i - 1] + limit_x[i]) / 2.) if len(x_cross_array) != 1: raise ValueError("ERROR : Found more than one crossing!") x_cross = x_cross_array[0] print "Found crossing (m, gq, gom) = ({}, {}, {})".format( x_cross, limit_graph.Eval(x_cross), Gamma_qq_tot(limit_graph.Eval(x_cross), x_cross, "vector") / x_cross) ''' # Old method: analytical solution by hand # max_gom = limit_y[i-1] + (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) * dx slope = (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) dx = (max_gom - limit_y[i-1]) / slope x_cross = limit_x[i-1] + dx x_points[-1].append(x_cross) x_points[-1].append(limit_x[i]) y_points[-1].append(limit_graph.Eval(x_cross)) y_points[-1].append(limit_graph.Eval(limit_x[i])) ''' x_points[-1].append(x_cross) x_points[-1].append(limit_x[i]) y_points[-1].append(limit_graph.Eval(x_cross)) y_points[-1].append(limit_graph.Eval(limit_x[i])) elif invert * limit_gom[ i - 1] < invert * max_gom and invert * limit_gom[ i] > invert * max_gom: # limit crosses max_gom going up: end this set with crossing value # Calculate crossing point print "Solving for good-to-bad crossing (max_gom={}).".format( max_gom) print "(m1, gq1, gom1) = ({}, {}, {})".format( limit_x[i - 1], limit_y[i - 1], limit_gom[i - 1]) print "(m2, gq2, gom2) = ({}, {}, {})".format( limit_x[i], limit_y[i], limit_gom[i]) x_cross_array = fsolve( lambda x: Gamma_qq_tot(limit_graph.Eval(x), x, "vector") / x - max_gom, (limit_x[i - 1] + limit_x[i]) / 2.) if len(x_cross_array) != 1: raise ValueError("ERROR : Found more than one crossing!") x_cross = x_cross_array[0] print "Found crossing (m, gq, gom) = ({}, {}, {})".format( x_cross, limit_graph.Eval(x_cross), Gamma_qq_tot(limit_graph.Eval(x_cross), x_cross, "vector") / x_cross) # max_gom = limit_y[i-1] + (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) * dx ''' # Old method: analytical solution by hand slope = (limit_y[i]-limit_y[i-1])/(limit_x[i]-limit_x[i-1]) dx = (max_gom - limit_y[i-1]) / slope x_cross = limit_x[i-1] + dx ''' x_points[-1].append(x_cross) y_points[-1].append(limit_graph.Eval(x_cross)) else: # Both above limit: ignore point pass # Convert sets of points to graphs new_graphs = [] for igraph in xrange(len(x_points)): if len(x_points[igraph]) == 0: print "[gq_summary_plot::truncate_graph_gom] WARNING : Graph has zero points : {}".format( self._name) print x_points print y_points else: new_graphs.append(TGraph(len(x_points[igraph]))) for ipoint in xrange(len(x_points[igraph])): new_graphs[igraph].SetPoint(ipoint, x_points[igraph][ipoint], y_points[igraph][ipoint]) return new_graphs def draw( self, logx=False, logy=False, x_title="M_{Z'} [GeV]", y_title="g'_{q}", x_range=[40., 7000.], y_range=[0, 1.45], canvas_dim=[1800, 1200], canvas_rm=0.32, legend_coords=[0.69, 0.17, 0.99, 0.9], draw_cms=None, legend_text_size=0.028, legend_ncolumns=None, legend_obsexp=False, # Add a solid and dotted line to legend for obs and exp legend_header="#bf{95% CL exclusions}", draw_Z_constraint=False, z_width_legend_entry="#splitline{Z width (all #Gamma_{Z'}/M_{Z'})}{#it{[arXiv:1404.3947]}}", draw_upsilon_constraint=False, upsilon_width_legend_entry="#splitline{#Upsilon width (all #Gamma_{Z'}/M_{Z'})}{#it{[arXiv:1404.3947]}}", gom_x=None, # x coordinate for Gamma/M labels model_label=False, # Add a string specifying the model on the plot gom_fills=False, # Draw limit fills including upper boundaries conference_label=False # Draw "timestamp" label, i.e. "Moriond 2018" ): canvas_name = "c_{}_{}_{}{}".format(self._name, ("logx" if logx else "linearx"), ("logy" if logy else "lineary"), ("_gomfills" if gom_fills else "")) self._canvas = TCanvas(canvas_name, canvas_name, canvas_dim[0], canvas_dim[1]) ROOT.gStyle.SetPadTickX(1) ROOT.gStyle.SetPadTickY(1) self._canvas.SetLeftMargin(0.09) self._canvas.SetBottomMargin(0.12) self._canvas.SetTopMargin(0.075) self._canvas.SetRightMargin(canvas_rm) if logx: self._canvas.SetLogx() if logy: self._canvas.SetLogy() self._canvas.SetTicks(1, 1) self._canvas.cd() self._legend = TLegend(legend_coords[0], legend_coords[1], legend_coords[2], legend_coords[3]) self._legend.SetFillStyle(0) self._legend.SetBorderSize(0) self._legend.SetTextSize(legend_text_size) if legend_ncolumns: self._legend.SetNColumns(legend_ncolumns) # Legend headers and obs/exp lines self._legend.SetHeader(legend_header) if legend_obsexp: self._g_obs_dummy = TGraph(10) self._g_obs_dummy.SetLineStyle(1) self._g_obs_dummy.SetLineColor(1) self._g_obs_dummy.SetLineWidth(402) self._g_obs_dummy.SetMarkerStyle(20) self._g_obs_dummy.SetMarkerSize(0) self._g_obs_dummy.SetFillStyle(3004) self._g_obs_dummy.SetFillColor(1) self._legend.AddEntry(self._g_obs_dummy, "Observed", "lf") self._g_exp_dummy = TGraph(10) self._g_exp_dummy.SetLineStyle(2) self._g_exp_dummy.SetLineColor(1) self._g_exp_dummy.SetLineWidth(402) self._g_exp_dummy.SetMarkerStyle(20) self._g_exp_dummy.SetMarkerSize(0) self._legend.AddEntry(self._g_exp_dummy, "Expected", "l") self._frame = TH1D("frame", "frame", 100, x_range[0], x_range[1]) self._frame.SetDirectory(0) self._frame.GetYaxis().SetRangeUser(y_range[0], y_range[1]) self._frame.GetXaxis().SetTitle(x_title) self._frame.GetYaxis().SetTitle(y_title) self._frame.Draw("axis") if logx: self._frame.GetXaxis().SetMoreLogLabels() self._frame.GetXaxis().SetNdivisions(10) self._frame.GetXaxis().SetNoExponent(True) self._frame.GetXaxis().SetTitleOffset(1.) self._frame.GetXaxis().SetTitleSize(0.05) self._frame.GetXaxis().SetLabelSize(0.04) self._frame.GetYaxis().SetTitleOffset(0.8) self._frame.GetYaxis().SetTitleSize(0.05) self._frame.GetYaxis().SetLabelSize(0.04) #if logy: # self._frame.GetYaxis().SetMoreLogLabels() # Draw limit fills first, if any for name, limit_fill in self._limit_fills.iteritems(): self._limit_fills[name].SetFillStyle(3003) self._limit_fills[name].SetFillColor( self._style[name]["fill_color"]) self._limit_fills[name].Draw("F") legend_entry_count = 0 for analysis_name in self._analyses: if self._graphs[analysis_name]: self.style_graph(self._graphs[analysis_name], analysis_name) self._graphs[analysis_name].Draw("lp") if self._legend_entries[analysis_name] != False: self._legend.AddEntry(self._graphs[analysis_name], self._legend_entries[analysis_name], "l") legend_entry_count += 1 else: self._legend.AddEntry(0, self._legend_entries[analysis_name], "") legend_entry_count += 1 # Add an empty entry if needed, to put Z/Y constraints on the same line if legend_entry_count % 2 == 1: self._legend.AddEntry(0, "", "") if draw_Z_constraint: self._tf_Z_constraint = TF1("Z_constraint", gq_Z_constraint, x_range[0], x_range[1], 0) self._tf_Z_constraint.SetNpx(1000) self._tf_Z_constraint.SetLineColor(17) ROOT.gStyle.SetLineStyleString(9, "40 20") self._tf_Z_constraint.SetLineStyle(9) self._tf_Z_constraint.SetLineWidth(2) self._tf_Z_constraint.Draw("same") self._legend.AddEntry(self._tf_Z_constraint, z_width_legend_entry, "l") if draw_upsilon_constraint: self._tf_upsilon_constraint = TF1("upsilon_constraint", gq_upsilon_constraint, x_range[0], x_range[1], 0) self._tf_upsilon_constraint.SetNpx(1000) self._tf_upsilon_constraint.SetLineColor(17) ROOT.gStyle.SetLineStyleString(11, "20 10") self._tf_upsilon_constraint.SetLineStyle(11) self._tf_upsilon_constraint.SetLineWidth(2) self._tf_upsilon_constraint.Draw("same") self._legend.AddEntry(self._tf_upsilon_constraint, upsilon_width_legend_entry, "l") # Lines at fixed Gamma / M self._GoM_tf1s = {} self._GoM_labels = {} for i, GoM in enumerate(self._GoMs): self._GoM_tf1s[GoM] = TF1( "tf1_gq_{}".format(GoM), lambda x, this_gom=GoM: gom_to_gq(this_gom, x[0], self._vtype), x_range[0], x_range[1], 0) # self._GoM_tf1s[GoM].SetLineColor(ROOT.kGray + 1) self._GoM_tf1s[GoM].SetLineStyle(ROOT.kDashed) self._GoM_tf1s[GoM].SetLineWidth(1) self._GoM_tf1s[GoM].Draw("same") # TLatex for Gamma / M if gom_x: label_x = gom_x else: if logx: label_xfrac = 0.05 else: label_xfrac = 0.864 label_x = (x_range[1] - x_range[0]) * label_xfrac + x_range[0] if logy: label_y = self._GoM_tf1s[GoM].Eval(label_x) * 0.85 gom_text = "#Gamma_{{Z'}}#kern[-0.6]{{ }}/#kern[-0.7]{{ }}M_{{Z'}}#kern[-0.7]{{ }}=#kern[-0.7]{{ }}{}%".format( int(GoM * 100)) else: # label_y = self._GoM_tf1s[GoM].Eval(label_x) - 0.085 # For labels under the line label_y = self._GoM_tf1s[GoM].Eval( label_x) + 0.05 # For labels over the line gom_text = "#frac{{#Gamma}}{{M_{{Z'}}}} = {}%".format( int(GoM * 100)) self._GoM_labels[GoM] = TLatex(label_x, label_y, gom_text) if logy: self._GoM_labels[GoM].SetTextSize(0.028) else: self._GoM_labels[GoM].SetTextSize(0.027) self._GoM_labels[GoM].SetTextColor(ROOT.kGray + 1) self._GoM_labels[GoM].Draw("same") # Vector label if model_label: self._model_label = TLatex(model_label["x"], model_label["y"], model_label["text"]) if not "size_modifier" in model_label.keys(): model_label["size_modifier"] = 1. self._model_label.SetTextSize(0.04 * model_label["size_modifier"]) self._model_label.SetTextColor(1) self._model_label.Draw("same") # Legend last, to be on top of lines self._legend.Draw() if draw_cms: CMSLabel(self._canvas, extra_text=draw_cms, halign="left", valign="top", in_frame=False) if conference_label: self._conference_label = TLatex(conference_label["x"], conference_label["y"], conference_label["text"]) self._conference_label.SetTextSize(0.045) self._conference_label.SetTextColor(1) self._conference_label.Draw("same") # Redraw axis self._frame.Draw("axis same") def cd(self): self._canvas.cd() def save(self, folder, exts=["pdf"]): exts = [x.lower() for x in exts] if "png" in exts: eps_created = False for ext in exts: if ext == "png": eps_filename = "{}/{}.{}".format(folder, self._canvas.GetName(), "eps") if not eps_created: self._canvas.SaveAs(eps_filename) eps_created = True png_filename = "{}/{}.{}".format(folder, self._canvas.GetName(), "png") os.system("convert -trim -density 300 {} {}".format( eps_filename, png_filename)) else: self._canvas.SaveAs("{}/{}.{}".format(folder, self._canvas.GetName(), ext)) if ext == "eps": eps_created = True
def main(): c1 = TCanvas('roc', 'roc', 200, 10, 700, 500) c1.cd() if chisquare: points_0 = FindCurveChi2(TFile("hazel_sig_smear0.root"), TFile("hazel_bkg_smear0.root")) points_1 = FindCurveChi2(TFile("hazel_sig_smear1.root"), TFile("hazel_bkg_smear1.root")) points_2 = FindCurveChi2(TFile("hazel_sig_smear2.root"), TFile("hazel_bkg_smear2.root")) points_f = FindCurveChi2(TFile("hazel_sig_smearf.root"), TFile("hazel_bkg_smearf.root")) else: ####### No Smearing ############## points_0 = FindCurveDTheta(TFile("hazel_sig_smear0.root"), TFile("hazel_bkg_smear0.root")) ####### 1 Strip Smearing ############## points_1 = FindCurveDTheta(TFile("hazel_sig_smear1.root"), TFile("hazel_bkg_smear1.root")) ####### 2 Strip Smearing ############## points_2 = FindCurveDTheta(TFile("hazel_sig_smear2.root"), TFile("hazel_bkg_smear2.root")) points_f = FindCurveDTheta(TFile("hazel_sig_smearf.root"), TFile("hazel_bkg_smearf.root")) signal_eff_0 = points_0[0] background_rej_0 = points_0[1] n0 = len(signal_eff_0) signal_eff_1 = points_1[0] background_rej_1 = points_1[1] n1 = len(signal_eff_1) signal_eff_2 = points_2[0] background_rej_2 = points_2[1] n2 = len(signal_eff_2) signal_eff_f = points_f[0] background_rej_f = points_f[1] nf = len(signal_eff_f) if hist: h_sig_0 = TH1F("signal_dtheta", "signal dtheta", 1000, -0.05, 0.05) h_bkg_0 = TH1F("background_0", "background dtheta", 1000, -0.05, 0.05) for i in points_0[2]: h_sig_0.Fill(i) for i in points_0[3]: h_bkg_0.Fill(i) h_sig_1 = TH1F("signal_1", "signal_1", 1000, -0.05, 0.05) h_bkg_1 = TH1F("background_1", "background_1", 1000, -0.05, 0.05) for i in points_1[2]: h_sig_1.Fill(i) for i in points_1[3]: h_bkg_1.Fill(i) h_sig_2 = TH1F("signal_2", "signal_2", 1000, -0.05, 0.05) h_bkg_2 = TH1F("background_2", "background_2", 10000, -0.05, 0.05) for i in points_2[2]: h_sig_2.Fill(i) for i in points_2[3]: h_bkg_2.Fill(i) h_sig_f = TH1F("signal_f", "signal_f", 1000, -0.05, 0.05) h_bkg_f = TH1F("background_f", "background_f", 1000, -0.05, 0.05) for i in points_f[2]: h_sig_f.Fill(i) for i in points_f[3]: h_bkg_f.Fill(i) c1.SetGrid() gr0 = TGraph(n0, signal_eff_0, background_rej_0) gr1 = TGraph(n1, signal_eff_1, background_rej_1) gr2 = TGraph(n2, signal_eff_2, background_rej_2) grf = TGraph(nf, signal_eff_f, background_rej_f) gr0.GetXaxis().SetTitle('Signal Efficiency') gr0.GetYaxis().SetTitle('1 - Background Efficiency') if chisquare: gr0.SetTitle('ROC Curve for Chi2/NDF') else: gr0.SetTitle('ROC Curve for Delta Theta') gr0.SetLineColor(46) gr0.SetLineWidth(3) gr0.SetMarkerStyle(4) gr0.SetMarkerColor(2) gr1.SetLineColor(30) gr1.SetLineWidth(3) gr1.SetMarkerStyle(21) gr1.SetMarkerColor(3) gr2.SetLineColor(38) gr2.SetLineWidth(3) gr2.SetMarkerStyle(29) gr2.SetMarkerColor(4) grf.SetLineColor(12) grf.SetLineWidth(3) grf.SetMarkerStyle(31) grf.SetMarkerColor(1) gr0.Draw('APL') gr1.Draw('PL') gr2.Draw('PL') grf.Draw('PL') legend = ROOT.TLegend(0.1, 0.3, 0.48, 0.5) legend.AddEntry(gr0, '1M events, 0 strip smearing', "lp") legend.AddEntry(gr1, '1M events, 1 strip smearing', "lp") legend.AddEntry(gr2, '1M events, 2 strip smearing', "lp") legend.AddEntry(grf, '1M events, function smearing', "lp") legend.Draw() c1.Update() if chisquare: c1.SaveAs("%s.pdf" % (c1.GetName() + "_chi2")) else: c1.SaveAs("%s.pdf" % (c1.GetName() + "_dtheta")) if hist: c2 = TCanvas('signal_dtheta', 'signal_dtheta') c2.cd() h_sig_0.Draw("hist") h_sig_1.SetLineColor(2) h_sig_1.Draw("hist same") h_sig_2.SetLineColor(3) h_sig_2.Draw("hist same") h_sig_f.SetLineColor(1) h_sig_f.Draw("hist same") legend2 = ROOT.TLegend(0.1, 0.7, 0.48, 0.9) legend2.AddEntry(h_sig_0, '0 strip smearing', "l") legend2.AddEntry(h_sig_1, '1 strip smearing', "l") legend2.AddEntry(h_sig_2, '2 strip smearing', "l") legend2.AddEntry(h_sig_f, 'function smearing', "l") legend2.Draw() c2.Update() c2.SaveAs("%s.pdf" % (c2.GetName())) c3 = TCanvas('background_dtheta', 'background_dtheta') c3.cd() h_bkg_0.Draw("hist") h_bkg_1.SetLineColor(2) h_bkg_1.Draw("hist same") h_bkg_2.SetLineColor(3) h_bkg_2.Draw("hist same") h_bkg_f.SetLineColor(1) h_bkg_f.Draw("hist same") legend3 = ROOT.TLegend(0.1, 0.7, 0.48, 0.9) legend3.AddEntry(h_bkg_0, '0 strip smearing', "l") legend3.AddEntry(h_bkg_1, '1 strip smearing', "l") legend3.AddEntry(h_bkg_2, '2 strip smearing', "l") legend3.AddEntry(h_bkg_f, 'function smearing', "l") legend3.Draw() c3.Update() c3.SaveAs("%s.pdf" % (c3.GetName()))
class ViewPane(object): #a graphics window nviews = 0 def __init__(self, name, projection, nx, xmin, xmax, ny, ymin, ymax, dx=600, dy=600, subscreens=None): '''arguments @name name = title name for the pane @param projection = name of the projection (string) eg one of 'xy', 'yz', 'xz' ,'ECAL_thetaphi', 'HCAL_thetaphi' @param nx: points on x axis @param xmin: lower left corner x for ROOT hists @param xmax: upper right corner x for ROOT hists @param nx: points on x axis @param ymin: lower left corner y for ROOT hists @param ymax: upper right corner y for ROOT hists @param dx: horizontal size of each subscreen in pixels @param dy: vertical size of each subscreen in pixels @param subscreens: list of names of the subscreens ''' self.projection = projection self.hists = dict() self.registered = dict() self.locked = dict() tx = 50 + self.__class__.nviews * (dx + 10) ty = 50 width = 1 height = 1 #decide how to subdivide the window for the subscreens #normally split screen into horizontally side by side self.subscreens = dict() if subscreens is None: #The projection name and the subscreen name get concatenated. eg "xy: simulated", #when there is only one subscreen the subscreen string is not needed so is set to "" subscreens = [""] self.nsubscreens = len(subscreens) width = width * self.nsubscreens # normal case self.canvas = TCanvas(name, name, tx, ty, width * dx, height * dy) self.canvas.SetRightMargin(0.) self.canvas.SetLeftMargin(0.) self.canvas.SetTopMargin(0.) self.canvas.SetBottomMargin(0.) #command to divide the window up into width*height subscreens self.canvas.Divide(width, height) #manufacture the subscreens for x in range(0, self.nsubscreens): c1 = self.canvas.cd(x + 1) margin = 0.05 c1.SetLeftMargin(margin) c1.SetRightMargin(margin) c1.SetTopMargin(margin) c1.SetBottomMargin(margin) panename = name + ": " + subscreens[x] #create a ViewPad, this is the subscreen on which outputs will be plotted. #side is used to index the subscreens self.subscreens[x] = ViewPad(panename, name, nx, xmin, xmax, ny, ymin, ymax, side=x) self.__class__.nviews += 1 def register(self, obj, layer, clearable=True, sides=None): ''' the object will be registered in selected subscreens @param obj: thing to be plotted, this will have a draw function. Often will be a ROOT type object such as TGraph, TEllipse etc @param layer: what layer in plot to use. Higher layers are plotted **on top- check** @param clearable: not sure @param sides: if None will send to all subscreens, otherwise side=0 is first/left subscreen side = 1 is second (right) subscreen ''' if sides is None: sides = range(0, len(self.subscreens)) for x in sides: self.subscreens[x].register(obj, layer, clearable) def clear(self): for p in self.subscreens.itervalues(): p.clear() def draw(self): '''draw all subscreens ''' for x in range(0, self.nsubscreens): if self.canvas is None: pass else: self.canvas.cd(x + 1) self.subscreens[x].draw() self.canvas.Update() def zoom(self, xmin, xmax, ymin, ymax): '''intended to be called from the command line all subscreens are zoomed @param xmin: lower left corner x for the zoomed in screen using hist coordinates @param xmax: upper right corner x for the zoomed in screen using hist coordinates @param ymin: lower left corner y for the zoomed in screen using hist coordinates @param ymax: upper right corner y for the zoomed in screen using hist coordinates ''' for p in self.subscreens.itervalues(): p.zoom(xmin, xmax, ymin, ymax) self.draw() def unzoom(self): '''intended to be called from the command line all subscreens are unzoomed ''' for p in self.subscreens.itervalues(): p.unzoom() self.draw() def save(self, outdir, filename, filetype): '''write the screen to file @param outdir: directory for output files @param filename: base of the final filename eg "event_0" would end up with outputs such as "****xy_event_0_simulation****"" @param filetype: eg png file output. ***what else is supported*** ''' fname = '{outdir}/{name}.{filetype}'.format(outdir=outdir, name=filename + self.canvas.GetName(), filetype=filetype) self.canvas.SaveAs(fname)
for plane in otherplanes: branches[plane[0]][0] = float( randint(0, 11)) scores.append(reader.EvaluateMVA(ML)) MLscore = sum(scores) / float(len(scores)) plane_y.append(float(strip1)) plane_x.append(float(strip2)) MLscores.append(MLscore) ########## Make canvases, draw plots, and save them c = TCanvas( sample[0] + "_" + planey[1] + "vs" + planex[1] + "vs" + ML, sample[0] + "_" + planey[1] + "vs" + planex[1] + "vs" + ML) gr = TGraph2D(len(MLscores), plane_x, plane_y, MLscores) gr.SetName(sample[1] + " " + planey[1] + " vs " + planex[1] + " vs " + ML + " score") gr.Draw("COLZ") c.Update() gr.SetTitle(sample[1] + " " + planey[1] + " vs " + planex[1] + " vs " + ML + " score") gr.GetXaxis().SetTitle(planex[1]) gr.GetYaxis().SetTitle(planey[1]) gr.GetZaxis().SetTitle(ML + " score") gr.GetZaxis().SetTitleOffset(1.2) d_out.cd() c.Write() c.SaveAs(folder + "/%s.pdf" % (c.GetName()))
gr4.SetLineColor(6) gr4.SetLineWidth(1) gr4.SetMarkerStyle(49) gr4.SetMarkerColor(6) gr5.SetLineColor(7) gr5.SetLineWidth(1) gr5.SetMarkerStyle(39) gr5.SetMarkerColor(7) gr0.Draw('APL') gr1.Draw('PL') gr2.Draw('PL') gr3.Draw('PL') gr4.Draw('PL') gr5.Draw('PL') legend = ROOT.TLegend(0.1, 0.1, 0.45, 0.25) legend.SetNColumns(2) legend.AddEntry(gr0, 'DNN', "lp") legend.AddEntry(gr3, 'kNN', "lp") legend.AddEntry(gr1, 'BDT', "lp") legend.AddEntry(gr4, 'Delta Theta', "lp") legend.AddEntry(gr2, 'MLP', "lp") legend.AddEntry(gr5, 'Chi Squared', "lp") legend.Draw() c1.Update() c1.SaveAs("%s.pdf" % (c1.GetName() + "_1M_" + str(options.n)))