def Draw(self, histos, scales, ref, irelhisto, preview=False): from ROOT import TH1 from ROOT import TH1F from ROOT import THStack from ROOT import TLegend from ROOT import TCanvas # Creating a canvas canvas = TCanvas("tempo", "") # Special case : NPID, NAPID if ref.observable.name in ['NPID', 'NAPID']: # New collection with labels labels = [] # Loop over histos for ind in range(len(histos)): nBins = histos[ind].GetNbinsX() for b in range(1, nBins + 1): # Get the bin label theLabel = histos[ind].GetXaxis().GetBinLabel(b) # Add in the collection if theLabel not in labels: labels.append(theLabel) # Sorting labels (alphabetical order) labels = sorted(labels) # New histos newhistos = [] for ind in range(len(histos)): nBins = histos[ind].GetNbinsX() # New histo newhisto = TH1F(histos[ind].GetName()+'_'+str(ind),\ histos[ind].GetTitle(),\ len(labels), 0, len(labels)) for ilabel in range(len(labels)): # Set new labels newhisto.GetXaxis().SetBinLabel(ilabel + 1, labels[ilabel]) fill = False for bin in range(1, nBins + 1): # Get the bin label if histos[ind].GetXaxis().GetBinLabel( bin) == labels[ilabel]: tmp = histos[ind].GetBinContent(bin) newhisto.SetBinContent(ilabel + 1, tmp) fill = True break if not fill: newhisto.SetBinContent(ilabel + 1, 0) newhistos.append(newhisto) # overwrite histos histos = newhistos # Loop over datasets and histos for ind in range(0, len(histos)): if ref.observable.name in ['NPID', 'NAPID']: nBins = histos[ind].GetNbinsX() for b in range(1, nBins + 1): pid = int(histos[ind].GetXaxis().GetBinLabel(b)) if ref.observable.name == 'NPID': spid = self.main.multiparticles.GetName(pid) else: spid = self.main.multiparticles.GetAName(-pid, pid) if spid != "": histos[ind].GetXaxis().SetBinLabel(b, spid) # Scaling histos[ind].Scale(scales[ind]) # Stacking or superimposing histos ? stackmode = False if ref.stack==StackingMethodType.STACK or \ ( ref.stack==StackingMethodType.AUTO and \ self.main.stack==StackingMethodType.STACK ): stackmode = True # Setting AUTO settings if len(histos) == 1: histos[0].SetLineColor(9) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) elif len(histos) == 2: histos[0].SetLineColor(9) histos[1].SetLineColor(46) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) elif len(histos) == 3: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) elif len(histos) == 4: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) elif len(histos) == 5: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) elif len(histos) == 6: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) histos[5].SetLineColor(2) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) histos[5].SetFillColor(2) histos[5].SetFillStyle(3017) elif len(histos) == 7: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) histos[5].SetLineColor(2) histos[6].SetLineColor(7) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) histos[5].SetFillColor(2) histos[5].SetFillStyle(3017) histos[6].SetFillColor(7) histos[6].SetFillStyle(3022) elif len(histos) == 8: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) histos[5].SetLineColor(2) histos[6].SetLineColor(7) histos[7].SetLineColor(3) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) histos[5].SetFillColor(2) histos[5].SetFillStyle(3017) histos[6].SetFillColor(7) histos[6].SetFillStyle(3022) histos[7].SetFillColor(3) histos[7].SetFillStyle(3315) elif len(histos) == 9: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) histos[5].SetLineColor(2) histos[6].SetLineColor(7) histos[7].SetLineColor(3) histos[8].SetLineColor(42) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) histos[5].SetFillColor(2) histos[5].SetFillStyle(3017) histos[6].SetFillColor(7) histos[6].SetFillStyle(3022) histos[7].SetFillColor(3) histos[7].SetFillStyle(3315) histos[8].SetFillColor(42) histos[8].SetFillStyle(3351) elif len(histos) == 10: histos[0].SetLineColor(9) histos[1].SetLineColor(46) histos[2].SetLineColor(8) histos[3].SetLineColor(4) histos[4].SetLineColor(6) histos[5].SetLineColor(2) histos[6].SetLineColor(7) histos[7].SetLineColor(3) histos[8].SetLineColor(42) histos[9].SetLineColor(48) if stackmode: histos[0].SetFillColor(9) histos[0].SetFillStyle(3004) histos[1].SetFillColor(46) histos[1].SetFillStyle(3005) histos[2].SetFillColor(8) histos[2].SetFillStyle(3006) histos[3].SetFillColor(4) histos[3].SetFillStyle(3007) histos[4].SetFillColor(6) histos[4].SetFillStyle(3013) histos[5].SetFillColor(2) histos[5].SetFillStyle(3017) histos[6].SetFillColor(7) histos[6].SetFillStyle(3022) histos[7].SetFillColor(3) histos[7].SetFillStyle(3315) histos[8].SetFillColor(42) histos[8].SetFillStyle(3351) histos[9].SetFillColor(48) histos[9].SetFillStyle(3481) else: histos[ind].SetLineColor(self.color) self.color += 1 # Setting USER color for ind in range(0, len(histos)): # linecolor if self.main.datasets[ind].linecolor != ColorType.AUTO: histos[ind].SetLineColor(ColorType.convert2root( \ self.main.datasets[ind].linecolor,\ self.main.datasets[ind].lineshade)) # lineStyle histos[ind].SetLineStyle(LineStyleType.convert2code( \ self.main.datasets[ind].linestyle)) # linewidth histos[ind].SetLineWidth(self.main.datasets[ind].linewidth) # background color if self.main.datasets[ind].backcolor != ColorType.AUTO: histos[ind].SetFillColor(ColorType.convert2root( \ self.main.datasets[ind].backcolor,\ self.main.datasets[ind].backshade)) # background color if self.main.datasets[ind].backstyle != BackStyleType.AUTO: histos[ind].SetFillStyle(BackStyleType.convert2code( \ self.main.datasets[ind].backstyle)) # Creating and filling the stack; computing the total number of events stack = THStack("mystack", "") ntot = 0 for item in histos: ntot += item.GetEntries() stack.Add(item) # Drawing if stackmode: stack.Draw() else: stack.Draw("nostack") # Setting Y axis label axis_titleY = ref.GetYaxis() # Scale to one ? scale2one = False if ref.stack==StackingMethodType.NORMALIZE2ONE or \ (self.main.stack==StackingMethodType.NORMALIZE2ONE and \ ref.stack==StackingMethodType.AUTO): scale2one = True if scale2one: axis_titleY += " ( scaled to one )" elif self.main.normalize == NormalizeType.LUMI or \ self.main.normalize == NormalizeType.LUMI_WEIGHT: axis_titleY += " ( L_{int} = " + str(self.main.lumi) + " fb^{-1} )" elif self.main.normalize == NormalizeType.NONE: axis_titleY += " (not normalized)" if ref.titleY != "": axis_titleY = self.NiceTitle(ref.titleY) stack.GetYaxis().SetTitle(axis_titleY) if (len(axis_titleY) > 35): stack.GetYaxis().SetTitleSize(0.04) else: stack.GetYaxis().SetTitleSize(0.06) stack.GetYaxis().SetTitleFont(22) stack.GetYaxis().SetLabelSize(0.04) # Setting X axis label if ref.titleX == "": axis_titleX = ref.GetXaxis() else: axis_titleX = self.NiceTitle(ref.titleX) # Setting X axis label stack.GetXaxis().SetTitle(axis_titleX) stack.GetXaxis().SetTitleSize(0.06) stack.GetXaxis().SetTitleFont(22) stack.GetXaxis().SetLabelSize(0.04) # Setting Log scale if ref.logX and ntot != 0: canvas.SetLogx() if ref.logY and ntot != 0: canvas.SetLogy() # Displaying a legend if len(self.main.datasets) > 1: ymin_legend = .9 - .055 * len(histos) if ymin_legend < 0.1: ymin_legend = 0.1 legend = TLegend(.65, ymin_legend, .9, .9) legend.SetTextSize(0.05) legend.SetTextFont(22) for ind in range(0, len(histos)): legend.AddEntry(histos[ind], self.NiceTitle(self.main.datasets[ind].title)) legend.SetFillColor(0) legend.Draw() if not preview: # Save the canvas in the report format canvas.SaveAs(self.output_path+"/selection_"+str(irelhisto)+"."+\ ReportFormatType.convert2filetype(self.mode)) # Save the canvas in the C format canvas.SaveAs(self.output_path + "/selection_" + str(irelhisto) + ".C") else: # break answer = raw_input("Press enter to continue : ")
h_signal_2017.Integral()) h_signal_2016.Scale(scaling_factor_2016_2018) h_signal_2016.SetMarkerStyle(20) h_signal_2016.SetMarkerColor(3) h_signal_2017.Scale(scaling_factor_2017_2018) h_signal_2017.SetMarkerStyle(20) h_signal_2017.SetMarkerColor(2) h_signal_2018.SetMarkerStyle(20) h_signal_2018.SetMarkerColor(1) h_signal_2016.GetXaxis().SetLabelOffset(999) h_signal_2016.GetXaxis().SetTitle("#it{m}_{#pi#gamma} (GeV)") h_signal_2016.GetYaxis().SetTitle("Events") h_signal_2016.Draw() h_signal_2017.Draw("SAME") h_signal_2018.Draw("SAME") legend_years.Draw("SAME") pad2.cd() pad2.SetTopMargin(0.03) pad2.SetFillColor(0) pad2.SetFillStyle(0) for entry in h_ratio_list: h_ratio_hists[entry].SetTitle("") h_ratio_hists[entry].SetMarkerStyle(8) h_ratio_hists[entry].SetLineColor(1) h_ratio_hists[entry].GetYaxis().SetLabelSize(0.1) h_ratio_hists[entry].GetYaxis().SetTitle("Ratio") h_ratio_hists[entry].GetYaxis().SetTitleSize(0.12) #h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.98) h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.25)
def plotBlockComparison(treeBlockA,treeBlockB,variable,additionalCut,nBins,firstBin,lastBin,labelX,labelY,suffix,log=False,signal=False): hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() legend = TLegend(0.7, 0.55, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(1) minMll = 20 ROOT.gStyle.SetOptStat(0) Cutlabel = ROOT.TLatex() Cutlabel.SetTextAlign(12) Cutlabel.SetTextSize(0.03) Labelin = ROOT.TLatex() Labelin.SetTextAlign(12) Labelin.SetTextSize(0.07) Labelin.SetTextColor(ROOT.kRed+2) Labelout = ROOT.TLatex() Labelout.SetTextAlign(12) Labelout.SetTextSize(0.07) Labelout.SetTextColor(ROOT.kBlack) EMuhistBlockA = createHistoFromTree(treeBlockA, variable, additionalCut, nBins, firstBin, lastBin, -1) EMuhistBlockB = createHistoFromTree(treeBlockB, variable, additionalCut, nBins, firstBin, lastBin, -1) EMuhistBlockB.Scale(9.2/10.4) print EMuhistBlockA.Integral() print EMuhistBlockB.Integral() EMuhistBlockA.SetMarkerStyle(21) EMuhistBlockB.SetMarkerStyle(22) EMuhistBlockA.SetMarkerColor(ROOT.kGreen+3) EMuhistBlockB.SetMarkerColor(ROOT.kBlack) EMuhistBlockA.SetLineColor(ROOT.kGreen+3) EMuhistBlockB.SetLineColor(ROOT.kBlack) if log: yMin=0.1 yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),EMuhistBlockB.GetBinContent(EMuhistBlockB.GetMaximumBin()))*10 plotPad.SetLogy() else: yMin=0 yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),EMuhistBlockB.GetBinContent(EMuhistBlockB.GetMaximumBin()))*1.5 hCanvas.DrawFrame(firstBin,yMin,lastBin,yMax,"; %s ; %s" %(labelX,labelY)) EMuhistBlockA.Draw("samep") EMuhistBlockB.Draw("samep") legend.AddEntry(EMuhistBlockA,"First 9.2 fb^{-1}","p") legend.AddEntry(EMuhistBlockB,"Second 10.4 fb^{-1} scaled","p") #~ latex = ROOT.TLatex() latex.SetTextSize(0.043) latex.SetTextFont(42) latex.SetNDC(True) latex.DrawLatex(0.13, 0.95, "CMS Preliminary, #sqrt{s} = 8 TeV, #scale[0.6]{#int}Ldt = 9.2-10.4 fb^{-1}") #~ legend.Draw("same") ratioPad.cd() ratioGraphs = ratios.RatioGraph(EMuhistBlockA,EMuhistBlockB, firstBin, lastBin,title="Bl. A / Bl. B",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kGreen+3,adaptiveBinning=0.25) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) if signal: name = "OFUnblinding_SignalRegion_%s_%s.pdf" else: name = "OFUnblinding_Inclusive_%s_%s.pdf" if variable == "p4.M()": hCanvas.Print(name%(suffix,"Mll")) else: hCanvas.Print(name%(suffix,variable)) hCanvas.Clear()
def plotUpperLimits(labels, values): # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/ N = len(labels) yellow = TGraph(2 * N) # yellow band green = TGraph(2 * N) # green band median = TGraph(N) # median line up2s = [] for i in range(N): file_name = "higgsCombine" + labels[i] + ".AsymptoticLimits.mH125.root" limit = getLimits(file_name) up2s.append(limit[4]) yellow.SetPoint(i, values[i], limit[4]) # + 2 sigma green.SetPoint(i, values[i], limit[3]) # + 1 sigma median.SetPoint(i, values[i], limit[2]) # median green.SetPoint(2 * N - 1 - i, values[i], limit[1]) # - 1 sigma yellow.SetPoint(2 * N - 1 - i, values[i], limit[0]) # - 2 sigma W = 800 H = 600 T = 0.08 * H B = 0.12 * H L = 0.12 * W R = 0.04 * W c = TCanvas("c", "c", 100, 100, W, H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.SetTickx(0) c.SetTicky(0) c.SetGrid() c.cd() frame = c.DrawFrame(1.4, 0.001, 4.1, 10) frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitleSize(0.05) frame.GetXaxis().SetTitleSize(0.05) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.GetYaxis().SetTitleOffset(0.9) frame.GetXaxis().SetNdivisions(508) frame.GetYaxis().CenterTitle(True) frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}") # frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}") frame.GetXaxis().SetTitle("background systematic uncertainty [%]") frame.SetMinimum(0) frame.SetMaximum(max(up2s) * 1.05) frame.GetXaxis().SetLimits(min(values), max(values)) yellow.SetFillColor(ROOT.kOrange) yellow.SetLineColor(ROOT.kOrange) yellow.SetFillStyle(1001) yellow.Draw("F") green.SetFillColor(ROOT.kGreen + 1) green.SetLineColor(ROOT.kGreen + 1) green.SetFillStyle(1001) green.Draw("Fsame") median.SetLineColor(1) median.SetLineWidth(2) median.SetLineStyle(2) median.Draw("Lsame") cms_lumi.cms_lumi(c, 14, 11) ROOT.gPad.SetTicks(1, 1) frame.Draw("sameaxis") x1 = 0.15 x2 = x1 + 0.24 y2 = 0.76 y1 = 0.60 legend = TLegend(x1, y1, x2, y2) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextSize(0.041) legend.SetTextFont(42) legend.AddEntry(median, "Asymptotic CL_{s} expected", "L") legend.AddEntry(green, "#pm 1 std. deviation", "f") # legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f') legend.AddEntry(yellow, "#pm 2 std. deviation", "f") # legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f') legend.Draw() print(" ") c.SaveAs("UpperLimit.png") c.Close()
def plot1(key, xsection1, xsection2, histo1, histo2, name1, name2, LogY, weight1, weight2, outputDIR): c1=TCanvas(key, key, 800, 600) pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99) pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20) pad1.SetGridx() pad1.SetGridy() pad2.SetGridy() pad1.SetFillColor(0) pad1.SetLineColor(0) pad2.SetFillColor(0) pad2.SetLineColor(0) pad1.SetBottomMargin(0.03) pad2.SetTopMargin(0.15) pad2.SetBottomMargin(0.3) pad1.Draw() pad2.Draw() leg1 = TLegend(0.65,0.75,0.86,0.86) histo1.Scale(xsection1/weight1) histo1.SetMaximum(1.2*histo1.GetMaximum()) histo1.SetMinimum(0.0001) histo1.SetLineColor(kRed) histo1.SetLineWidth(2) histo1.GetXaxis().SetLabelSize(0) histo2.Scale(xsection2/weight2) histo2.SetLineColor(kBlack) histo2.SetLineWidth(2) pad1.cd() if LogY: pad1.SetLogy() histo_ratio=histo2.Clone() histo_ratio.SetTitle('') histo_ratio.Divide(histo1) histo_ratio.SetMaximum(1.5) histo_ratio.SetMinimum(0.5) histo_ratio.GetYaxis().SetNdivisions(4,kFALSE) histo_ratio.GetXaxis().SetTitle(key) histo_ratio.GetXaxis().SetTitleSize(0.15) histo_ratio.GetXaxis().SetTitleOffset(0.75) histo_ratio.GetXaxis().SetLabelSize(0.13) histo_ratio.GetYaxis().SetTitle(name1+'/'+name2) histo_ratio.GetYaxis().SetTitleSize(0.1) histo_ratio.GetYaxis().SetTitleOffset(0.3) histo_ratio.GetYaxis().SetLabelSize(0.13) histo_ratio.SetLineWidth(2) histo1.Draw('pe') histo2.Draw('same pe') leg1.AddEntry(histo1, name1) leg1.AddEntry(histo2, name2) leg1.SetFillStyle(0) leg1.SetBorderSize(0) leg1.Draw() c1.Update() pad2.cd() histo_ratio.Draw() if LogY: c1.SaveAs(outputDIR + '/' + key + '_log.png') c1.SaveAs(outputDIR + '/' + key + '_log.pdf') else: c1.SaveAs(outputDIR + '/' + key + '.png') c1.SaveAs(outputDIR + '/' + key + '.pdf') # renew histo1.Scale(weight1/xsection1) histo2.Scale(weight2/xsection2)
def comp_fit_pars(do_ratio=False, meson='Ds'): #pylint: disable-msg=too-many-statements,too-many-locals inputdir = '../../AnalysisNonPromptDpp2017/Dplus/outputs/rawyields' input_files = ['RawYieldsDplus_pp5TeV_prompt_central.root', 'RawYieldsDplus_pp5TeV_FD_central_freesigma.root'] input_files_MC = ['RawYieldsDplusMC_pp5TeV_prompt_central.root', 'RawYieldsDplusMC_pp5TeV_FD_central.root'] colors = [kOrange+7, kAzure+2, kRed+1, kAzure+4] markers = [kOpenCircle, kOpenSquare, kFullCircle, kFullSquare] legendnames = ['MC - prompt enhanced', 'MC - FD enhanced', 'data - prompt enhanced', 'data - FD enhanced'] suffix = 'CompMCData' min_pt = 2. max_pt = 16. SetGlobalStyle(padleftmargin=0.18, padtopmargin=0.05, padbottommargin=0.14, titleoffsety=1.6, titlesize=0.045, labelsize=0.04) hMean, hSigma = [], [] input_files = input_files_MC + input_files if meson == 'Ds': massD = TDatabasePDG.Instance().GetParticle(431).Mass() elif meson == 'Dplus': massD = TDatabasePDG.Instance().GetParticle(411).Mass() lineMass = TLine(min_pt, massD, max_pt, massD) lineMass.SetLineWidth(2) lineMass.SetLineColor(kBlack) lineMass.SetLineStyle(9) legSigma = TLegend(0.2, 0.78, 0.8, 0.93) legSigma.SetFillStyle(0) legSigma.SetBorderSize(0) legSigma.SetTextSize(0.04) legMean = TLegend(0.4, 0.73, 0.7, 0.93) legMean.SetFillStyle(0) legMean.SetBorderSize(0) legMean.SetTextSize(0.04) legMean.AddEntry(lineMass, "PDG", 'l') for file_path, color, marker, legend_name in zip(input_files, colors, markers, legendnames): input_file = TFile(f'{inputdir}/{file_path}') histo_mean = input_file.Get('hRawYieldsMean') histo_sigma = input_file.Get('hRawYieldsSigma') histo_mean.SetDirectory(0) histo_sigma.SetDirectory(0) SetObjectStyle(histo_mean, linecolor=color, markercolor=color, markerstyle=marker) SetObjectStyle(histo_sigma, linecolor=color, markercolor=color, markerstyle=marker) legMean.AddEntry(histo_mean, legend_name, 'p') legSigma.AddEntry(histo_sigma, legend_name, 'p') hMean.append(histo_mean) hSigma.append(histo_sigma) if do_ratio: mean_num_list = list(hMean) mean_num_list.pop(0) mean_den_hist = hMean[0] mean_ratio_list = [] for histo in mean_num_list: mean_ratio_list.append(ComputeRatioDiffBins(histo, mean_den_hist)) cMeanRatio = TCanvas('cMeanRatio', '', 800, 800) cMeanRatio.DrawFrame(min_pt, 0.99, max_pt, 1.01, ';#it{p}_{T} (GeV/#it{c}); peak mean / peak mean MC') lineRatio = TLine(min_pt, 1., max_pt, 1.) lineRatio.SetLineWidth(2) lineRatio.SetLineColor(kBlack) lineRatio.SetLineStyle(9) legMeanRatio = TLegend(0.4, 0.73, 0.7, 0.93) legMeanRatio.SetFillStyle(0) legMeanRatio.SetBorderSize(0) legMeanRatio.SetTextSize(0.04) for hist, color, marker, legend_name in zip(mean_ratio_list, colors[1:], markers[1:], legendnames[1:]): SetObjectStyle(hist, linecolor=color, markercolor=color, markerstyle=marker) hist.Draw('same') legMeanRatio.AddEntry(hist, legend_name, 'p') lineRatio.Draw() legMeanRatio.Draw() sigma_num_list = list(hSigma) sigma_num_list.pop(0) sigma_den_hist = hSigma[0] sigma_ratio_list = [] for histo in sigma_num_list: sigma_ratio_list.append(ComputeRatioDiffBins(histo, sigma_den_hist)) cSigmaRatio = TCanvas('cSigmaRatio', '', 800, 800) hFrameSigma = cSigmaRatio.DrawFrame(min_pt, 0.6, max_pt, 1.8, ';#it{p}_{T} (GeV/#it{c}); peak width / peak width MC') hFrameSigma.GetYaxis().SetDecimals() legSigmaRatio = TLegend(0.4, 0.73, 0.7, 0.93) legSigmaRatio.SetFillStyle(0) legSigmaRatio.SetBorderSize(0) legSigmaRatio.SetTextSize(0.04) for hist, color, marker, legend_name in zip(sigma_ratio_list, colors[1:], markers[1:], legendnames[1:]): SetObjectStyle(hist, linecolor=color, markercolor=color, markerstyle=marker) hist.Draw('same') legSigmaRatio.AddEntry(hist, legend_name, 'p') lineRatio.Draw() legSigmaRatio.Draw() cMeanRatio.SaveAs(f'{inputdir}/MeanRatio_{suffix}.pdf') cSigmaRatio.SaveAs(f'{inputdir}/SigmaRatio_{suffix}.pdf') cMean = TCanvas('cMean', '', 800, 800) hFrameMean = cMean.DrawFrame(min_pt, massD*0.995, max_pt, massD*1.01, ';#it{p}_{T} (GeV/#it{c}); peak mean (GeV/#it{c}^{2})') hFrameMean.GetYaxis().SetDecimals() lineMass.Draw("same") for histo_mean in hMean: histo_mean.Draw('same') legMean.Draw() cSigma = TCanvas('cSigma', '', 800, 800) cSigma.DrawFrame(min_pt, 0., max_pt, 0.025, ';#it{p}_{T} (GeV/#it{c}); peak width (GeV/#it{c}^{2})') for histo_sigma in hSigma: histo_sigma.Draw('same') legSigma.Draw() cMean.SaveAs(f'{inputdir}/Mean_{suffix}.pdf') cSigma.SaveAs(f'{inputdir}/Sigma_{suffix}.pdf') input('Press enter to exit')
else: tau_frWeight = tree_t.tau_fake_prob evtWeight = evtWeight * lep1_frWeight * lep2_frWeight * lep3_frWeight * tau_frWeight mvaValue = reader.EvaluateMVA("testmva") hist_bkg.Fill(mvaValue, evtWeight) hist_signal.SetLineColor(2) hist_bkg.SetLineColor(4) hist_signal.SetFillColor(2) hist_bkg.SetFillColor(4) hist_signal.SetFillStyle(3004) hist_bkg.SetFillStyle(3005) leg = TLegend(0.2, 0.65, 0.5, 0.9) leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetLineColor(0) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetTextFont(42) leg.AddEntry(hist_signal, "loose selection", "l") leg.AddEntry(hist_bkg, "tight selection", "l") hist_signal.DrawNormalized("histsame") hist_bkg.DrawNormalized("histsame") leg.Draw() c1.SaveAs("plots/bdt_score_sklearn_3l1t_8Var_wfrWt_loose_vs_tight_" + process + ".png")
if "Pt" in plotName_list[i]: canvas.SetLogy() # if "Chi2" in plotName_list[i] : # canvas.SetLogx() # gmt_list[i].Draw('EP') kalman_list[i].Draw('EP') kalmanAll_list[i].Draw('sameEP') bmtfStd_list[i].Draw('sameEP') bmtf_list[i].Draw('sameEP') # legend legend = TLegend(0.80, 0.74, 0.99, 0.91) legend.AddEntry(kalman_list[i], "Kalman Cleaned", "pl") legend.AddEntry(kalmanAll_list[i], "Kalman All", "pl") # legend.AddEntry(gmt_list[i],"Gmt","pl") legend.AddEntry(bmtfStd_list[i], "BmtfStd", "pl") legend.AddEntry(bmtf_list[i], "Bmtf", "pl") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(14) #20 legend.Draw() canvas.Update() canvas.SaveAs(OutputPath + "/" + plotName_list[i] + ".pdf") canvas.SaveAs(OutputPath + "/" + plotName_list[i] + ".png")
def sysCompare(): parser = argparse.ArgumentParser( description='Produce Systematic Uncertainties From Varied inputs.') parser.add_argument( '-d', '--directory', required=False, default="", type=str, help= "Directory for comparison plots. If none given, plots are not saved") parser.add_argument( '-l', '--list', required=False, type=str, default="", help= "List of histograms/graphs to use. If not given, all objects are used." ) parser.add_argument('-o', '--output', required=True, type=str, help="Output file to produce") # parser.add_argument('-a','--all',requred=False,type=bool,help="whether to use all valid objects in the first file") parser.add_argument('-r', '--ratioMode', required=False, type=bool, default=False, help="Whether to produce plots of the ratios") parser.add_argument( '-c', '--centerValueMode', required=False, default=0, type=int, help= "Whether to use the first file as the central value (0) or the average (1)" ) parser.add_argument('-t', '--titles', required=True, type=str, nargs='+', help="Titles for each file") parser.add_argument('-f', '--files', metavar='Files', required=True, type=str, nargs='+', help="Files to use") parser.add_argument('-D', '--DeletePoints', required=False, default=0, type=int, help="Delete the beginning N points for TGraphs") # parser.add_argument('files',metavar='Files',type=str,nargs='+',help="Files to use") parser.add_argument('-T', '--OverallTitle', required=False, type=str, default="", help="Title to appear in legend headers") parser.add_argument('-y', '--LogY', required=False, type=int, default=False, help="Whether to force the plots to have log Y.") args = parser.parse_args() setStyle() stringListOfHists = args.list #list of hists/graphs listOfHists = stringListOfHists.split() # bUseAllObjs=False # if (len(listOfHists) == 0): # bUseAllObjs=True bUseAllObjs = (len(listOfHists) == 0) bRatioMode = args.ratioMode if (bRatioMode): print("Ratio Mode is enabled.") #array of files fileNames = args.files fileTitles = args.titles directory = args.directory outputFileName = args.output CenterValueMode = args.centerValueMode LogYMode = False LogYMode = args.LogY numDelete = args.DeletePoints print("List of hists/graphs to use:"), print(listOfHists) if (bUseAllObjs): print("Will use all valid objects found in the first file") else: print("List of files to use:") print(fileNames) print("That is %d files" % (len(fileNames))) print("List of titles:") print(fileTitles) print("That is %d titles" % (len(fileTitles))) if (len(fileNames) != len(fileTitles)): print("Error: mismatch in number of files vs titles") exit(1) print("Primary file:") print(fileNames[0]) if (numDelete > 0): print("Will delete the first %d points from TGraphs" % (numDelete)) # list of files files = [] titlesToFileNames = zip(fileTitles, fileNames) titlesToFileNames = set(titlesToFileNames) print(titlesToFileNames) fileNamesToTitles = zip(fileNames, fileTitles) fileNamesToTitles = dict(fileNamesToTitles) filesToTitles = {} cleanTitlesToFiles = {} filesToCleanTitles = {} for filename in fileNames: print("Opening File %s" % (filename)) tfile = TFile.Open(filename, "READ") print("opened file %s" % (tfile.GetName())) files.append(tfile) filesToTitles[tfile] = fileNamesToTitles[filename] # clean name that can be added to root object names cleanedTitle = cleanName(fileNamesToTitles[filename]) filesToCleanTitles[tfile] = cleanedTitle primaryFile = files[0] if (directory == ""): print("No directory given. Output plots will not be saved") else: print("Directory for output %s" % (directory)) # create output file here, before changing directory outputFile = TFile.Open(outputFileName, "RECREATE") OverallTitle = args.OverallTitle canvas = TCanvas("canvas", "canvas", c_width, c_height) if (directory != ""): # check if the directory exists if (not os.path.isdir(directory)): os.makedirs(directory) os.chdir(directory) # This is where it gets easier than compare: just need to find the objects in the files if (bUseAllObjs): print("Building list of objects") #primaryObj ListOfKeys = primaryFile.GetListOfKeys() for key in ListOfKeys: print("Adding item %s" % (key.GetName())) listOfHists.append(key.GetName()) for objName in listOfHists: print("Starting the thing for object %s" % (objName)) #print(" Looking in file %s" % (primaryFile.GetName())) primaryObj = primaryFile.Get(objName) if (not primaryObj): print("Could not find object %s in file %s" % (objName, fileNames[0])) else: print("obj title = %s" % (primaryObj.GetTitle())) objectTitle = primaryObj.GetTitle() listOfObjs = [] for tfile in files: localObj = tfile.Get(objName) if (not localObj): print("Could not find object %s in file %s" % (objName, tfile)) exit(1) else: print("obj title = %s" % (localObj.GetTitle())) localObj.SetName("%s_%s" % (objName, filesToCleanTitles[tfile])) print(" name set to %s" % (localObj.GetName())) localObj.SetTitle(filesToTitles[tfile]) print(" title set to %s" % (localObj.GetTitle())) listOfObjs.append(localObj) legX = 0.6 legY = 0.22 legWidth = 0.2 #0.45 legHeight = 0.4 #0.225 # legend for comparison # leg = TLegend(legX,legY,legX+legWidth,legY+legHeight) # legend for SysUncert # leg2 = TLegend(legX,legY,legX+legWidth,legY+legHeight) # legend for comparison leg = TLegend(legWidth, legHeight, legWidth, legHeight) if (OverallTitle != ""): leg.SetHeader(OverallTitle, "c") # legend for SysUncert leg2 = TLegend(legWidth, legHeight, legWidth, legHeight) # Set Properties and include in legend for i in range(len(listOfObjs)): localObj = listOfObjs[i] localTitle = fileTitles[i] color = ROOT.kBlack if (i != 0): if (useCustomColor): color = GetCustomColor(i) else: color = colorList[i] if (i >= len(markerList)): # This check code is redundant for now, in case I # want to switch so something fancier than just looping # marker styles markerStyle = markerList[i % len(markerList)] else: markerStyle = markerList[i] localObj.SetMarkerColor(color) localObj.SetLineColor(color) localObj.SetMarkerStyle(markerStyle) localObj.SetTitle(localTitle) localObj.SetFillColor(0) leg.AddEntry(localObj, localTitle, "LP") leg2.AddEntry(listOfObjs[0], fileTitles[0], "LP") # Two key cases: TGraph or TH1 # For TGraphs we want to do a multigraph # for th1, we have to manually track the y-limits iObjType = GetObjType(listOfObjs[0]) # tgraph : 1 # th1 : 2 # other : 0 canvas.Clear() canvas.cd() if (iObjType == 0): # Not coded yet print("Object is of a type I don't have comparison code for (yet)") continue if (iObjType == 1): # TGraph # Get object name #objName = "TestGraph" # Reset the margins gPad.SetTopMargin(fDefaultTopMargin) gPad.SetLeftMargin(fDefaultLeftMargin) gPad.SetBottomMargin(fDefaultBottomMargin) gPad.SetRightMargin(fDefaultRightMargin) mg = TMultiGraph() for j in range(numDelete): print("Deleting a point from object %s" % (primaryObj.GetName())) primaryObj.RemovePoint(0) # remove the first point mg.SetTitle(primaryObj.GetTitle()) mg.GetXaxis().SetTitle(primaryObj.GetXaxis().GetTitle()) mg.GetYaxis().SetTitle(primaryObj.GetYaxis().GetTitle()) # FIXME is this going to double deleting points from the primary object for lobj in listOfObjs: print("Object starts with %d points" % (lobj.GetN())) for j in range(numDelete): print("Deleting a point from object %s" % (lobj.GetName())) lobj.RemovePoint(0) # remove the first point print("Object ends with %d points" % (lobj.GetN())) mg.Add(lobj) mg.Draw("ALP") mg.GetXaxis().SetLabelSize(AxisLabelSizeX) mg.GetYaxis().SetLabelSize(AxisLabelSizeY) #leg.Draw("SAME") legtest = gPad.BuildLegend() legtest.Draw("SAME") if (directory != ""): canvas.Print("%s_Cmp.pdf" % (objName)) canvas.Print("%s_Cmp.png" % (objName)) canvas.Print("%s_Cmp.C" % (objName)) # Now produce systematic uncertainties (for TGraphErrors (sysUncertObj, ListOfRangeHists) = ProduceSystematicFromGraphs(listOfObjs) sysUncertObj.SetName("%s_SysErr" % (objName)) #sysUncertObj.SetName(objName) totalUncertObj = ProduceTotalErrorGraphs(primaryObj, sysUncertObj) totalUncertObj.SetName(objName) #totalUncertObj.SetName("%s_TotalErr" % (objName)) sysUncertObj.SetTitle("Systematic Uncertainty") sysUncertObj.SetFillColor(ROOT.kBlue) sysUncertObj.SetFillStyle(3002) sysUncertObj.Draw("ALP[]5") # reset the primary objects title primaryObj.Draw("LP") leg2.AddEntry(sysUncertObj, "Systematic Uncertainty", "F") #mg.Draw("LP") #leg.Draw("SAME") leg2.Draw("SAME") # not using the autobuild legend here. could get a good location # from the comparison plot #legtest2=gPad.BuildLegend() #legtest2.Draw("SAME") if (directory != ""): canvas.Print("%s_SysUncert.pdf" % (objName)) canvas.Print("%s_SysUncert.png" % (objName)) outputFile.Add(sysUncertObj) outputFile.Add(totalUncertObj) for hist in ListOfRangeHists: outputFile.Add(hist) # Now plot them both in a split canvas canvas.Clear() canvas.Divide(1, 2, 0.01, 0.0) canvas.cd(1) mg.Draw("ALP X+") gPad.SetTopMargin(0.0) leg.Draw("SAME") gPad.SetBottomMargin(0.0) canvas.cd(2) sysUncertObj.Draw("ALP[]5") gPad.SetTopMargin(0.0) gPad.SetBottomMargin(0.1) primaryObj.Draw("LP") leg2.Draw("SAME") if (directory != ""): canvas.Print("%s_SysUncert_Cmp.pdf" % (objName)) canvas.Print("%s_SysUncert_Cmp.png" % (objName)) canvas.Print("%s_SysUncert_Cmp.C" % (objName)) canvas.Clear() canvas.Divide(1, 2, 0.01, 0.0) ratioMg = TMultiGraph() legRatio = TLegend(2 * legWidth, legHeight, 2 * legWidth, legHeight) #RatioArray=[] # Make, draw ratios if (bRatioMode): max_ratio_y = 1. min_ratio_y = 1. nPointsFirst = primaryObj.GetN() bDivisionPossible = True for lobj in listOfObjs: if (nPointsFirst != lobj.GetN()): bDivisionPossible = False if (bDivisionPossible): numObjects = 0 for lobj in listOfObjs: numObjects = numObjects + 1 if (lobj == primaryObj): print("Avoided TGraph over itself using object") continue if (lobj.GetName() == primaryObj.GetName()): print("Avoided TGraph over itself using name") continue if (numObjects == 1): print("Avoided TGraph over itself using index") continue ratioName = "%s_Ratio" % (lobj.GetName()) lRatio = DivideTGraphErrors(lobj, primaryObj, ratioName) lRatio.SetTitle("%s / %s" % (lobj.GetTitle(), fileTitles[0])) ratioMg.Add(lRatio) legRatio.AddEntry(lRatio, lRatio.GetTitle(), "LP") # RatioArray.append(lRatio) ratioMg.GetYaxis().SetTitle("Ratio over (%s)" % (fileTitles[0])) canvas.cd(1) mg.Draw("ALP X+") gPad.SetTopMargin(0.0) leg.Draw("SAME") gPad.SetBottomMargin(0.0) canvas.cd(2) ratioMg.Draw("ALP") legRatio.Draw("SAME") if (directory != ""): canvas.Print("%s_Ratio.pdf" % (objName)) canvas.Print("%s_Ratio.png" % (objName)) canvas.Print("%s_Ratio.C" % (objName)) # for histograms, also draw a plot with each of them # separately? Useful if the fit functions are visible if (iObjType == 2): # TH1 primaryObj.Draw() # if (LogYMode): # canvas.SetLogy(1) primaryObj.GetYaxis().UnZoom() primaryObj.GetXaxis().SetLabelSize(AxisLabelSizeX) primaryObj.GetYaxis().SetLabelSize(AxisLabelSizeY) primaryObj.GetXaxis().SetTitleSize(kDefaultTitleSizeX) primaryObj.GetYaxis().SetTitleSize(kDefaultTitleSizeY) primaryObj.GetXaxis().SetTitleOffset(kDefaultTitleOffsetX) primaryObj.GetYaxis().SetTitleOffset(kDefaultTitleOffsetY) primaryObj.SetMarkerSize(kMarkerSize) fYMin = GetMinValue(primaryObj) fYMax = GetMaxValue(primaryObj) for lobj in listOfObjs: lobj.SetMarkerSize(kMarkerSize) lobj.Draw("SAME") fYMin = min(fYMin, GetMinValue(lobj)) fYMax = max(fYMax, GetMaxValue(lobj)) if (LogYMode != 0): (fYMin, fYMax) = ExpandRange(fYMin, fYMax) leg.Draw("SAME") primaryObj.GetYaxis().SetRangeUser(fYMin, fYMax) if (LogYMode == 1): canvas.SetLogy(1) primaryObj.GetYaxis().UnZoom() # FIXME temp # primaryObj.GetXaxis().SetRangeUser(0,25) # Draw a title tp = TPaveText(0.3, 0.91, 0.7, 0.99, "NDC") if (objectTitle == ""): tp.AddText(objName) else: tp.AddText(objectTitle) tp.Draw("SAME") if (directory != ""): canvas.Print("%s_Cmp.pdf" % (objName)) canvas.Print("%s_Cmp.png" % (objName)) canvas.Print("%s_Cmp.C" % (objName)) sysUncertObj = ProduceSystematicFromHists(listOfObjs) #sysUncertObj.SetName(objName) # This sets the name to be that of the original object sysUncertObj.SetName("%s_SysErr" % (objName)) # This adds the label SysErr totalUncertObj = ProduceTotalErrorHists(primaryObj, sysUncertObj) totalUncertObj.SetName(objName) #totalUncertObj.SetName("%s_TotalErr" % (objName)) sysUncertObj.SetFillColor(ROOT.kBlue) sysUncertObj.SetFillStyle(3002) #sysUncertObj.Draw("E2") sysUncertObj.Draw("E4") primaryObj.Draw("SAME") leg2.AddEntry(sysUncertObj, "Systematic Uncertainty", "F") leg2.Draw("SAME") if (directory != ""): canvas.Print("%s_SysUncert.pdf" % (objName)) canvas.Print("%s_SysUncert.png" % (objName)) outputFile.Add(sysUncertObj) outputFile.Add(totalUncertObj) if (bRatioMode): max_ratio_y = 1. min_ratio_y = 1. nBinsFirst = primaryObj.GetNbinsX() bDivisionPossible = False for hobj in listOfObjs: if (nBinsFirst == hobj.GetNbinsX()): bDivisionPossible = True if (bDivisionPossible): RatioArray = [] #canvas.Divide(1,2,canvSmall,canvSmall) #canvas.cd(1) #gPad.SetBottomMargin(small) #primaryObj.Draw() # Build the ratios. # Draw the thing for lobj in listOfObjs: lRatio = lobj.Clone("%s_Ratio" % (lobj.GetName())) if (bBinomialDivision): lRatio.Divide(lRatio, primaryObj, 1.0, 1.0, "B") else: lRatio.Divide(primaryObj) #lRatio.GetFunction(“myFunction”).SetBit(TF1::kNotDraw) localRatioMin = lRatio.GetBinContent( lRatio.GetMinimumBin()) localRatioMax = lRatio.GetBinContent( lRatio.GetMaximumBin()) if (localRatioMin < min_ratio_y): min_ratio_y = localRatioMin if (localRatioMax > max_ratio_y): max_ratio_y = localRatioMax RatioArray.append(lRatio) # magic adjustments to ratio min/max if (min_ratio_y != 0): if (max_ratio_y > 1. / min_ratio_y): min_ratio_y = 1. / max_ratio_y else: max_ratio_y = 1. / min_ratio_y if (max_ratio_y > 20.): max_ratio_y = 1.3 min_ratio_y = 1.0 / 1.3 #min_ratio_y = pow(min_ratio_y,1.6) #max_ratio_y = pow(max_ratio_y,1.6) legRatio = TLegend(legWidth, legHeight, legWidth, legHeight) RatioArray[0].Draw("HIST E") RatioArray[0].GetYaxis().SetRangeUser(min_ratio_y, max_ratio_y) for lRatio in RatioArray: lRatio.Draw("SAME HIST E") legRatio.AddEntry(lRatio, lRatio.GetTitle(), "LP") legRatio.Draw("SAME") if (directory != ""): canvas.Print("%s_Ratio.pdf" % (objName)) canvas.Print("%s_Ratio.png" % (objName)) canvas.Print("%s_Ratio.C" % (objName)) # primaryObj.Draw() # for lobj in listOfObjs: # lobj.Draw("SAME") # canvas.Print("Test.pdf") outputFile.Write()
def MakeCombined(myfile, color, fitInfo): info = myfile.split("_") curFile = TFile.Open(myfile,"read") if not myfile: print "No File found in MakeCombined" return # else: # curFile.Print() elasticHdata = curFile.Get("G0") elasticH = curFile.Get("G1") inelasticHdata = curFile.Get("G2") inelasticH = curFile.Get("G3") canvas = TCanvas('canvas','shouldnotseethis',0,0,1280,720) canvas.SetLogy() legend = TLegend(.75,.75,.9,.9) # title = "SFRESCO fit for initial parameters rC: {}, V_vol: {}, r_vol: {}, d_vol: {}, W_surf: {}, rW_surf: {}, aW_surf: {}".format(info[2],info[3],info[4],info[5],info[6],info[7],info[8][0:2]) title = "Final parameters rC: {}, V_vol: {}, r_vol: {}, d_vol: {}, W_surf: {}, rW_surf: {}, aW_surf: {}".format(fitInfo[1],fitInfo[2],fitInfo[3],fitInfo[4],fitInfo[5],fitInfo[6],fitInfo[7]) Dummy = ROOT.TH2F("Dummy","tmptitle",90,10,90,1000000,0,10000) Dummy.SetTitle(title) Dummy.GetXaxis().SetTitle("COM Angle in Degrees") Dummy.GetYaxis().SetTitle("Cross Section in mb/sr") Dummy.SetStats(ROOT.kFALSE) Dummy.Draw() Dummy.SetAxisRange(10,80,"X") Dummy.SetAxisRange(.0001,1000,"Y") graphOptions="sameP" # elasticColor = ROOT.kRed if elasticHdata: # elasticHdata.SetMarkerColor(color) # elasticHdata.SetLineColor(color) # elasticHdata.SetFillColor(color) elasticHdata.SetMarkerStyle(20) elasticHdata.Draw(graphOptions) legend.AddEntry(elasticHdata,"Elastic") else: print "No elasticH in Draw()" if elasticH: elasticH.SetMarkerColor(color) elasticH.SetLineColor(color) elasticH.SetFillColor(color) # elasticH.SetMarkerStyle(20) elasticH.SetLineWidth(5) elasticH.Draw("sameL") # inelasticColor = ROOT.kBlue # # if inelasticHdata: # inelasticHdata.SetMarkerColor(inelasticColor) # inelasticHdata.SetLineColor(inelasticColor) # inelasticHdata.SetFillColor(inelasticColor) # inelasticHdata.SetMarkerStyle(20) # legend.AddEntry(inelasticHdata,"Inelastic") # inelasticHdata.Draw(graphOptions) # # if inelasticH: # inelasticH.SetMarkerColor(inelasticColor) # inelasticH.SetLineColor(inelasticColor) # inelasticH.SetFillColor(inelasticColor) # #inelasticH.SetMarkerStyle(20) # inelasticH.Draw("sameL") legend.Draw() saveName = "outputs/special_{}_{}_{}_{}_{}_{}_{}.png".format(info[2],info[3],info[4],info[5],info[6],info[7],info[8][0:2]) canvas.SaveAs(saveName)
def DrawScatRatio(graph1, graph2, ratio, name1, name2, fname): #, grid): c = TCanvas("c", "c", 800, 800) # Upper histogram plot is pad1 p1 = TPad("p1", "p1", 0, 0.3, 1, 1.0) p1.SetBottomMargin(0) # joins upper and lower plot p1.Draw() # Lower ratio plot is pad 2 c.cd() # returns to main canvas before defining pad2 p2 = TPad("p2", "p2", 0, 0.05, 1, 0.3) p2.SetTopMargin(0) # joins upper and lower plot p2.SetBottomMargin(0.2) # p2.SetGridx() p2.Draw() # Now draw p1.cd() leg = TLegend(0.69, 0.89, 0.69, 0.89) leg.AddEntry(graph1, name1) leg.AddEntry(graph2, name2) leg.SetBorderSize(0) graph1.SetTitle("") graph1.GetXaxis().SetRangeUser(-1, 501) graph1.GetYaxis().SetTitle("Tracks passing quality cuts") # graph1.GetYaxis().SetTitleSize(20) # .04) graph1.GetYaxis().SetTitleOffset(1.25) graph1.GetYaxis().CenterTitle(1) graph1.SetMarkerStyle(20) # Full circle graph2.SetMarkerStyle(24) # Open circle graph1.Draw("AP") graph2.Draw("P SAME") leg.Draw("same") # to avoid clipping the bottom zero, redraw a small axis # ratio.GetYaxis().SetLabelSize(15) # SetLabelSize(.05) # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") # axis.SetLabelFont(43) # axis.SetLabelSize(15) p2.cd() # Sort out y-axis\ ratio.SetTitle("") # ;test;test") y2 = ratio.GetYaxis() y2.SetTitle("Ratio") y2.CenterTitle(1) y2.SetTitleOffset(1.75) y2.SetTitleSize(20) y2.SetTitleFont(43) y2.SetLabelFont(43) y2.SetLabelSize(15) y2.SetNdivisions(6) # Sort x-axis x2 = ratio.GetXaxis() x2.SetTitle("Lock low DCA threshold [#mum]") x2.CenterTitle(1) x2.SetTitleSize(20) #) x2.SetTitleFont(43) x2.SetRangeUser(-1, 501) x2.SetTitleOffset(3.5) x2.SetLabelFont(43) x2.SetLabelSize(15) ratio.SetLineColor(2) ratio.SetMarkerColor(2) ratio.SetMarkerStyle(24) ratio.Draw("AP") c.SaveAs(fname + ".pdf") c.SaveAs(fname + ".C") return
def plotDataMC(args, plot_mu, plot_el): hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) if args.ratio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() # Data load processes colors = createMyColors() if args.use2016: data = Process(Data2016, normalized=True) elif args.use2018: data = Process(Data2018, normalized=True) else: data = Process(Data, normalized=True) eventCounts_mu = totalNumberOfGeneratedEvents(path, plot_mu.muon) eventCounts_el = totalNumberOfGeneratedEvents(path, plot_el.muon) negWeights_mu = negWeightFractions(path, plot_mu.muon) negWeights_el = negWeightFractions(path, plot_el.muon) #print negWeights # Background load processes backgrounds = copy(args.backgrounds) '''if plot_mu.useJets: if "Wjets" in backgrounds: backgrounds.remove("Wjets") backgrounds.insert(0,"Jets")''' processes_mu = [] processes_el = [] for background in backgrounds: if args.use2016: if background == "Jets": processes_mu.append( Process(getattr(Backgrounds2016, background), eventCounts_mu, negWeights_mu, normalized=True)) processes_el.append( Process(getattr(Backgrounds2016, background), eventCounts_el, negWeights_el, normalized=True)) else: processes_mu.append( Process(getattr(Backgrounds2016, background), eventCounts_mu, negWeights_mu)) processes_el.append( Process(getattr(Backgrounds2016, background), eventCounts_el, negWeights_el)) else: if background == "Jets": processes_mu.append( Process(getattr(Backgrounds, background), eventCounts_mu, negWeights_mu, normalized=True)) processes_el.append( Process(getattr(Backgrounds, background), eventCounts_el, negWeights_el, normalized=True)) else: processes_mu.append( Process(getattr(Backgrounds, background), eventCounts_mu, negWeights_mu)) processes_el.append( Process(getattr(Backgrounds, background), eventCounts_el, negWeights_el)) '''# Signal load processes signals = [] for signal in args.signals: if args.use2016: if args.ADD: signals.append(Process(getattr(Signals2016ADD, signal), eventCounts, negWeights)) else: signals.append(Process(getattr(Signals2016,signal),eventCounts,negWeights)) else: if args.ADD: signals.append(Process(getattr(SignalsADD, signal), eventCounts, negWeights)) else: signals.append(Process(getattr(Signals,signal),eventCounts,negWeights)) ''' legend = TLegend(0.55, 0.75, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) '''legendEta = TLegend(0.35, 0.55, 0.9, 0.9) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) legendEta.SetNColumns(2) ''' latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] # Modify legend information legendHistData = ROOT.TH1F() if args.data: legend.AddEntry(legendHistData, "Data", "pe") legendEta.AddEntry(legendHistData, "Data", "pe") for process in reversed(processes_mu): if not plot_mu.muon and "#mu^{+}#mu^{-}" in process.label: process.label = process.label.replace("#mu^{+}#mu^{-}", "e^{+}e^{-}") process.theColor = ROOT.kBlue process.theLineColor = ROOT.kBlue temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") #legendEta.AddEntry(temphist,process.label,"f") for process in reversed(processes_el): if not plot_el.muon and "#mu^{+}#mu^{-}" in process.label: process.label = process.label.replace("#mu^{+}#mu^{-}", "e^{+}e^{-}") process.theColor = ROOT.kRed process.theLineColor = ROOT.kRed temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") #legendEta.AddEntry(temphist,process.label,"f") '''if args.signals !=0: processesWithSignal = [] for process in processes: processesWithSignal.append(process) for Signal in signals: processesWithSignal.append(Signal) temphist = ROOT.TH1F() temphist.SetFillColor(Signal.theColor) temphist.SetLineColor(Signal.theLineColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist,Signal.label,"l") legendEta.AddEntry(temphist,Signal.label,"l") ''' # Modify plot pad information nEvents = -1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() # Luminosity information plotPad.cd() plotPad.SetLogy(0) logScale = plot_mu.log if logScale == True: plotPad.SetLogy() if args.use2016: lumi_el = 35.9 * 1000 lumi_mu = 36.3 * 1000 elif args.use2018: lumi_el = 59.97 * 1000 lumi_mu = 61.608 * 1000 else: lumi_el = 41.529 * 1000 lumi_mu = 42.135 * 1000 if args.use2016: zScaleFac_mu = zScale2016["muons"] zScaleFac_el = zScale2016["electrons"] elif args.use2018: zScaleFac_mu = zScale2018["muons"] zScaleFac_el = zScale2018["electrons"] else: zScaleFac_mu = zScale["muons"] zScaleFac_el = zScale["electrons"] # Data and background loading '''if plot.plot2D: datahist = data.loadHistogramProjected(plot,lumi,zScaleFac) stack = TheStack2D(processes,lumi,plot,zScaleFac) else: datahist = data.loadHistogram(plot,lumi,zScaleFac) stack = TheStack(processes,lumi,plot,zScaleFac) ''' lumi_mu = 1.0 * 1000 lumi_el = 1.0 * 1000 datahist = data.loadHistogram(plot_mu, lumi_mu, zScaleFac_mu) stackmu = TheStack(processes_mu, lumi_mu, plot_mu, zScaleFac_mu) stackel = TheStack(processes_el, lumi_el, plot_el, zScaleFac_el) # call hist in stack by: for h in stackmu.theStack.GetHists() #muheight = stackmu.theHistogram.FindBin(90) #print "Z height in mu: %.3f, %.3f"%(stackmu.theHistogram.GetBinContent(muheight), stackel.theHistogram.GetBinContent(muheight)) if args.znorm: muheight = stackmu.theHistogram.FindBin(90) print "Z height of mu: %d +- %d" % (stackmu.theHistogram.GetBinCenter( muheight), stackmu.theHistogram.GetBinWidth(muheight)) print "Z height of mu: %d" % ( stackmu.theHistogram.GetBinContent(muheight)) elheight = stackel.theHistogram.FindBin(90) print "Z height of el: %d +- %d" % (stackel.theHistogram.GetBinCenter( elheight), stackel.theHistogram.GetBinWidth(elheight)) print "Z height of el: %d" % ( stackel.theHistogram.GetBinContent(elheight)) znum = stackmu.theHistogram.GetBinContent(muheight) print znum for h in stackmu.theStack.GetHists(): h.Scale(1. / znum) for h in stackel.theStack.GetHists(): h.Scale(1. / znum) stackmu.theHistogram.Scale(1. / znum) stackel.theHistogram.Scale(1. / znum) if args.ae: year = 2017 if args.use2018: year = 2018 for h in stackmu.theStack.GetHists(): inverseAE(h, plot_mu, year) for h in stackel.theStack.GetHists(): inverseAE(h, plot_el, year) inverseAE(stackmu.theHistogram, plot_mu, year) inverseAE(stackel.theHistogram, plot_el, year) if args.data: yMax = datahist.GetBinContent(datahist.GetMaximumBin()) if "Mass" in plot.fileName: yMin = 0.00001 else: yMin = 0.01 xMax = datahist.GetXaxis().GetXmax() xMin = datahist.GetXaxis().GetXmin() else: yMax = stackmu.theHistogram.GetBinContent(datahist.GetMaximumBin()) yMin = 0.01 xMax = stackmu.theHistogram.GetXaxis().GetXmax() xMin = stackmu.theHistogram.GetXaxis().GetXmin() if plot_mu.yMax == None: if logScale: yMax = yMax * 10000 else: yMax = yMax * 1.5 else: yMax = plot_mu.yMax if "Mass" in plot_mu.fileName: yMax = 20000000 if not plot_mu.yMin == None: yMin = plot_mu.yMin if not plot_mu.xMin == None: xMin = plot_mu.xMin if not plot_mu.xMax == None: xMax = plot_mu.xMax #if args.ADD and args.use2016: # xMin = 1700 # xMax = 4000 # yMax = 1.0 #if "CosThetaStarBBM1800" in plot.fileName: # yMax = 3 #print xMin, xMax, yMin, yMax '''xMin = 70 xMax = 4000 yMin = 0.00001 yMax = 20000000''' yMin = 0.00001 / 40 yMax = 200000000.0 / 40 if args.ae: xMin = 200 if args.znorm: yMin /= 300 yMax /= 300 plotPad.DrawFrame( xMin, yMin, xMax, yMax, "; %s ; %s" % ("m(l^{+}l^{-}) [GeV]", "d#sigma(pp#rightarrow ll)")) drawStack_mu = stackmu drawStack_el = stackel #~ print datahist.Integral(datahist.FindBin(60),datahist.FindBin(120))/drawStack.theHistogram.Integral(drawStack.theHistogram.FindBin(60),drawStack.theHistogram.FindBin(120)) #~ low = 900 #~ high = 1300 #~ print datahist.Integral(datahist.FindBin(low),datahist.FindBin(high)) #~ print drawStack.theHistogram.Integral(datahist.FindBin(low),datahist.FindBin(high)) # Draw background from stack drawStack_mu.theStack.Draw("same hist") drawStack_el.theStack.Draw("same hist") '''# Draw signal information if len(args.signals) != 0: signalhists = [] for Signal in signals: if plot.plot2D: # plot collins-soper angle signalhist = Signal.loadHistogramProjected(plot,lumi, zScaleFac) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove("DrellYan") signalProcesses = [] for background in signalBackgrounds: if background == "Jets": signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights,normalized=True)) else: signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights)) signalStack = TheStack2D(signalProcesses,lumi,plot, zScaleFac) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.1) signalhist.Draw("samehist") signalhists.append(signalhist) else: signalhist = Signal.loadHistogram(plot,lumi,zScaleFac) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove("DrellYan") # signalBackgrounds = ["Jets", "Other"] signalProcesses = [] for background in signalBackgrounds: if background == "Jets": signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights,normalized=True)) else: signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights)) signalStack = TheStack(signalProcesses,lumi,plot,zScaleFac) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.0001) signalhist.Draw("samehist") signalhists.append(signalhist) ''' # Draw data datahist.SetMinimum(0.0001) #if args.data: # datahist.Draw("samep") # Draw legend if "Eta" in plot_mu.fileName or "CosTheta" in plot_mu.fileName: legendEta.Draw() else: legend.Draw() plotPad.SetLogx(plot_mu.logX) latex.DrawLatex( 0.95, 0.96, "%.3f fb^{-1} (13 TeV, #mu#mu), %.3f fb^{-1} (13 TeV, ee)" % (lumi_mu * 0.001, lumi_el * 0.001)) yLabelPos = 0.85 cmsExtra = "Private Work" if not args.data: cmsExtra = "#splitline{Private Work}{Simulation}" yLabelPos = 0.82 latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) #~ print datahist.Integral() if args.ratio: try: ratioPad.cd() ratioPad.SetLogx(plot_mu.logX) except AttributeError: print("Plot fails. Look up in errs/failedPlots.txt") outFile = open("errs/failedPlots.txt", "a") outFile.write('%s\n' % plot_mu.filename % ("_" + run.label + "_" + dilepton)) outFile.close() plot_mu.cuts = baseCut return 1 #ratioGraphs = ratios.RatioGraph(drawStack_mu.theStack.GetHists()[0], drawStack_el.theStack.GetHists()[0], xMin=xMin, xMax=xMax,title="R_{#mu#mu/ee}",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000) #setRatioError(ratioGraphs, drawStack_mu.theHistogram, drawStack_el.theHistogram) #ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) hhmu = drawStack_mu.theHistogram hhel = drawStack_el.theHistogram ratioGraphs = ROOT.TGraphAsymmErrors(hhmu.GetSize() - 2) chann = True if "BB" in plot_mu.fileName else False for i in range(1, hhmu.GetSize() - 1): xval = hhmu.GetBinCenter(i) xerr = hhmu.GetBinWidth(i) / 2 if hhel.GetBinContent(i) == 0: continue if hhel.GetBinContent(i) < 0 or hhmu.GetBinContent(i) < 0: continue yval = hhmu.GetBinContent(i) * 1.0 / hhel.GetBinContent(i) #if yval > 10: continue yerr = yval * math.sqrt( getMuErr(xval, chann, args.znorm)**2 + getElErr(xval, chann, args.znorm)**2) ratioGraphs.SetPoint(i, xval, yval) ratioGraphs.SetPointError(i, xerr, xerr, yerr, yerr) nBinsX = 20 nBinsY = 10 hAxis = ROOT.TH2F("hAxis", "", nBinsX, xMin, xMax, nBinsY, 0.0, 4.0) hAxis.Draw("AXIS") hAxis.GetYaxis().SetNdivisions(408) hAxis.SetTitleOffset(0.4, "Y") hAxis.SetTitleSize(0.15, "Y") hAxis.SetYTitle("R_{#mu#mu/ee}") hAxis.GetXaxis().SetLabelSize(0.0) hAxis.GetYaxis().SetLabelSize(0.15) hAxis.SetTitleSize(0.15, "Y") #binMerging = [-1] oneLine = ROOT.TLine(xMin, 1.0, xMax, 1.0) oneLine.SetLineStyle(2) oneLine.Draw() ratioGraphs.SetFillColor(6) ratioGraphs.SetFillStyle(3002) #ratioGraphs.Draw("SAMEpZ4") ratioGraphs.Draw("same p") ratioPad.Update() ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if args.ratio: ratioPad.RedrawAxis() if not os.path.exists("lepFlavor"): os.makedirs("lepFlavor") if args.use2016: year = "2016" elif args.use2018: year = "2018" else: year = "2017" if args.ae: year += "_inverseAE" if args.znorm: year += "_znorm" hCanvas.Print("lepFlavor/%s_%s_other.pdf" % (plot_mu.fileName, year))
f_l2.SetMaximum(max_y+a) f_l3.SetMaximum(max_y+a) f_l4.SetMaximum(max_y+a) f_l1.Draw("lsame") f_l2.Draw("lsame") f_l3.Draw("lsame") f_l4.Draw("lsame") lb.SetNDC(kTRUE) lb.SetTextSize(0.025) lb.SetTextAlign(13) lb.DrawLatex(0.5, 0.55, "MP L1 = "+str(MP_l1)+"#pm"+str(MPe_l1)) lb.DrawLatex(0.5, 0.50, "MP L2 = "+str(MP_l2)+"#pm"+str(MPe_l2)) lb.DrawLatex(0.5, 0.45, "MP L3 = "+str(MP_l3)+"#pm"+str(MPe_l3)) lb.DrawLatex(0.5, 0.40, "MP L4 = "+str(MP_l4)+"#pm"+str(MPe_l4)) leg.Draw() gPad.RedrawAxis() c.SaveAs(plotdir+"barrel_summary_"+var+"_"+fill"_.pdf")) #c.Update() #c.Clear() c2 = TCanvas('c2', 'c2', 800, 640) leg2 = TLegend(0.60,0.90,0.90, 0.70) leg2.SetBorderSize(0) leg2.SetFillColor(10) leg2.SetLineColor(10) leg2.SetLineWidth(0) if var == "norm_charge": f_d1 = fitting(h_d1)
def plotFailedHoMatchesNoTrg(): c = TCanvas("cFailedHoMatchesNoTrg", "cFailedHoMatchesNoTrg", 1200, 1200) c.cd().SetRightMargin(0.25) c.cd().SetLeftMargin(0.08) #legend legend = TLegend(0.75, 0.8, 0.99, 0.9) #Graph for in events not in geometric acceptance grNotInGaNC = file.Get("hoMuonAnalyzer/graphs/NoTrgTdmiNotInGA") grNotInGa = PlotStyle.convertToHcalCoords(grNotInGaNC) grNotInGa.GetYaxis().SetTitle("i#phi / a.u.") grNotInGa.GetXaxis().SetTitle("i#eta / a.u.") grNotInGa.GetYaxis().SetTitleFont(62) grNotInGa.GetYaxis().SetLabelFont(62) grNotInGa.SetMarkerStyle(6) grNotInGa.SetMarkerColor(PlotStyle.colorRwthDarkBlue) grNotInGa.SetTitle( "#eta #phi plot failed HO matches in no Single #mu Trg. events") grNotInGa.Draw("AP") #Graph of events with HO match below threshold grHoBelowThrNC = file.Get("hoMuonAnalyzer/graphs/NoTrgTdmiBelowThr") grHoBelowThr = PlotStyle.convertToHcalCoords(grHoBelowThrNC) grHoBelowThr.SetMarkerStyle(20) grHoBelowThr.SetMarkerSize(1.2) grHoBelowThr.SetMarkerColor(PlotStyle.colorRwthGruen) grHoBelowThr.Draw("samep") #Graph for events where HO matching failed grHoMatchFailNC = file.Get("hoMuonAnalyzer/graphs/NoTrgHoMatchFail") grHoMatchFail = None nNotMatching = 0 if not grHoMatchFailNC == None: grHoMatchFail = PlotStyle.convertToHcalCoords(grHoMatchFailNC) grHoMatchFail.SetMarkerStyle(21) grHoMatchFail.SetMarkerSize(1) grHoMatchFail.SetMarkerColor(PlotStyle.colorRwthRot) grHoMatchFail.Draw("samep") legend.AddEntry(grHoMatchFail, 'HO match fail', 'p') nNotMatching = grHoMatchFail.GetN() #Draw chimneys chimney1Converted = PlotStyle.convertToHcalCoords(PlotStyle.chimney1) chimney2Converted = PlotStyle.convertToHcalCoords(PlotStyle.chimney2) chimney1Converted.SetLineColor(PlotStyle.colorRwthMagenta) chimney2Converted.SetLineColor(PlotStyle.colorRwthMagenta) chimney1Converted.Draw('same') chimney2Converted.Draw('same') #cms private label label = TPaveText( PlotStyle.getLabelCmsPrivateSimulation(x1ndc=0.5, x2ndc=0.75)) label.Draw() #create extra marker for the legend marker = TMarker(1, 1, 2) marker.SetMarkerSize(3) marker.SetMarkerColor(PlotStyle.colorRwthDarkBlue) legend.AddEntry(chimney2Converted, "chimney", "l") legend.AddEntry(marker, 'Not in GA', 'p') legend.AddEntry(grHoBelowThr, 'HO match < 0.2 GeV', 'p') legend.Draw() nNotInGa = grNotInGa.GetN() nBelowThr = grHoBelowThr.GetN() nTotal = nNotMatching + nNotInGa + nBelowThr print 80 * '#' print 'Not Matching:\t%5d/%d\t=> %5.2f%% +- %f%%' % ( nNotMatching, nTotal, nNotMatching / float(nTotal) * 100, PlotStyle.calcSigma(nNotMatching, float(nTotal))) print 'Not in GA:\t%5d/%d\t=> %5.2f%% +- %f%%' % ( nNotInGa, nTotal, nNotInGa / float(nTotal) * 100, PlotStyle.calcSigma(nNotInGa, float(nTotal))) print 'Below Thr:\t%5d/%d\t=> %5.2f%% +- %f%%' % ( nBelowThr, nTotal, nBelowThr / float(nTotal) * 100, PlotStyle.calcSigma(nBelowThr, float(nTotal))) print 80 * '#' c.Update() c.SaveAs('plots/graphsEtaPhi/gNoTrgHoMatchingFailed.png') c.SaveAs('plots/graphsEtaPhi/gNoTrgHoMatchingFailed.pdf') return c, grNotInGa, label, chimney1Converted, chimney2Converted, legend, grHoMatchFail, grHoBelowThr
#Drawing the graphs c2=TCanvas() c2.Divide(2,2,.01,.01,0) c2.cd(1) l2=TLegend(.3,.2) l2.AddEntry(g2,"Uncorrected","l") l2.AddEntry(b2,"Background","l") l2.AddEntry(cor2,"Corrected by Event","l") g2.ProfileX().Draw() b2.SetLineColor(2) b2.ProfileX().Draw("same") cor2.SetLineColor(3) cor2.ProfileX().Draw("same") l2.Draw("same") c2.cd(2) l3=TLegend(.3,.2) l3.AddEntry(g3,"Uncorrected","l") l3.AddEntry(b3,"Background","l") l3.AddEntry(cor3,"Corrected by Event","l") g3.ProfileX().Draw() b3.SetLineColor(2) b3.ProfileX().Draw("same") cor3.SetLineColor(3) cor3.ProfileX().Draw("same") l3.Draw("same") c2.cd(3) l4=TLegend(.3,.2)
legEff.AddEntry(hEffPrompt[5], 'FONLL #times MC@sHQ-EPOS2', 'p') lineatone = TLine(0., 1., 36., 1.) lineatone.SetLineWidth(2) lineatone.SetLineStyle(9) lineatone.SetLineColor(kBlack) cShapes = TCanvas('cShapes', '', 1000, 500) cShapes.Divide(2, 1) cShapes.cd(1).DrawFrame(0, 1.e-8, 36, 1., ';#it{p}_{T} GeV/#it{c}; d#it{N}/d#it{p}_{T} (a. u.)') cShapes.cd(1).SetLogy() for iShape, _ in enumerate(hPtShapes): hPtShapes[iShape].SetLineWidth(2) hPtShapes[iShape].SetLineColor(colors[iShape]) hPtShapes[iShape].Draw('chistsame') leg.Draw() cShapes.cd(2).DrawFrame(0, 1.e-3, 36, 1.e+1, ';#it{p}_{T} GeV/#it{c}; #it{p}_{T} weights') cShapes.cd(2).SetLogy() lineatone.Draw('same') for iShape, _ in enumerate(hPtWeights): hPtWeights[iShape].Draw('chistsame') hPtWeights[iShape].SetLineWidth(2) hPtWeights[iShape].SetLineColor(colors[iShape+1]) cShapes.SaveAs(outFilePtWeightsName) if inFileEffNames and len(inFileEffNames) == len(PtShapes): ptmin = hEffPrompt[0].GetBinLowEdge(1) ptmax = hEffPrompt[0].GetBinLowEdge(hEffPrompt[0].GetNbinsX( ))+hEffPrompt[0].GetBinWidth(hEffPrompt[0].GetNbinsX()) cEff = TCanvas('cEff', '', 1000, 500)
def plot(path, leg_title, ecms, xmin, xmax, xbins): try: f_data = TFile(path[0]) t_data = f_data.Get('save') entries_data = t_data.GetEntries() logging.info('data entries :' + str(entries_data)) except: logging.error(path[0] + 'is invalid!') sys.exit() try: f_side1 = TFile(path[1]) t_side1 = f_side1.Get('save') entries_side1 = t_side1.GetEntries() logging.info('data(side1) entries :' + str(entries_side1)) except: logging.error(path[1] + ' is invalid!') sys.exit() try: f_side2 = TFile(path[2]) t_side2 = f_side2.Get('save') entries_side2 = t_side2.GetEntries() logging.info('data(side2) entries :' + str(entries_side2)) except: logging.error(path[2] + ' is invalid!') sys.exit() try: f_side3 = TFile(path[3]) t_side3 = f_side3.Get('save') entries_side3 = t_side3.GetEntries() logging.info('data(side3) entries :' + str(entries_side3)) except: logging.error(path[3] + ' is invalid!') sys.exit() try: f_side4 = TFile(path[4]) t_side4 = f_side4.Get('save') entries_side4 = t_side4.GetEntries() logging.info('data(side4) entries :' + str(entries_side4)) except: logging.error(path[4] + ' is invalid!') sys.exit() mbc = TCanvas('mbc', 'mbc', 800, 600) set_canvas_style(mbc) content = int((xmax - xmin) / xbins * 1000) ytitle = 'Entries/%.1f MeV' % content xtitle = 'RM(#pi^{+}_{0}#pi^{-}_{0})(GeV)' h_data = TH1F('data', 'data', xbins, xmin, xmax) set_histo_style(h_data, xtitle, ytitle, 1, -1) rm_pipi_fill(t_data, h_data) h_side1 = TH1F('side1', 'side1', xbins, xmin, xmax) set_histo_style(h_side1, xtitle, ytitle, 3, 3004) rm_pipi_fill(t_side1, h_side1) h_side2 = TH1F('side2', 'side2', xbins, xmin, xmax) set_histo_style(h_side2, xtitle, ytitle, 3, 3004) rm_pipi_fill(t_side2, h_side2) h_side3 = TH1F('side3', 'side3', xbins, xmin, xmax) set_histo_style(h_side3, xtitle, ytitle, 3, 3004) rm_pipi_fill(t_side3, h_side3) h_side4 = TH1F('side4', 'side4', xbins, xmin, xmax) set_histo_style(h_side4, xtitle, ytitle, 3, 3004) rm_pipi_fill(t_side4, h_side4) h_side1.Add(h_side2) h_side1.Scale(0.5) h_side3.Add(h_side4) h_side3.Scale(0.35) h_side1.Add(h_side3, -1) h_data.Draw('E1') hs = THStack('hs', 'Stacked') hs.Add(h_side1) hs.Draw('same') h_data.Draw('sameE1') legend = TLegend(0.55, 0.65, 0.8, 0.85) set_legend(legend, h_data, h_side1, leg_title) legend.Draw() if not os.path.exists('./figs/'): os.makedirs('./figs/') mbc.SaveAs('./figs/rm_pipi_' + str(ecms) + '.pdf') raw_input('Enter anything to end...')
def MCSPlot(self, pname): #print self.fname f = TFile(self.fname) self.RMS = {} self.RMSErr = {} self.Chi2 = {} self.RMSsysdiff = {} self.RMSsyserr = {} # create a plot for each histvarname for histvar in self.histvarnames: self.RMS[histvar] = {} self.RMSErr[histvar] = {} self.RMSsysdiff[histvar] = {} self.RMSsyserr[histvar] = {} self.Chi2[histvar] = {} names = [histvar + '_' + x for x in self.histstatenames] print names hists = [f.Get(histvar + '_' + x) for x in self.histstatenames] print hists[0] hists[0].SetTitle("") # hists[3].Scale(norm) # self.formatHist(hist[0], 0) resplots = [x.Clone() for x in hists] resplots[0].SetTitle('') resplots[0].GetYaxis().SetTitle("Normalized Residuals") # if histvar == 'thetaScatt': leg = TLegend(0.55, 0.73, 0.89, 0.92) leg.SetLineColor(10) # else: # leg = TLegend(0.35,0.2,0.65,0.5) for i in range(len(self.histstatedesc)): hists[i].Sumw2() if histvar == 'theta2Scatt': hists[i].Rebin(8) resplots[i].Rebin(8) elif histvar == 'thetaScatt': hists[i].Rebin(1) resplots[i].Rebin(1) else: hists[i].Rebin(1) resplots[i].Rebin(1) self.formatHists(hists[i], i) self.formatHists(resplots[i], i) self.addToRMS(i, hists[i], hists[0], resplots[i], histvar) if histvar == 'theta2Scatt': hists[i].GetYaxis().SetTitle('Probability per ' + str( round(1000 * 1000 * hists[i].GetXaxis().GetBinWidth(4), 2)) + ' mrad^{2}') else: hists[i].GetYaxis().SetTitle('Probability per ' + str( round(1000 * hists[i].GetXaxis().GetBinWidth(4), 2)) + ' mrad') leg.AddEntry(hists[i], self.histstatedesc[i], self.histopts[i]) #print hists[0] self.calculateChi2(i, hists[i], hists[0], resplots[i], histvar, pname) c = TCanvas(self.fname[:-5] + '_' + histvar + '_c1') if self.desc[0] == 'XePion': t1 = TText(0.18, 0.885, "MICE ISIS cycle 2015/03") t2 = TText(0.18, 0.85, "Xe, " + self.desc[1][2:5] + ", MAUS v3.1.2") else: t1 = TText(0.18, 0.885, "MICE ISIS cycle 2015/04") t2 = TText(0.18, 0.85, "LiH, " + self.desc[1][2:5] + ", MAUS v3.1.2") t1.SetNDC(1) t1.SetTextSize(0.04) t1.SetTextFont(42) t2.SetNDC(1) t2.SetTextSize(0.03) t2.SetTextFont(42) hists[0].GetYaxis().SetRangeUser(4e-4, 2.0) hists[0].SetTitle(";" + hists[0].GetXaxis().GetTitle() + " (radians);" + hists[0].GetYaxis().GetTitle()) hists[0].Draw('ep') c.SetBottomMargin(0.15) c.SetTopMargin(0.075) for h in hists[1:len(self.histstatedesc)]: h.Draw('epsame') leg.SetTextSize(0.04) leg.Draw('same') t1.Draw() t2.Draw() c.SetLogy() c.SaveAs(pname + '_' + self.fname[:-5] + '_' + histvar + '_sys.eps') c.SaveAs(pname + '_' + self.fname[:-5] + '_' + histvar + '_sys.root') c.SaveAs(pname + '_' + self.fname[:-5] + '_' + histvar + '_sys_pq.jpg') c.Clear() c.SetLogy(0) resplots[0].GetYaxis().SetRangeUser(-2, 2) resplots[0].SetTitle(";" + resplots[0].GetXaxis().GetTitle() + " (radians);" + resplots[0].GetYaxis().GetTitle()) leg.SetX1NDC(0.5) leg.SetX2NDC(0.89) leg.SetY1NDC(0.2) leg.SetY2NDC(0.4) resplots[0].Draw("p") for r in resplots: r.Draw('psame') leg.SetTextSize(0.04) leg.Draw('same') t1.Draw() t2.Draw() # pblock.Draw() c.SaveAs(pname + '_' + self.fname[:-5] + '_' + histvar + '_sys_res_T.eps') c.SaveAs(pname + '_' + self.fname[:-5] + '_' + histvar + '_sys_res_pq.jpg') momhist = f.Get("cor_mom") #mom = [momhist.GetMean() + 19.468, momhist.GetMeanError()] #if self.fname.find("LiHMuon_03172") >= 0: # mom = [momhist.GetMean()*1.107 + 1.05, momhist.GetMeanError()] #elif self.fname.find("LiHMuon_03200") >= 0: # mom = [momhist.GetMean()*1.104 + 1.139, momhist.GetMeanError()] #elif self.fname.find("LiHMuon_03240") >= 0: # mom = [momhist.GetMean()*1.17 - 9.41, momhist.GetMeanError()] if self.fname.find("LiHMuon_03172") >= 0: mom = [momhist.GetMean(), momhist.GetMeanError()] elif self.fname.find("LiHMuon_03200") >= 0: mom = [momhist.GetMean(), momhist.GetMeanError()] elif self.fname.find("LiHMuon_03240") >= 0: mom = [momhist.GetMean(), momhist.GetMeanError()] rms = [momhist.GetRMS(), momhist.GetRMSError()] summary = [] syssummary = [] def sigfig(x): if math.fabs(x) > 1e-5: return int(math.ceil(math.fabs(math.log(math.fabs(x), 10)))) else: return 1 # syssummary.append("p (MeV/c) & "+self.histvarnames[0]+"&"+self.histvarnames[1]+"&"+self.histvarnames[3]+"\\\\") if pname != "Truth": for sys in self.sysFiles: # if sys[3] == 'Material': stindx = 1 # else: stindx = 0 # print sys[3], self.histstatenames[stindx] difference0 = self.RMSsysdiff[self.histvarnames[0]][ self.histstatenames[stindx]][sys[3]] difference1 = self.RMSsysdiff[self.histvarnames[1]][ self.histstatenames[stindx]][sys[3]] difference3 = self.RMSsysdiff[self.histvarnames[3]][ self.histstatenames[stindx]][sys[3]] syserr0 = self.RMSsyserr[self.histvarnames[0]][ self.histstatenames[stindx]][sys[3]] syserr1 = self.RMSsyserr[self.histvarnames[1]][ self.histstatenames[stindx]][sys[3]] syserr3 = self.RMSsyserr[self.histvarnames[3]][ self.histstatenames[stindx]][sys[3]] relerr0 = syserr0 / self.RMS[self.histvarnames[0]][ self.histstatenames[0]] relerr1 = syserr1 / self.RMS[self.histvarnames[1]][ self.histstatenames[0]] relerr3 = syserr3 / self.RMS[self.histvarnames[3]][ self.histstatenames[0]] syssummary.append(str(round(mom[0],sigfig(mom[1])))+"$\pm$"+str(round(mom[1],sigfig(mom[1])))+\ " & "+str(round(difference0,sigfig(difference0)))+\ " & "+str(round(syserr0,sigfig(syserr0)))+\ " & "+str(round(relerr0,sigfig(relerr0)))+\ " & "+str(round(difference1,sigfig(difference1)))+\ " & "+str(round(syserr1,sigfig(syserr1)))+\ " & "+str(round(relerr1,sigfig(relerr1)))+\ " & "+str(round(difference3,sigfig(difference3)))+\ " & "+str(round(syserr3,sigfig(syserr3)))+\ " & "+str(round(relerr3,sigfig(relerr3)))+"\\\\") # print syssummary[-1] syssummary.append(str(round(mom[0],2))+"$\pm$"+str(round(mom[1],2))+\ " & "+ str(round(rms[0],2))+"$\pm$"+str(round(rms[1],2))+\ " & "+str(round(self.RMSsysdiff[self.histvarnames[0]][self.histstatenames[0]]['Sum'],2))+\ " & "+str(round(self.RMSsyserr[self.histvarnames[0]][self.histstatenames[0]]['Sum'],2))+\ " & "+str(round(self.RMSsyserr[self.histvarnames[0]][self.histstatenames[0]]['Sum']/self.RMS[self.histvarnames[0]][self.histstatenames[0]],2))+\ " & "+str(round(self.RMSsysdiff[self.histvarnames[1]][self.histstatenames[0]]['Sum'],2))+\ " & "+str(round(self.RMSsyserr[self.histvarnames[1]][self.histstatenames[0]]['Sum'],2))+\ " & "+str(round(self.RMSsyserr[self.histvarnames[1]][self.histstatenames[0]]['Sum']/self.RMS[self.histvarnames[1]][self.histstatenames[0]],2))+\ " & "+str(round(self.RMSsysdiff[self.histvarnames[3]][self.histstatenames[0]]['Sum'],2))+ " & "+str(round(self.RMSsyserr[self.histvarnames[3]][self.histstatenames[0]]['Sum'],2))+ " & "+str(round(self.RMSsyserr[self.histvarnames[3]][self.histstatenames[0]]['Sum']/self.RMS[self.histvarnames[2]][self.histstatenames[0]],2))+"\\\\") # summary.append("p (MeV/c) & &"+str(self.histstatenames[0])+" & "+str(self.histstatenames[1])+" & $\chi^{2}$/ndf & "+ # +str(self.histstatenames[2])+" & $\chi^{2}$/ndf \\\\") # print mom, self.RMS, self.RMSErr, self.Chi2 for histvar in self.histvarnames: summary.append(str(round(mom[0],2))+"$\pm$"+str(round(mom[1],2))+\ "& $\ "+histvar+"$ & "+str(round(self.RMS[histvar][self.histstatenames[0]],2))+ \ "$\pm$"+str(round(self.RMSErr[histvar][self.histstatenames[0]],2))+ \ "$\pm$"+str(round(self.RMSsyserr[histvar][self.histstatenames[0]]["Sum"],2))+ \ " & "+str(round(self.RMS[histvar][self.histstatenames[1]],2))+ \ "$\pm$"+str(round(self.RMSErr[histvar][self.histstatenames[1]],2))+ \ # "$\pm$"+str(round(self.RMSsyserr[histvar][self.histstatenames[1]]["Sum"],2))+\ " & "+str(round(self.Chi2[histvar][self.histstatenames[1]][0],1))+ \ " / "+ str(self.Chi2[histvar][self.histstatenames[1]][1])+ \ " & "+str(round(self.RMS[histvar][self.histstatenames[2]],2))+ \ "$\pm$"+str(round(self.RMSErr[histvar][self.histstatenames[2]],2))+ \ #"$\pm$"+str(round(self.RMSsyserr[histvar][self.histstatenames[2]]["Sum"],2))+\ " & "+str(round(self.Chi2[histvar][self.histstatenames[2]][0],1))+ \ " / "+ str(self.Chi2[histvar][self.histstatenames[2]][1]) +"\\\\") # print summary[-1] f.Close() return [summary, syssummary]
def __plot_profiles_in_same_canvas(self, hist_objs, hist_names, legends, y_limits, **kwargs): legend_position = retrieve_kw(kwargs, 'legend_position', (0.36, 0.20, 0.66, 0.36)) legend_prefix = retrieve_kw(kwargs, 'legend_prefix', 'Z#rightarrowee, ') legend_header = retrieve_kw(kwargs, 'legend_header', 'Trigger step') ylabel = retrieve_kw(kwargs, 'ylabel', 'Trigger Efficiency') title = retrieve_kw(kwargs, 'title', 'Trigger Efficiency') oname = retrieve_kw(kwargs, 'oname', 'plot_efficiencys') column = retrieve_kw(kwargs, 'column', 2) doRatio = retrieve_kw(kwargs, 'doRatio', False) canvas_size = retrieve_kw(kwargs, 'canvas_size', (1800, 1500)) # FIXME: This must be disable for now, there is some problem into the xaxis scale # The top and bot axis must be match! tobject_collector = [] ratio_size_as_fraction = 0.35 from ROOT import TCanvas, TLegend, TProfile, TPad rows = int(round(len(hist_objs) / float(column))) canvas = TCanvas('canvas', 'canvas', canvas_size[0], canvas_size[1]) canvas.Divide(rows, column) leg_holder = [] for index, hist_str in enumerate(hist_names): hists = hist_objs[hist_str] pad = canvas.cd(index + 1) # Force disable if != of 2 if len(hists) != 2: doRatio = False if doRatio: drawopt = 'pE1' pad.cd() top = TPad("pad_top", "This is the top pad", 0.0, ratio_size_as_fraction, 1.0, 1.0) top.SetBottomMargin(0.0) top.SetBottomMargin(0.06 / float(top.GetHNDC())) #top.SetTopMargin (0.04/float(top.GetHNDC())) top.SetRightMargin(0.05) top.SetLeftMargin(0.16) top.SetFillColor(0) top.Draw(drawopt) tobject_collector.append(top) pad.cd() bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0, ratio_size_as_fraction) bot.SetBottomMargin(0.10 / float(bot.GetHNDC())) #bot.SetTopMargin (0.02/float(bot.GetHNDC())) bot.SetTopMargin(0.0) bot.SetRightMargin(0.05) bot.SetLeftMargin(0.16) bot.SetFillColor(0) bot.Draw(drawopt) tobject_collector.append(bot) if type(legend_prefix) is not list: legend_prefix = [legend_prefix] * len(legends) if doRatio: top.cd() leg = TLegend(legend_position[0], legend_position[1], legend_position[2], legend_position[3]) from AtlasStyle import setLegend1, atlas_template setLegend1(leg) leg.SetHeader(legend_header) for i, eff in enumerate(hists): eff.SetLineColor(self._curve_color[i]) eff.SetMarkerColor(self._curve_color[i]) eff.SetMarkerStyle(self._marker_style[i]) if type(eff) is TProfile: eff.SetStats(0) leg.AddEntry(eff, legend_prefix[i] + legends[i], 'p') if i is 0: eff.Draw() else: eff.Draw('same') leg.SetTextSize(0.03) leg.SetBorderSize(0) leg.Draw() if doRatio: top.Modified() top.Update pad.Modified() pad.Update() from ROOT import TProfile, TEfficiency, kFALSE xmin = 0 xmax = 999 if type(hists[0]) is TProfile: hists[0].GetYaxis().SetRangeUser(y_limits[index][0], y_limits[index][1]) elif type(hists[0]) is TEfficiency: hists[0].GetPaintedGraph().GetYaxis().SetRangeUser( y_limits[index][0], y_limits[index][1]) hists[0].GetPaintedGraph().GetYaxis().SetTitle('A') # Fix the X axis nbins = hists[0].GetTotalHistogram().GetNbinsX() xmin = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge(1) xmax = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge( nbins + 1) hists[0].GetPaintedGraph().GetXaxis().SetLimits(xmin, xmax) else: hists[0].GetYaxis().SetRangeUser(y_limits[index][0], y_limits[index][1]) pad.Modified() pad.Update() tobject_collector.append(leg) if doRatio: atlas_template(top, **kwargs) top.Update() from ROOT import TH1 divide = "" drawopt = 'pE1' bot.cd() ref = hists[0].GetPassedHistogram().Clone() h = hists[1].GetPassedHistogram().Clone() #ref = hists[0].Clone() #h = hists[1].Clone() ref.Sumw2() h.Sumw2() ref.Divide(hists[0].GetTotalHistogram().Clone()) h.Divide(hists[1].GetTotalHistogram().Clone()) #ratioplot = TEfficiency(h,ref) ratioplot = h.Clone() ratioplot.Sumw2() ratioplot.SetName(h.GetName() + '_ratio') ratioplot.Divide(h, ref, 1., 1., '') #ratioplot.Divide(ref) ratioplot.SetFillColor(0) ratioplot.SetFillStyle(0) ratioplot.SetMarkerColor(1) ratioplot.SetLineColor(kBlack) ratioplot.SetMarkerStyle(24) ratioplot.SetMarkerSize(1.2) ratioplot.GetYaxis().SetTitle('trigger / ref') ratioplot.GetYaxis().SetTitleSize(0.10) ratioplot.GetXaxis().SetTitleSize(0.10) ratioplot.GetXaxis().SetLabelSize(0.10) ratioplot.GetYaxis().SetLabelSize(0.10) ratioplot.GetYaxis().SetRangeUser(0.9, 1.07) ratioplot.Draw(drawopt) tobject_collector.append(ratioplot) #atlas_template(bot, **kwargs) from ROOT import TLine l1 = TLine(xmin, 1, xmax, 1) l1.SetLineColor(kRed) l1.SetLineStyle(2) l1.Draw() tobject_collector.append(l1) bot.Update() else: atlas_template(pad, **kwargs) pad.Update() canvas.SaveAs(oname + '.pdf')
latex.DrawLatex(1.3 * l, posY_ - relExtraDY * cmsTextSize * t, extraText) latex1 = TLatex() latex1.SetNDC() latex1.SetTextAngle(0) latex1.SetTextColor(1) latex1.SetTextSize(0.03) if expect_or_observe == 'observe': h[15].SetMarkerStyle(20) h[15].SetMarkerSize(1) h[15].SetStats(0) h[15].Draw("same p e") leg1.AddEntry(h[15], "DATA", "lp") leg1.Draw() leg2.Draw() leg3.Draw() fPads2.cd() fPads2.SetGridy() fPads2.SetGridx() divide = TH1D() if expect_or_observe == 'expect': divide = hmc else: divide = h[15] divide.Divide(hmc) divide.SetTitle("") divide.SetStats(0)
leg_limit_vs_mass_.SetBorderSize(0) leg_limit_vs_mass_.SetTextSize(0.03) leg_limit_vs_mass_.SetLineColor(1) leg_limit_vs_mass_.SetLineStyle(1) leg_limit_vs_mass_.SetLineWidth(1) leg_limit_vs_mass_.SetFillColor(0) leg_limit_vs_mass_.SetFillStyle(1001) leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__Th_limit, "Theoretical cross-section", "L") if drawObs: leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__obs_limit, "Observed 95% CL upper limit", "L") leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__exp_limit, "Expected 95% CL upper limit", "L") leg_limit_vs_mass_.Draw() myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_" + year_this + "_ctau" + ctau_this_str + plot_tag + ".pdf") myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_" + year_this + "_ctau" + ctau_this_str + plot_tag + ".png") myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_" + year_this + "_ctau" + ctau_this_str + plot_tag + ".C") ##################exclusion region of ctau and Lambda/mass ####################### print "value of the 2D r grid (exp, " + year_this + ") provided from samples: " print r_exp_2d_grid_ print "value of the 2D r grid (obs, " + year_this + ") provided from samples: " print r_obs_2d_grid_ lambda_point_boundary_exp_ = np.zeros(N_ctau)
def drawTrainingCurve(input, output): hist = pickle.load(open(input, "rb")) tr_acc = hist["acc"] tr_loss = hist["loss"] val_acc = hist["val_acc"] val_loss = hist["val_loss"] epochs = range(len(tr_acc)) c = TCanvas("c", "c", 800, 500) #c.SetFillStyle(4000) #c.SetFrameFillStyle(4000) gStyle.SetOptStat(0) uppad = TPad("u", "u", 0., 0.55, 1., 1.) downpad = TPad("d", "d", 0., 0., 1., 0.55) uppad.Draw() #uppad.SetFillStyle(4000) #uppad.SetFrameFillStyle(4000) downpad.Draw() #downpad.SetFillStyle(4000) #downpad.SetFrameFillStyle(4000) uppad.cd() gPad.SetMargin(0.15, 0.05, 0.02, 0.15) gPad.SetGrid(1, 1) gStyle.SetGridColor(13) gr_acc_train = TGraph(len(epochs), array('d', epochs), array('d', tr_acc)) gr_acc_train.SetLineColor(2) gr_acc_train.SetLineWidth(2) gr_acc_test = TGraph(len(epochs), array('d', epochs), array('d', val_acc)) gr_acc_test.SetLineColor(4) gr_acc_test.SetLineWidth(2) mgup = TMultiGraph("mgup", ";number of epochs;accuracy") mgup.Add(gr_acc_train, "l") mgup.Add(gr_acc_test, "l") mgup.Draw("AL") mgup.GetXaxis().SetRangeUser(min(epochs), max(epochs)) mgup.GetXaxis().SetLabelSize(0) mgup.GetYaxis().CenterTitle() mgup.GetYaxis().SetTitleSize(0.12) mgup.GetYaxis().SetTitleOffset(0.5) mgup.GetYaxis().SetLabelSize(0.105) mgup.GetYaxis().SetNdivisions(8) l = TLegend(0.6, 0.15, 0.88, 0.6) l.SetTextSize(0.14) l.AddEntry(gr_acc_train, "training", "l") l.AddEntry(gr_acc_test, "validation", "l") l.Draw("same") downpad.cd() gPad.SetMargin(0.15, 0.05, 0.25, 0.02) gPad.SetGrid(1, 1) gStyle.SetGridColor(13) gr_loss_train = TGraph(len(epochs), array('d', epochs), array('d', tr_loss)) gr_loss_train.SetLineColor(2) gr_loss_train.SetLineWidth(2) gr_loss_test = TGraph(len(epochs), array('d', epochs), array('d', val_loss)) gr_loss_test.SetLineColor(4) gr_loss_test.SetLineWidth(2) mgdown = TMultiGraph("mgdown", ";number of epochs;loss") mgdown.Add(gr_loss_train, "l") mgdown.Add(gr_loss_test, "l") mgdown.Draw("AL") mgdown.GetXaxis().SetRangeUser(min(epochs), max(epochs)) mgdown.GetXaxis().SetLabelSize(0.085) mgdown.GetXaxis().SetTitleSize(0.11) mgdown.GetXaxis().SetTitleOffset(0.9) mgdown.GetXaxis().CenterTitle() mgdown.GetYaxis().CenterTitle() mgdown.GetYaxis().SetTitleSize(0.11) mgdown.GetYaxis().SetTitleOffset(0.55) mgdown.GetYaxis().SetLabelSize(0.085) mgdown.GetYaxis().SetNdivisions(8) c.SaveAs(output)
def drawlegend(self, position=None, **kwargs): """Create and draw legend. Legend position can be controlled in several ways drawlegend(position) drawlegend(position=position) where position is a string which can contain the horizontal position, e.g. 'left', 'center', 'right', 'L', 'C', 'R', 'x=0.3', ... where 'x' is the position (between 0 an 1) of the left side in the frame. The position string can also contain the vertical position as e.g. 'top', 'middle', 'bottom', 'T', 'M', 'B', 'y=0.3', ... where 'y' is the position (between 0 an 1) of the top side in the frame. Instead of the strings, the exact legend coordinates can be controlled with the keywords x1, x2, y1 and y2, or, x1, y1, width and height: drawlegend(x1=0.2,width=0.4) drawlegend(x1=0.2,width=0.4,y1=0.9,height=0.4) drawlegend(x1=0.2,x2=0.6,y1=0.9,y2=0.4) These floats are normalized to the axis frame, ignoring the canvas margins: x=0 is the left, x=1 is the right, y=0 is the bottom and y=1 is the top side. Values less than 0, or larger than 1, will put the legend outside the frame. """ #if not ratio: # tsize *= 0.80 # signaltsize *= 0.80 verbosity = LOG.getverbosity(self, kwargs) hists = self.hists errstyle = 'lep' if gStyle.GetErrorX() else 'ep' entries = kwargs.get('entries', []) bands = kwargs.get('band', [self.errband]) # error bands bands = ensurelist(bands, nonzero=True) bandentries = kwargs.get('bandentries', []) title = kwargs.get('header', None) title = kwargs.get('title', title) # legend header/title latex = kwargs.get('latex', True) # automatically format strings as LaTeX style = kwargs.get('style', None) style0 = kwargs.get('style0', None) # style of first histogram errstyle = kwargs.get('errstyle', errstyle) # style for an error point styles = kwargs.get('styles', []) position = kwargs.get('pos', position) # legend position position = kwargs.get('position', position) or self.position option = kwargs.get('option', '') border = kwargs.get('border', False) transparent = kwargs.get('transparent', True) x1_user = kwargs.get('x1', None) # legend left side x2_user = kwargs.get('x2', None) # legend right side y1_user = kwargs.get('y1', None) # legend top side y2_user = kwargs.get('y2', None) # legend bottom side width = kwargs.get('width', -1) # legend width height = kwargs.get('height', -1) # legend height tsize = kwargs.get('tsize', _lsize) # text size twidth = kwargs.get('twidth', None) or 1 # scalefactor for legend width theight = kwargs.get('theight', None) or 1 # scalefactor for legend height texts = kwargs.get('text', []) # extra text below legend ncols = kwargs.get('ncols', self.ncols) or 1 # number of legend columns colsep = kwargs.get('colsep', 0.06) # seperation between legend columns bold = kwargs.get('bold', True) # bold legend header panel = kwargs.get('panel', 1) # panel (top=1, bottom=2) texts = ensurelist(texts, nonzero=True) entries = ensurelist(entries, nonzero=False) bandentries = ensurelist(bandentries, nonzero=True) headerfont = 62 if bold else 42 # CHECK LOG.insist(self.canvas, "Canvas does not exist!") self.canvas.cd(panel) scale = 485. / min(gPad.GetWh() * gPad.GetHNDC(), gPad.GetWw() * gPad.GetWNDC()) tsize *= scale # text size # ENTRIES #if len(bandentries)==len(bands) and len(entries)>len(hists): # for band, bandtitle in zip(band,bandentries): # entries.insert(hists.index(band),bandtitle) while len(entries) < len(hists): entries.append(hists[len(entries)].GetTitle()) while len(bandentries) < len(bands): bandentries.append(bands[len(bandentries)].GetTitle()) hists = hists + bands entries = entries + bandentries # STYLES if style0: styles[0] = style0 while len(styles) < len(hists): hist = hists[len(styles)] if hist in bands: styles.append('f') elif style != None: styles.append(style) elif hasattr(hist, 'GetFillStyle') and hist.GetFillStyle() > 0: styles.append('f') elif 'E0' in hist.GetOption() or 'E1' in hist.GetOption(): styles.append(errstyle) else: styles.append('lp') # NUMBER of LINES nlines = sum([1 + e.count('\n') for e in entries]) #else: nlines += 0.80 if texts: nlines += sum([1 + t.count('\n') for t in texts]) if ncols > 1: nlines /= float(ncols) if title: nlines += 1 + title.count('\n') # DIMENSIONS if width < 0: width = twidth * 0.35 if height < 0: height = theight * 1.34 * tsize * nlines if ncols > 1: width *= ncols / (1 - colsep) x2 = 0.90 x1 = x2 - width y1 = 0.92 y2 = y1 - height # POSITION if not position: position = 'TRR' if ncols > 1 else 'R' if title else 'TR' position = position.replace('left', 'L').replace( 'center', 'C').replace('right', 'R').replace( #.lower() 'top', 'T').replace('middle', 'M').replace('bottom', 'B') if 'C' in position: if 'R' in position: center = 0.57 elif 'L' in position: center = 0.43 else: center = 0.50 x1 = center - width / 2 x2 = center + width / 2 elif 'LL' in position: x1 = 0.03 x2 = x1 + width elif 'L' in position: x1 = 0.08 x2 = x1 + width elif 'RR' in position: x2 = 0.97 x1 = x2 - width elif 'R' in position: x2 = 0.92 x1 = x2 - width elif 'x=' in position: x1 = float(re.findall(r"x=(\d\.\d+)", position)[0]) x2 = x1 + width if 'M' in position: if 'T' in position: middle = 0.57 elif 'B' in position: middle = 0.43 else: middle = 0.50 y1 = middle - height / 2 y2 = middle + height / 2 elif 'TT' in position: y2 = 0.97 y1 = y2 - height elif 'T' in position: y2 = 0.92 y1 = y2 - height elif 'BB' in position: y1 = 0.03 y2 = y1 + height elif 'B' in position: y1 = 0.08 y2 = y1 + height elif 'y=' in position: y2 = float(re.findall(r"y=(\d\.\d+)", position)[0]) y1 = y2 - height if x1_user != None: x1 = x1_user x2 = x1 + width if x2_user == None else x2_user if y1_user != None: y1 = y1_user y2 = y1 - height if y2_user == None else y2_user L, R = gPad.GetLeftMargin(), gPad.GetRightMargin() T, B = gPad.GetTopMargin(), gPad.GetBottomMargin() X1, X2 = L + (1 - L - R) * x1, L + ( 1 - L - R) * x2 # convert frame to canvas coordinates Y1, Y2 = B + (1 - T - B) * y1, B + ( 1 - T - B) * y2 # convert frame to canvas coordinates legend = TLegend(X1, Y1, X2, Y2) LOG.verb( "Plot.drawlegend: position=%r, height=%.3f, width=%.3f, (x1,y1,x2,y2)=(%.2f,%.2f,%.2f,%.2f), (X1,Y1,X2,Y2)=(%.2f,%.2f,%.2f,%.2f)" % (position, height, width, x1, y1, x2, y2, X1, Y1, X2, Y2), verbosity, 1) # MARGIN if ncols >= 2: margin = 0.090 / width else: margin = 0.044 / width legend.SetMargin(margin) # STYLE if transparent: legend.SetFillStyle(0) # 0 = transparent else: legend.SetFillColor(0) legend.SetBorderSize(border) legend.SetTextSize(tsize) legend.SetTextFont(headerfont) # bold for title if ncols > 1: legend.SetNColumns(ncols) legend.SetColumnSeparation(colsep) # HEADER if title: if latex: title = maketitle(title) legend.SetHeader(title) legend.SetTextFont(42) # no bold for entries # ENTRIES if hists: for hist1, entry1, style1 in columnize(zip(hists, entries, styles), ncols): for entry in entry1.split('\n'): if latex: entry = maketitle(entry) legend.AddEntry(hist1, entry, style1) hist1, style1 = 0, '' for line in texts: if latex: line = maketitle(line) legend.AddEntry(0, line, '') if verbosity >= 2: print ">>> Plot.drawlegend: title=%r, texts=%s, latex=%s" % ( title, texts, latex) print ">>> Plot.drawlegend: hists=%s" % (hists) print ">>> Plot.drawlegend: entries=%s" % (entries) print ">>> Plot.drawlegend: styles=%s" % (styles) print ">>> Plot.drawlegend: nlines=%s, len(hists)=%s, len(texts)=%s, ncols=%s, margin=%s" % ( nlines, len(hists), len(texts), ncols, margin) legend.Draw(option) self.legends.append(legend) return legend
def makeDiscr(train_discr_dict, discr_dict, outfile, xtitle="discriminator"): c = ROOT.TCanvas("c", "c", 800, 500) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1) #ROOT.gPad.SetLogy(1) #ROOT.gPad.SetGrid(1,1) ROOT.gStyle.SetGridColor(17) l = TLegend(0.17, 0.75, 0.88, 0.88) l.SetTextSize(0.055) l.SetBorderSize(0) l.SetFillStyle(0) l.SetNColumns(2) colors = [2, 1, 4, ROOT.kCyan + 2] counter = 0 for leg, discr in train_discr_dict.iteritems(): a = Hist(30, 0, 1) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.06) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.9) if counter == 0: a.draw("hist") else: a.draw("same hist") l.AddEntry(a, leg, "l") counter += 1 counter = 0 for leg, discr in discr_dict.iteritems(): a = Hist(30, 0, 1) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetMarkerColor(colors[counter]) a.SetMarkerStyle(34) a.SetMarkerSize(1.8) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.06) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.4) a.draw("same p X0") l.AddEntry(a, leg, "p") counter += 1 # counter = 0 # for leg,discr in train_discr_dict.iteritems(): # d = Hist(30, 0, 1) # d.fill_array(discr) # d.SetLineColor(colors[counter]) # d.SetLineWidth(2) # l.AddEntry(d,leg,"l") # # b = Hist(30, 0, 1) # d.fill_array(discr_dict[leg.split(" ")[0] + " test"]) # b.SetLineColor(colors[counter]) # b.SetMarkerColor(colors[counter]) # b.SetMarkerStyle(34) # b.SetMarkerSize(1.8) # b.SetLineWidth(2) # l.AddEntry(b,leg,"p") # counter += 1 l.Draw("same") c.SaveAs(outfile)
def plot2(key, xsections, histos, names, LogY, weights, outputDIR): c1=TCanvas(key, key, 800, 600) pad1 = TPad("pad1", "", 0.00, 0.20, 0.99, 0.99) pad2 = TPad("pad2", "", 0.00, 0.00, 0.99, 0.20) pad1.SetGridx() pad1.SetGridy() pad2.SetGridy() pad1.SetFillColor(0) pad1.SetLineColor(0) pad2.SetFillColor(0) pad2.SetLineColor(0) pad1.SetBottomMargin(0.03) pad2.SetTopMargin(0.15) pad2.SetBottomMargin(0.3) pad1.Draw() pad2.Draw() leg1 = TLegend(0.68,0.55,0.86,0.86) histos[0].GetXaxis().SetLabelSize(0) histos[0].SetMarkerStyle(20) for i in range(0,len(histos)): #if histos[i].Integral()==0: continue histos[i].Scale(xsections[i]/weights[i]) histos[i].SetLineColor(i+1) histos[i].SetLineWidth(2) histo_ratio=histos[1].Clone() for i in range(2,len(histos)): histo_ratio.Add(histos[i]) histo_ratio.SetLineWidth(2) histo_sum=histo_ratio.Clone() histo_sum.SetLineColor(49) histo_sum.SetLineWidth(2) histo_ratio.SetTitle('') histo_ratio.Divide(histos[0]) histo_ratio.SetLineColor(49) histo_ratio.SetMaximum(1.5) histo_ratio.SetMinimum(0.5) histo_ratio.GetYaxis().SetNdivisions(4,kFALSE) histo_ratio.GetXaxis().SetTitle(key) histo_ratio.GetXaxis().SetTitleSize(0.15) histo_ratio.GetXaxis().SetTitleOffset(0.75) histo_ratio.GetXaxis().SetLabelSize(0.13) histo_ratio.GetYaxis().SetTitle('summed/inc') histo_ratio.GetYaxis().SetTitleSize(0.1) histo_ratio.GetYaxis().SetTitleOffset(0.3) histo_ratio.GetYaxis().SetLabelSize(0.13) pad1.cd() if LogY: pad1.SetLogy() histos[0].SetMaximum(1.2*histos[0].GetMaximum()) histos[0].SetMinimum(0.0001) histos[0].Draw('pe') for i in range(1,len(histos)): histos[i].Draw('same h') histo_sum.Draw('same h') leg1.AddEntry(histos[0], names[0]) leg1.AddEntry(histo_sum, 'MGsummed') for i in range(1,len(histos)): leg1.AddEntry(histos[i], names[i]) leg1.SetFillStyle(0) leg1.SetBorderSize(0) leg1.Draw() c1.Update() pad2.cd() histo_ratio.Draw() if LogY: c1.SaveAs(outputDIR + '/' + key + '_log.png') c1.SaveAs(outputDIR + '/' + key + '_log.pdf') else: c1.SaveAs(outputDIR + '/' + key + '.png') c1.SaveAs(outputDIR + '/' + key + '.pdf') for i in range(0,len(histos)): histos[i].Scale(weights[i]/xsections[i])
def main(): filename = read_file_name("NY_OUTPUT.txt") can = TCanvas("can", "can") can.SetGrid() mg = TMultiGraph() nn = 9 GR = [] NAME = [] px, py = array('d'), array('d') f = open(filename[2], 'r') indicator = 0 for line in f: if (indicator == 0): indicator = indicator + 1 continue Name, Total, Pos, Neg, TNum = line.split() name = Find_Loca(Name) name = Name.replace(Name[name:], "") # print(name) px.append((indicator - 1) % 9) py.append(float(Total)) if ((indicator) % 9 == 0): NAME.append(name) gr = TGraph(nn, px, py) GR.append(gr) px, py = array('d'), array('d') indicator = indicator + 1 # print(GR); print(len(GR)) for i in range(len(GR)): GR[i].SetLineWidth(2) if "water" in NAME[i]: GR[i].SetLineWidth(5) GR[i].SetLineColor(1) GR[i].SetMarkerColor(1) if "wine" in NAME[i]: GR[i].SetMarkerColor(2) GR[i].SetLineColor(2) if "beer" in NAME[i]: GR[i].SetMarkerColor(5) GR[i].SetLineColor(5) if "tea" in NAME[i]: GR[i].SetMarkerColor(4) GR[i].SetLineColor(4) if "coffee" in NAME[i]: GR[i].SetMarkerColor(3) GR[i].SetLineColor(3) if "juice" in NAME[i]: GR[i].SetMarkerColor(7) GR[i].SetLineColor(7) if "COLA" in NAME[i]: GR[i].SetMarkerColor(6) GR[i].SetLineColor(6) GR[i].GetXaxis().SetTitle("days") GR[i].SetMarkerStyle(20) # GR[i].Fit("pol4","q") mg.Add(GR[i]) mg.Draw("ALP") leg = TLegend(0.65, 0.65, 0.9, 0.8) leg.SetBorderSize(0) leg.SetFillColor(10) for i in range(len(GR)): leg_entry = leg.AddEntry(GR[i], NAME[i], "l") leg.Draw() mg.SetTitle("Total words counts at NY") mg.GetHistogram().GetXaxis().SetTitle("days") mg.GetHistogram().GetXaxis().SetTitleOffset(1) mg.GetHistogram().GetXaxis().SetLabelSize(0.03) mg.GetHistogram().GetYaxis().SetTitle("Counts") mg.GetHistogram().GetYaxis().SetTitleOffset(1.3) mg.GetHistogram().GetYaxis().SetLabelSize(0.03) mg.GetHistogram().GetXaxis().SetBinLabel(5, "Mon") mg.GetHistogram().GetXaxis().SetBinLabel(16, "Tue") mg.GetHistogram().GetXaxis().SetBinLabel(28, "Wed") mg.GetHistogram().GetXaxis().SetBinLabel(40, "Thu") mg.GetHistogram().GetXaxis().SetBinLabel(51, "Fri") mg.GetHistogram().GetXaxis().SetBinLabel(63, "Sat") mg.GetHistogram().GetXaxis().SetBinLabel(73, "Sun") mg.GetHistogram().GetXaxis().SetBinLabel(84, "Mon") mg.GetHistogram().GetXaxis().SetBinLabel(96, "Tue") # for i in range(len(GR)): # mg.GetHistogram().GetXaxis().SetBinLabel(i,DAYS) # mg.GetHistogram().GetXaxis().SetLabel("tt") can.Modified() can.Update() # can.GetFrame().SetBorderSize( 12 ) can.Print("Total_NY.pdf")
yMin=0 yMax = max(eeHist.GetBinContent(eeHist.GetMaximumBin()),eeHist.GetBinContent(mmHist.GetMaximumBin()))*1.5 hCanvas.DrawFrame(0,yMin,30,yMax,"; %s ; %s" %("m(ll) [GeV]","N_{events} / 0.5 GeV")) ROOT.gStyle.SetOptStat(0) #~ eeHist.SetLineColor(ROOT.kRed) #~ eeHist.SetLineColor(ROOT.kRed) fakeHist = ROOT.TH1F() fakeHist.SetLineColor(ROOT.kWhite) legend.SetHeader("Data") legend.AddEntry(eeHist,"e^{#pm}e^{#mp} + #mu^{#pm}#mu^{#mp}","p") #~ legend.AddEntry(mmHist,"e^{#pm}#mu^{#mp}","l") eeHist.Draw("same") #~ emHist.Draw("samehist") legend.Draw("same") line1 = ROOT.TLine(20,0,20,yMax) line2 = ROOT.TLine(1.6,0,1.6,yMax) line1.SetLineColor(ROOT.kBlue+3) line2.SetLineColor(ROOT.kBlue+3) line1.SetLineWidth(2) line2.SetLineWidth(2) line1.SetLineStyle(2) line2.SetLineStyle(2) line1.Draw("same") #~ line2.Draw("same")
def DrawOverlap(histList, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1], cat='2b'): gStyle.SetOptTitle(0) gStyle.SetOptStat(0) gStyle.SetTitleOffset(1.1, "Y") #gStyle.SetTitleOffset(1.9,"X"); gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) gStyle.SetTickLength(0.0, "x") i = 0 # histList_=[] # histList=[] # histList1=[] # maximum=[] ## Legend leg = TLegend(0.2, 0.80, 0.89, 0.89) #,NULL,"brNDC"); leg.SetBorderSize(0) leg.SetNColumns(3) # leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) # leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.05) c = TCanvas("c1", "c1", 0, 0, 500, 500) c.SetBottomMargin(0.15) c.SetLeftMargin(0.15) c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) # print ("you have provided "+str(len(fileVec))+" files and "+str(len(histVec))+" histograms to make a overlapping plot" ) # print "opening rootfiles" c.cd() print "provided hists", histList for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(1.5) #1.4 for log histList[ih].SetMinimum(0.1) #1.4 for log if logstatus[1] is 0: maxi = histList[ih].GetMaximum() histList[ih].SetMaximum(maxi * 2) #1.4 for log histList[ih].SetMinimum(0) #1.4 for log # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if tt is TGraphAsymmErrors: histList[ih].Draw("APL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("PE2 ") if ih > 0: #histList[ih].SetLineWidth(2) if tt is TGraphAsymmErrors: histList[ih].Draw("PL same") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("PE0 same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(100) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(0) histList[ih].SetMarkerStyle(markerStyle[ih]) histList[ih].SetMarkerSize(1) leg.AddEntry(histList[ih], legendtext[ih], "PL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): print "setting style for hist" print "color code", colors[ih] # histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetFillColor(colors[ih]) histList[ih].SetMarkerStyle(20) histList[ih].SetMarkerSize(1.0) histList[ih].SetLineWidth(1) #invert legend between first and second if ih == 0: leg.AddEntry(histList[ih + 1], legendtext[ih + 1], "PEL") #"f") if ih == 1: leg.AddEntry(histList[ih - 1], legendtext[ih - 1], 'f') #"PEL") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(1.4) histList[ih].GetYaxis().SetTitleFont(42) histList[ih].GetYaxis().SetLabelFont(42) histList[ih].GetYaxis().SetLabelSize(.052) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) # histList[ih].GetXaxis().SetLabelSize(0.0000); histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) #histList[ih].GetXaxis().SetTitleOffset(1.14) histList[ih].GetXaxis().SetTitleFont(42) histList[ih].GetXaxis().SetLabelFont(42) histList[ih].GetYaxis().SetLabelFont(42) histList[ih].GetXaxis().SetNdivisions(507) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); # histList[ih].GetXaxis().SetTickSize(0.00) i = i + 1 pt = TPaveText(0.01, 0.92, 0.95, 0.96, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(42) pt.SetTextSize(0.046) #text = pt.AddText(0.12,0.35,"CMS Internal 36 fb^{-1} (2016) ") text = pt.AddText(0.12, 0.35, "CMS Internal 41.5 fb^{-1} (2017) ") #text = pt.AddText(0.12,0.35,"CMS Internal 59.6 fb^{-1} (2018) ") #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ") cattxt = TLatex(0.20, 0.75, cat + ' ' + "category") cattxt.SetTextSize(0.06) cattxt.SetTextAlign(12) cattxt.SetNDC(1) cattxt.SetTextFont(42) pt.Draw() cattxt.Draw() leg.Draw() outputdirname = 'TFplots/' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
def main(): inputfiles = ["/mnt/disk1/nutufts/kmason/data/sparseinfill_data_test.root"] outputfile = ["sparseoutput.root"] CHECKPOINT_FILE = "../training/vplane_24000.tar" trueadc_h = TH1F('adc value', 'adc value', 100, 0., 100.) predictadc_h = TH1F('adc value', 'adc value', 100, 0., 100.) diffs2d_thresh_h = TH2F('h2', 'diff2d', 90, 10., 100., 90, 10., 100.) diff2d_h = TH2F('h2', 'diff2d', 100, 0., 100., 100, 0., 100.) if GPUMODE: DEVICE = torch.device("cuda:%d" % (DEVICE_IDS[0])) else: DEVICE = torch.device("cpu") iotest = load_infill_larcvdata("infillsparsetest", inputfiles, batchsize, nworkers, "ADCMasked", "ADC", plane, tickbackward=tickbackward, readonly_products=readonly_products) inputmeta = larcv.IOManager(larcv.IOManager.kREAD) inputmeta.add_in_file(inputfiles[0]) inputmeta.initialize() # setup model model = SparseInfill((image_height, image_width), reps, ninput_features, noutput_features, nplanes, show_sizes=False).to(DEVICE) # load checkpoint data checkpoint = torch.load( CHECKPOINT_FILE, map_location=CHECKPOINT_MAP_LOCATIONS) # load weights to gpuid best_prec1 = checkpoint["best_prec1"] model.load_state_dict(checkpoint["state_dict"]) tstart = time.time() # values for average accuracies totacc2 = 0 totacc5 = 0 totacc10 = 0 totacc20 = 0 totalbinacc = 0 # output IOManager outputdata = larcv.IOManager(larcv.IOManager.kWRITE, "IOManager", larcv.IOManager.kTickForward) outputdata.set_out_file("sparseoutput.root") outputdata.initialize() # save to output file ev_out_ADC = outputdata.get_data(larcv.kProductImage2D, "ADC") ev_out_input = outputdata.get_data(larcv.kProductImage2D, "Input") ev_out_output = outputdata.get_data(larcv.kProductImage2D, "Output") ev_out_overlay = outputdata.get_data(larcv.kProductImage2D, "Overlay") totaltime = 0 for n in xrange(nentries): starttime = time.time() print "On entry: ", n inputmeta.read_entry(n) ev_meta = inputmeta.get_data(larcv.kProductSparseImage, "ADC") outmeta = ev_meta.SparseImageArray()[0].meta_v() model.eval() infilldict = iotest.get_tensor_batch(DEVICE) coord_t = infilldict["coord"] input_t = infilldict["ADCMasked"] true_t = infilldict["ADC"] # run through model predict_t = model(coord_t, input_t, 1) forwardpasstime = time.time() predict_t.detach().cpu().numpy() input_t.detach().cpu().numpy() true_t.detach().cpu().numpy() # calculate accuracies labels = input_t.eq(0).float() chargelabel = labels * (true_t > 0).float() totaldeadcharge = chargelabel.sum().float() totaldead = labels.sum().float() predictdead = labels * predict_t truedead = true_t * labels predictcharge = chargelabel * predict_t truecharge = chargelabel * true_t err = (predictcharge - truecharge).abs() totacc2 += (err.lt(2).float() * chargelabel.float()).sum().item() / totaldeadcharge totacc5 += (err.lt(5).float() * chargelabel.float()).sum().item() / totaldeadcharge totacc10 += (err.lt(10).float() * chargelabel.float()).sum().item() / totaldeadcharge totacc20 += (err.lt(20).float() * chargelabel.float()).sum().item() / totaldeadcharge bineq0 = (truedead.eq(0).float() * predictdead.eq(0).float() * labels).sum().item() bingt0 = (truedead.gt(0).float() * predictdead.gt(0).float()).sum().item() totalbinacc += (bineq0 + bingt0) / totaldead # construct dense images ADC_img = larcv.Image2D(image_width, image_height) Input_img = larcv.Image2D(image_width, image_height) Output_img = larcv.Image2D(image_width, image_height) Overlay_img = larcv.Image2D(image_width, image_height) ADC_img, Input_img, Output_img, Overlay_img, trueadc_h, predictadc_h, diff2d_h, diffs2d_thresh_h = pixelloop( true_t, coord_t, predict_t, input_t, ADC_img, Input_img, Output_img, Overlay_img, trueadc_h, predictadc_h, diff2d_h, diffs2d_thresh_h) ev_out_ADC.Append(ADC_img) ev_out_input.Append(Input_img) ev_out_output.Append(Output_img) ev_out_overlay.Append(Overlay_img) outputdata.set_id(ev_meta.run(), ev_meta.subrun(), ev_meta.event()) outputdata.save_entry() endentrytime = time.time() print "total entry time: ", endentrytime - starttime print "forward pass time: ", forwardpasstime - starttime totaltime += forwardpasstime - starttime avgacc2 = (totacc2 / nentries) * 100 avgacc5 = (totacc5 / nentries) * 100 avgacc10 = (totacc10 / nentries) * 100 avgacc20 = (totacc20 / nentries) * 100 avgbin = (totalbinacc / nentries) * 100 tend = time.time() - tstart print "elapsed time, ", tend, "secs ", tend / float(nentries), " sec/batch" print "average forward pass time: ", totaltime / nentries print "--------------------------------------------------------------------" print " For dead pixels that should have charge..." print "<2 ADC of true: ", avgacc2.item(), "%" print "<5 ADC of true: ", avgacc5.item(), "%" print "<10 ADC of true: ", avgacc10.item(), "%" print "<20 ADC of true: ", avgacc20.item(), "%" print "binary acc in dead: ", avgbin.item(), "%" print "--------------------------------------------------------------------" # create canvas to save as pngs # ADC values rt.gStyle.SetOptStat(0) c1 = TCanvas("ADC Values", "ADC Values", 600, 600) trueadc_h.GetXaxis().SetTitle("ADC Value") trueadc_h.GetYaxis().SetTitle("Number of pixels") c1.UseCurrentStyle() trueadc_h.SetLineColor(632) predictadc_h.SetLineColor(600) c1.SetLogy() trueadc_h.Draw() predictadc_h.Draw("SAME") legend = TLegend(0.1, 0.7, 0.48, 0.9) legend.AddEntry(trueadc_h, "True Image", "l") legend.AddEntry(predictadc_h, "Output Image", "l") legend.Draw() c1.SaveAs(("ADCValues.png")) # 2d ADC difference histogram c2 = TCanvas("diffs2D", "diffs2D", 600, 600) c2.UseCurrentStyle() line = TLine(0, 0, 80, 80) line.SetLineColor(632) diff2d_h.SetOption("COLZ") c2.SetLogz() diff2d_h.GetXaxis().SetTitle("True ADC value") diff2d_h.GetYaxis().SetTitle("Predicted ADC value") diff2d_h.Draw() line.Draw() c2.SaveAs(("diffs2d.png")) # 2d ADC difference histogram - thresholded c3 = TCanvas("diffs2D_thresh", "diffs2D_thresh", 600, 600) c3.UseCurrentStyle() line = TLine(10, 10, 80, 80) line.SetLineColor(632) diffs2d_thresh_h.SetOption("COLZ") diffs2d_thresh_h.GetXaxis().SetTitle("True ADC value") diffs2d_thresh_h.GetYaxis().SetTitle("Predicted ADC value") diffs2d_thresh_h.Draw() line.Draw() c3.SaveAs(("diffs2d_thresh.png")) # save results outputdata.finalize()
class PlotGraphs: def __init__(self, data, xlow, xhigh, ylow, yhigh, xlabel="", ylabel="", xLegend=.45, yLegend=.60, legendWidth=0.20, legendHeight=0.45, fillStyle=3395, drawOption='APL3', make_tfile=False): self.graph_index = {} self.ngraphs = 0 self.data = data self.drawOption = drawOption self.xlow = xlow self.xhigh = xhigh self.ylow = ylow self.yhigh = yhigh self.xlabel = xlabel self.ylabel = ylabel self.multigraph = TMultiGraph("MultiGraph", "") self.legend_type = {} if make_tfile: self.tfile = TFile('tgraphs.root', 'recreate') self.legend = TLegend(xLegend, yLegend, xLegend + legendWidth, yLegend + legendHeight) self.g_ = {} self.g2_ = {} self.g3_ = {} for cat in data.cat: if data.type[cat] == 'observed': #self.g_[cat] = TGraph(len(data.x[cat]), data.x[cat], data.y[cat]) self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g_[cat].SetName(cat) if make_tfile: _gcopy = self.g_[cat].Clone() self.tfile.Append(_gcopy) if data.dofit[cat]: #self.g_[cat].Fit("pol3", "M", "", data.fit_min[cat], data.fit_max[cat]) f1 = TF1( "f1", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0+[3]*(x-1000.0)*(x-1000.0)*(x-1000.0)/1000000000.0", data.fit_min[cat], data.fit_max[cat]) f2 = TF1( "f2", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0", data.fit_min[cat], data.fit_max[cat]) f3 = TF1("f3", "[0]+[1]*(x-1000.0)/1000.0", data.fit_min[cat], data.fit_max[cat]) _fr = self.g_[cat].Fit("f2", "MEWS", "", data.fit_min[cat], data.fit_max[cat]) _fr.Print() elif data.type[cat] == 'expected': self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat]) self.g2_[cat] = TGraphAsymmErrors( len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.eyl2[cat], data.eyh2[cat]) self.g3_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.y[cat], data.exl2[cat]) self.g3_[cat].SetFillStyle(1002) #self.g3_[cat].SetFillStyle(3008) # 95% quantile self.g2_[cat].SetMarkerColor(data.fill2_color[cat]) self.g2_[cat].SetMarkerStyle(data.marker_style[cat]) self.g2_[cat].SetMarkerSize(data.marker_size[cat]) self.g2_[cat].SetLineColor(data.fill2_color[cat]) self.g2_[cat].SetLineStyle(data.line_style[cat]) self.g2_[cat].SetLineWidth(data.line_width[cat]) #self.g2_[cat].SetFillColor(data.marker_color[cat]+2) self.g2_[cat].SetFillColor(data.fill2_color[cat]) #self.g2_[cat].SetFillStyle(3008) #self.g2_[cat].SetFillStyle(3003) self.g2_[cat].SetFillStyle(data.fill2_style[cat]) self.g_[cat].SetMarkerColor(data.marker_color[cat]) self.g_[cat].SetMarkerStyle(data.marker_style[cat]) self.g_[cat].SetMarkerSize(data.marker_size[cat]) self.g_[cat].SetLineColor(data.line_color[cat]) self.g_[cat].SetLineStyle(data.line_style[cat]) self.g_[cat].SetLineWidth(data.line_width[cat]) self.g_[cat].SetFillColor(data.fill_color[cat]) if data.fill_style[cat] == None: self.g_[cat].SetFillStyle(fillStyle) else: self.g_[cat].SetFillStyle(data.fill_style[cat]) if data.type[cat] == 'observed': # only the main observed limit is a line, # everything else is a filled area if cat[0:3] == 'obs': _legend_type = 'lp' if 'PC' in drawOption: _draw_option = 'PC' else: _draw_option = 'PL' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:3] == 'SSM': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) # print theory curve #self.g_[cat].Print() elif cat[0:3] == 'Psi': _legend_type = 'lp' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) elif cat[0:2] == 'RS': _legend_type = 'f' _draw_option = '3' self.multigraph.Add(self.g_[cat], _draw_option) else: _legend_type = 'f' self.multigraph.Add(self.g_[cat]) #self.multigraph.Add(self.g_[cat]) self.graph_index[cat] = self.ngraphs self.ngraphs += 1 #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], _legend_type); self.legend_type[cat] = _legend_type elif data.type[cat] == 'expected': self.g3_[cat].SetFillColor(0) self.g3_[cat].SetMinimum(self.ylow) self.g3_[cat].SetMaximum(self.yhigh) self.g3_[cat].GetXaxis().SetLimits(self.xlow, self.xhigh) self.multigraph.Add(self.g3_[cat], 'C3') self.ngraphs += 1 # 95 expected band self.multigraph.Add(self.g2_[cat]) self.ngraphs += 1 self.multigraph.Add(self.g_[cat], 'C3L') self.graph_index[cat] = self.ngraphs self.ngraphs += 1 # median line gline = self.g_[cat].Clone() gline.SetLineWidth(3) gline.SetLineColor(ROOT.kBlue) gline.SetLineStyle(2) # print graph contents #gline.Print() #self.multigraph.Add(gline, 'LXC') self.multigraph.Add(gline, 'C3X') self.legend.AddEntry(gline, 'median expected', "l") self.ngraphs += 1 #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], "f"); self.legend.AddEntry(self.g_[cat], '68% expected', "f") # 95% expected band legend self.legend.AddEntry(self.g2_[cat], '95% expected', "f") keylist = data.legend_index.keys() # keys are indices keylist.sort() for key in keylist: self.legend.AddEntry(self.g_[data.legend_index[key]], data.tlegend[data.legend_index[key]], self.legend_type[data.legend_index[key]]) self.legend.SetShadowColor(0) self.legend.SetFillColor(0) self.legend.SetLineColor(0) if make_tfile: self.tfile.Write() self.tfile.Close() def draw(self, yLabelSize=0.045): self.multigraph.SetMinimum(self.ylow) self.multigraph.SetMaximum(self.yhigh) self.multigraph.Draw(self.drawOption) self.multigraph.GetXaxis().SetNdivisions(405) self.multigraph.GetYaxis().SetNdivisions(405) self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh) #self.multigraph.GetYaxis().SetTitle("") #self.multigraph.GetYaxis().SetLabelSize(yLabelSize) #self.multigraph.GetXaxis().SetLabelSize(yLabelSize) # axis labels #latex = TLatex() #latex.SetNDC() ##latex.SetTextSize(0.04) #latex.SetTextSize(yLabelSize) #latex.SetTextAlign(31) # align right #latex.DrawLatex(0.95,0.01, self.xlabel) #latex.SetTextAngle(90) #latex.DrawLatex(0.04,0.95, self.ylabel) XLabel(self.xlabel, 0.95, 0.03, text_size=0.07) YLabel(self.ylabel, 0.04, 0.9, text_size=0.07) self.legend.SetFillStyle(0) self.legend.SetBorderSize(0) #self.legend.SetTextSize(0.04) self.legend.SetTextSize(yLabelSize) self.legend.SetTextFont(22) self.legend.Draw() return self.multigraph def draw_line(self, xline, ymin=-0.02, ymax=0.20): if xline == None: return #print 'XXXX', xline _x = array('d') _y = array('d') _x.append(xline) _y.append(ymin) _x.append(float(xline)) _y.append(ymax) g_ = TGraph(len(_x), _x, _y) self.multigraph.Add(g_, 'L') def print_values(self, cat1, cat2): legend = 'PlotGraphs::print_values():' if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat1]) else: return None if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat2]) else: return None for x in range(750, 1150, 50): dmax = 0.0 drelmax = 0.0 v1 = graph1.Eval(x) v2 = graph2.Eval(x) d = math.fabs(v2 - v1) drel = math.fabs((v2 - v1) / v1) if d > dmax: dmax = d if drel > drelmax: drelmax = drel print legend, 'x =', x print legend, cat1, 'value =', v1 print legend, cat2, 'value =', v2 print legend, 'abs diff =', d print legend, 'abs relative diff =', drel print legend, 'max abs diff =', dmax print legend, 'max abs relative diff =', drelmax def find_intersection(self, cat1, cat2, xmin=250, xmax=2500, precision=0.00001): legend = 'PlotGraphs::find_intersection():' if cat1 in self.data.cat: graph1 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat1]) else: return None if cat2 in self.data.cat: graph2 = self.multigraph.GetListOfGraphs().At( self.graph_index[cat2]) #graph2.Print() else: return None _x = xmin print legend, graph1.Eval(_x) - graph2.Eval(_x) _d = graph1.Eval(_x) - graph2.Eval(_x) _step = xmax - xmin while abs(_d) > precision: _x += _step if _x > xmax or _x < xmin: return None _d2 = graph1.Eval(_x) - graph2.Eval(_x) _sign1 = _d > 0 _sign2 = _d2 > 0 if _sign1 != _sign2: _step = -0.5 * _step _d = _d2 if abs(_d2) < precision: return _x