def EMTFEta(plotter): ## variables for the plot xTitle = "Generated muon |#eta|" title = "%s;%s;%s" % (topTitle, xTitle, yTitle) toPlot = "TMath::Abs(%s)" % (geneta) h_bins = "(20,1.2,2.4)" nBins = int(h_bins[1:-1].split(',')[0]) minBin = float(h_bins[1:-1].split(',')[1]) maxBin = float(h_bins[1:-1].split(',')[2]) c = newCanvas() gPad.SetGridx(xGrid) gPad.SetGridy(yGrid) base = TH1F("base", title, nBins, minBin, maxBin) base.SetMinimum(0) base.SetMaximum(plotter.yMax) base.GetXaxis().SetLabelSize(0.05) base.GetYaxis().SetLabelSize(0.05) base.GetXaxis().SetTitleSize(0.05) base.GetYaxis().SetTitleSize(0.05) base.Draw("") CMS_lumi.CMS_lumi(c, iPeriod, iPos) denom_cut = AND(ok_eta(1.2, 2.4), ok_2_csc_lcts()) h1 = draw_geff(plotter.tree, title, h_bins, toPlot, AND(denom_cut, TCut("genParticle.pt>20")), ok_emtf(20), "same", kBlue) h2 = draw_geff(plotter.tree, title, h_bins, toPlot, AND(denom_cut, TCut("genParticle.pt>15")), ok_emtf(15), "same", kRed) h3 = draw_geff(plotter.tree, title, h_bins, toPlot, AND(denom_cut, TCut("genParticle.pt>10")), ok_emtf(10), "same", kGreen + 2) h4 = draw_geff(plotter.tree, title, h_bins, toPlot, AND(denom_cut, TCut("genParticle.pt>5")), ok_emtf(5), "same", kOrange + 2) h5 = draw_geff(plotter.tree, title, h_bins, toPlot, AND(denom_cut, TCut("genParticle.pt>3")), ok_emtf(0), "same", kBlack) leg = TLegend(0.45, 0.2, .75, 0.5, "", "brNDC") leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextSize(0.05) leg.SetHeader("EMTF") leg.AddEntry(h1, "p_{T} > 20 GeV", "l") leg.AddEntry(h2, "p_{T} > 15 GeV", "l") leg.AddEntry(h3, "p_{T} > 10 GeV", "l") leg.AddEntry(h4, "p_{T} > 5 GeV", "l") leg.AddEntry(h5, "p_{T} > 0 GeV", "l") leg.Draw("same") c.Print("%sEff_EMTF_eta_Pt20_%s" % (plotter.targetDir + subdirectory, plotter.ext)) del c, base, h1, leg, h2, h3, h4, h5
def drawStavePlots(detector, det): from ROOT import TCanvas from ROOT import TH1F from ROOT import gPad StavePlots = {} if det == 1: Lay = [0, 1, 2] Phi = [22, 38, 52] detname = "PIX" if det == 2: Lay = [0, 1, 2, 3] Phi = [32, 40, 48, 56] detname = "SCT" ncanvas = 0 for lay in Lay: for phi in range(Phi[lay]): StavePlots[ncanvas] = TCanvas( "Stave%sPlots_L%d_Phi%d" % (detname, lay, phi), "Stave Plots %s L%d Phi%d" % (detname, lay, phi)) StavePlots[ncanvas].Divide(3, 2) stavemodules = detector.ReturnModules(det, 0, lay, phi) hStaveCorrections = {} for i in range(6): StavePlots[ncanvas].cd(i + 1) name, value = detector.GetModule(0).GetDoF(i) hname = 'Stave_%s_L%d_Phi%d_%s_corrections' % (detname, lay, phi, name) htitle = 'Stave %s L%d Phi%d %s Corrections' % (detname, lay, phi, name) hStaveCorrections[name] = TH1F(hname, htitle, len(stavemodules), 0, len(stavemodules)) if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hStaveCorrections[name].SetYTitle("mm") else: hStaveCorrections[name].SetYTitle("mrad") bin = 1 for mod in stavemodules: hStaveCorrections[name].SetBinContent( bin, detector.GetModule(mod).GetDoF(i)[1]) bin = bin + 1 #hStaveCorrections[name].Draw() XAxis = hStaveCorrections[name].GetXaxis() XAxis.CenterLabels() bin = 1 for mod in stavemodules: XAxis.SetBinLabel(bin, str(detector.GetModule(mod).Eta)) bin = bin + 1 hStaveCorrections[name].SetStats(False) hStaveCorrections[name].DrawCopy() gPad.SetGridx() gPad.SetGridy() ncanvas = ncanvas + 1 return StavePlots
def setpad(left, right, top, bottom): gPad.SetFillColor(10) gPad.SetBorderMode(0) gPad.SetBorderSize(0) gPad.SetFrameFillColor(10) gPad.SetFrameBorderMode(0) gPad.SetFrameBorderSize(0) gPad.SetLeftMargin(left) gPad.SetRightMargin(right) gPad.SetTopMargin(top) gPad.SetBottomMargin(bottom) gPad.SetGridx(0) gPad.SetGridy(0) gStyle.SetOptStat(0)
def drawSctBarrelCorrDistributions(detector): from ROOT import TCanvas from ROOT import TH1F from ROOT import gPad SctBarrelCorrDistributions = TCanvas( "SctBarrelCorrDistributions", "SCT Barrel Corrections Distributions") SctBarrelCorrDistributions.Divide(3, 2) hSctBarrelCorrDistributions = {} detname = "SCT Barrel" Color = AutoColors(len(detector)) for d in detector: hSctBarrelCorrDistributions[d] = {} for i in range(6): SctBarrelCorrDistributions.cd(i + 1) name, value = detector[d].GetModule(0).GetDoF(i) hname = '%s_%sCorrections_%d' % (detname, name, d) htitle = '%s %s Corrections' % (detname, name) if name is 'Tx': hSctBarrelCorrDistributions[d][name] = TH1F( hname, htitle, 50, -0.005, 0.005) elif name is 'Ty': hSctBarrelCorrDistributions[d][name] = TH1F( hname, htitle, 50, -0.1, 0.1) else: hSctBarrelCorrDistributions[d][name] = TH1F( hname, htitle, 50, -0.25, 0.25) if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hSctBarrelCorrDistributions[d][name].GetXaxis().SetTitle( name + " (mm)") else: hSctBarrelCorrDistributions[d][name].GetXaxis().SetTitle( name + " (mrad)") hSctBarrelCorrDistributions[d][name].GetYaxis().SetTitle("Modules") hSctBarrelCorrDistributions[d][name].SetLineColor(Color[d]) for module in detector[d].ReturnSctBarrelModules(): hSctBarrelCorrDistributions[d][name].Fill(module.GetDoF(i)[1]) if d == 0: hSctBarrelCorrDistributions[d][name].Draw() else: hSctBarrelCorrDistributions[d][name].Draw("Same") gPad.SetGridx() gPad.SetGridy() SctBarrelCorrDistributions.Update() return SctBarrelCorrDistributions, hSctBarrelCorrDistributions
def drawCorrVsHits(detector): from ROOT import TCanvas from ROOT import TGraph from array import array from ROOT import gPad CorrVsHits = TCanvas("CorrVsHits", "Alignment Corrections vs hits") CorrVsHits.Divide(3, 2) hCorrVsHits = {} Color = AutoColors(len(detector)) for det in detector: hCorrVsHits[det] = {} for i in range(6): CorrVsHits.cd(i + 1) name, value = detector[det].GetModule(0).GetDoF(i) hname = 'CorrVsHits_%s_corrections_%d' % (name, det) htitle = '%s Corrections vs hits_%d' % (name, det) xpoints = [] ypoints = [] for j in range(detector[det].nModules()): xpoints.append(detector[det].GetModule(j).Hits) ypoints.append(detector[det].GetModule(j).GetDoF(i)[1]) x = array("f", xpoints) y = array("f", ypoints) hCorrVsHits[det][name] = TGraph(detector[det].nModules(), x, y) hCorrVsHits[det][name].SetTitle(htitle) hCorrVsHits[det][name].GetXaxis().SetTitle("Hits per module") hCorrVsHits[det][name].GetYaxis().SetTitle(name) if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hCorrVsHits[det][name].GetYaxis().SetTitle(name + " (mm)") else: hCorrVsHits[det][name].GetYaxis().SetTitle(name + " (mrad)") hCorrVsHits[det][name].SetMarkerStyle(4) hCorrVsHits[det][name].SetMarkerSize(0.5) hCorrVsHits[det][name].SetMarkerColor(Color[det]) if det == 0: hCorrVsHits[det][name].Draw("Ap") else: hCorrVsHits[det][name].Draw("psame") gPad.SetGridx() gPad.SetGridy() gPad.SetLogx() CorrVsHits.Update() return CorrVsHits, hCorrVsHits
def rooFit109(): print ">>> setup model..." x = RooRealVar("x", "x", -10, 10) sigma = RooRealVar("sigma", "sigma", 3, 0.1, 10) mean = RooRealVar("mean", "mean", 0, -10, 10) gauss = RooGaussian("gauss", "gauss", x, RooConst(0), sigma) # RooConst(0) gives segfaults data = gauss.generate(RooArgSet(x), 100000) # RooDataSet #sigma = 3.15 # overwrites RooRealVar with a float sigma.setVal(3.15) print ">>> plot data and slightly distorted model..." frame1 = x.frame(Title("Data with distorted Gaussian pdf"), Bins(40)) # RooPlot data.plotOn(frame1, DataError(RooAbsData.SumW2)) gauss.plotOn(frame1) print ">>> calculate chi^2..." # Show the chi^2 of the curve w.r.t. the histogram # If multiple curves or datasets live in the frame you can specify # the name of the relevant curve and/or dataset in chiSquare() print ">>> chi^2 = %.2f" % frame1.chiSquare() print ">>> construct histograms with the residuals and pull of the data wrt the curve" hresid = frame1.residHist() # RooHist hpull = frame1.pullHist() # RooHist frame2 = x.frame(Title("Residual Distribution")) # RooPlot frame2.addPlotable(hresid, "P") frame3 = x.frame(Title("Pull Distribution")) # RooPlot frame3.addPlotable(hpull, "P") print ">>> draw functions and toy data on canvas..." canvas = TCanvas("canvas", "canvas", 100, 100, 2000, 400) canvas.Divide(3) for i, frame in enumerate([frame1, frame2, frame3], 1): canvas.cd(i) gPad.SetLeftMargin(0.14) gPad.SetRightMargin(0.04) frame.GetYaxis().SetTitleOffset(1.5) frame.GetYaxis().SetLabelOffset(0.010) frame.GetYaxis().SetTitleSize(0.045) frame.GetYaxis().SetLabelSize(0.042) frame.GetXaxis().SetTitleSize(0.045) frame.GetXaxis().SetLabelSize(0.042) frame.Draw() canvas.SaveAs("rooFit109.png") canvas.Close() # ratio/pull/residual plot print ">>> draw with pull plot..." canvas = TCanvas("canvas", "canvas", 100, 100, 1000, 1000) canvas.Divide(2) canvas.cd(1) gPad.SetPad("pad1", "pad1", 0, 0.33, 1, 1, 0, -1, 0) gPad.SetTopMargin(0.10) gPad.SetBottomMargin(0.03) gPad.SetLeftMargin(0.14) gPad.SetRightMargin(0.04) gPad.SetBorderMode(0) gStyle.SetTitleFontSize(0.062) frame1.GetYaxis().SetTitle("Events / %.3g GeV" % frame1.getFitRangeBinW()) frame1.GetYaxis().SetTitleSize(0.059) frame1.GetYaxis().SetTitleOffset(1.21) #frame1.GetYaxis().SetLabelOffset(0.010) frame1.GetXaxis().SetLabelSize(0) frame1.GetYaxis().SetLabelSize(0.045) frame1.Draw() canvas.cd(2) gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.33, 0, -1, 0) gPad.SetTopMargin(0.01) gPad.SetBottomMargin(0.30) gPad.SetLeftMargin(0.14) gPad.SetRightMargin(0.04) gPad.SetBorderMode(0) gPad.SetGridy(kTRUE) line1 = TLine(frame3.GetXaxis().GetXmin(), 0, frame3.GetXaxis().GetXmax(), 0) line2 = TLine(frame3.GetXaxis().GetXmin(), 0, frame3.GetXaxis().GetXmax(), 0) line1.SetLineColor(0) # white to clear dotted grid lines line2.SetLineColor(12) # dark grey line2.SetLineStyle(2) frame3.SetTitle("") frame3.GetYaxis().SetTitle("pull") frame3.GetXaxis().SetTitle("#Deltam^{2}_{ll} [GeV]") frame3.GetXaxis().SetTitleSize(0.13) frame3.GetYaxis().SetTitleSize(0.12) frame3.GetXaxis().SetTitleOffset(1.0) frame3.GetYaxis().SetTitleOffset(0.58) frame3.GetXaxis().SetLabelSize(0.10) frame3.GetYaxis().SetLabelSize(0.10) frame3.GetXaxis().SetLabelOffset(0.02) frame3.GetYaxis().SetLabelOffset(0.01) frame3.GetYaxis().SetRangeUser(-5, 5) frame3.GetYaxis().CenterTitle(True) frame3.GetYaxis().SetNdivisions(505) frame3.Draw("") line1.Draw("SAME") line2.Draw("SAME") frame3.Draw("SAME") canvas.SaveAs("rooFit109_ratiolike.png") canvas.Close()
def MakeOneHist(histogramName): HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right, header_y_top, HeaderText, "NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right, topLeft_y_top, LumiText, "NDC") LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) NormLabel = TPaveLabel() NormLabel.SetDrawOption("NDC") NormLabel.SetX1NDC(topLeft_x_left) NormLabel.SetX2NDC(topLeft_x_right) NormLabel.SetBorderSize(0) NormLabel.SetFillColor(0) NormLabel.SetFillStyle(0) NormText = "" if arguments.normalizeToUnitArea: NormText = "Scaled to unit area" Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) Canvas = TCanvas(histogramName) Histograms = [] LegendEntries = [] colorIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'], source['dataset']) inputFile = TFile(dataset_file) NumHistogramObj = inputFile.Get("OSUAnalysis/" + source['num_channel'] + "/" + histogramName) if 'condor_dir_den' in source: # If specified, take the denominator histogram from a different condor directory. dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'], source['dataset']) inputFileDen = TFile(dataset_fileDen) DenHistogramObj = inputFileDen.Get("OSUAnalysis/" + source['den_channel'] + "/" + histogramName) else: # Default is to use the same condor directory DenHistogramObj = inputFile.Get("OSUAnalysis/" + source['den_channel'] + "/" + histogramName) if not NumHistogramObj: print "WARNING: Could not find histogram " + source[ 'num_channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return if not DenHistogramObj: print "WARNING: Could not find histogram " + source[ 'den_channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = NumHistogramObj.Clone() if Histogram.Class().InheritsFrom("TH2"): Histogram.SetName(Histogram.GetName() + "__" + source['dataset']) Histogram.SetDirectory(0) DenHistogram = DenHistogramObj.Clone() DenHistogram.SetDirectory(0) inputFile.Close() if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetTitle( ).find("GenMatch") is -1 and not Histogram.Class().InheritsFrom( "TH2"): Histogram.Rebin(RebinFactor) DenHistogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "#epsilon_{ " + cutName + "} (" + str( Histogram.GetXaxis().GetBinWidth(1) ) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] + " width)" else: yAxisLabel = "#epsilon_{ " + cutName + "} (" + str( Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj) if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"): Histogram.Divide(DenHistogram) else: Histogram = TGraphAsymmErrors(Histogram, DenHistogram) if not arguments.makeFancy: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") # print splitTitle histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] Histogram.SetMarkerStyle(markerStyle) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) ### scaling histograms as per user's specifications for histogram in Histograms: if arguments.normalizeToUnitArea and histogram.Integral() > 0: histogram.Scale(1. / histogram.Integral()) ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram, LegendEntries[legendIndex], "LEP") legendIndex = legendIndex + 1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 if arguments.noTGraph: for histogram in Histograms: currentMax = histogram.GetMaximum() + histogram.GetBinError( histogram.GetMaximumBin()) if (currentMax > finalMax): finalMax = currentMax finalMax = 1.5 * finalMax if finalMax is 0: finalMax = 1 if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1, 2) Canvas.cd(1) gPad.SetPad(0, 0.25, 1, 1) gPad.SetMargin(0.15, 0.05, 0.01, 0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0, 0, 1, 0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15, 0.05, 0.4, 0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.plot_hist: plotting_options = "HIST" for histogram in Histograms: if histogram.Class().InheritsFrom("TH2"): histogram.SetTitle(histoTitle) histogram.Draw("colz") DatasetName = histogram.GetName() DatasetName = DatasetName[ DatasetName.rfind('__') + 2:] # substring starting with the last underscore DatasetLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right, topLeft_y_top, DatasetName, "NDC") DatasetLabel.SetBorderSize(0) DatasetLabel.SetFillColor(0) DatasetLabel.SetFillStyle(0) DatasetLabel.Draw() outputFile.cd() Canvas.SetName(histogram.GetName()) Canvas.Write() if arguments.makeFancy: HeaderLabel.Draw() else: if histogram.InheritsFrom("TGraph") and histCounter == 0: plotting_options = "AP" histogram.SetTitle(histoTitle) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) if histogram.InheritsFrom("TH1"): histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: if histogram.InheritsFrom("TH1"): plotting_options = plotting_options + " SAME" elif histogram.InheritsFrom("TGraph"): plotting_options = "P" histCounter = histCounter + 1 if histogram.Class().InheritsFrom("TH2"): return #legend coordinates, empirically determined :-) x_left = 0.1677852 x_right = 0.9647651 y_min = 0.6765734 y_max = 0.9 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() if arguments.makeFancy: HeaderLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: Comparison = ratioHistogram(Histograms[0], Histograms[1]) elif makeDiffPlots: Comparison = Histograms[0].Clone("diff") Comparison.Add(Histograms[1], -1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("hist1-hist2") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2 * YMax, 1.2 * YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 1.2 * YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") outputFile.cd() Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
def MakeOneDHist(histogramDirectory, histogramName,integrateDir): if arguments.verbose: print "Creating histogram", histogramName, "in directory", histogramDirectory HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetTextFont(42) HeaderLabel.SetTextSize(0.697674) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") CMSLabel.SetTextAlign(32) CMSLabel.SetTextFont(42) CMSLabel.SetTextSize(0.697674) CMSLabel.SetBorderSize(0) CMSLabel.SetFillColor(0) CMSLabel.SetFillStyle(0) if makeFancy: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC") LumiLabel.SetTextFont(62) LumiLabel.SetTextSize(0.7) LumiLabel.SetTextAlign(12) else: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC") LumiLabel.SetTextAlign(32) LumiLabel.SetTextFont(42) LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) canvasName = histogramName if integrateDir is "left": canvasName += "_CumulativeLeft" elif integrateDir is "right": canvasName += "_CumulativeRight" Canvas = TCanvas(canvasName) Histograms = [] RefIndex = -99 LegendEntries = [] colorIndex = 0 markerStyleIndex = 0 fillIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset']) inputFile = TFile(dataset_file) if arguments.generic: if histogramDirectory == "": histPath = histogramName else: histPath = histogramDirectory + "/" + histogramName HistogramObj = inputFile.Get(histPath) else: HistogramObj = inputFile.Get(source['channel'] + "Plotter/" + histogramDirectory + "/" + histogramName) if not HistogramObj: print "WARNING: Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = HistogramObj.Clone() Histogram.SetDirectory(0) inputFile.Close() Histogram.Sumw2() if arguments.verbose: print " Got histogram", Histogram.GetName(), "from file", dataset_file if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1: Histogram.Rebin(RebinFactor) # correct bin contents of object multiplcity plots if Histogram.GetName().startswith("num") and "PV" not in Histogram.GetName(): # include overflow bin for bin in range(2,Histogram.GetNbinsX()+2): content = Histogram.GetBinContent(bin) Histogram.SetBinContent(bin, content/float(bin-1)) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") xAxisLabelVar = xAxisLabel if "_pfx" in Histogram.GetName() or "_pfy" in Histogram.GetName() or "_sigma" in Histogram.GetName(): yAxisLabel = Histogram.GetYaxis().GetTitle() else: if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] xAxisLabelVar = xAxisLabel[0:unitBeginIndex] else: yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" if arguments.normalizeToUnitArea and arguments.makeSignificancePlots: unit = "Efficiency" else: unit = "Yield" if integrateDir is "left": yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" if integrateDir is "right": yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" nbins = Histogram.GetNbinsX() if not noOverFlow: Histogram.SetBinContent(nbins, Histogram.GetBinContent(nbins) + Histogram.GetBinContent(nbins+1)) # Add overflow Histogram.SetBinError(nbins, math.sqrt(math.pow(Histogram.GetBinError(nbins),2) + math.pow(Histogram.GetBinError(nbins+1),2))) # Set the errors to be the sum in quadrature if not noUnderFlow: Histogram.SetBinContent(1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) # Add underflow Histogram.SetBinError(1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) # Set the errors to be the sum in quadrature if not arguments.makeFancy and not arguments.generic: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") if len(splitTitle) > 1: histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = splitTitle[0] else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyleIndex = markerStyleIndex + 1 if markerStyleIndex is len(markerStyleList): markerStyleIndex = 0 fillIndex = fillIndex + 1 if 'scale' in source: Histogram.Scale(source['scale']) markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] else: markerStyle = markers[markerStyleList[markerStyleIndex]] fillStyle = 0 if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] else: markerStyle = markerStyle + fills[fillList[fillIndex]] Histogram.SetMarkerStyle(markerStyle) Histogram.SetMarkerSize(0.5) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) if arguments.normalizeToUnitArea and Histogram.Integral() > 0: Histogram.Scale(1./Histogram.Integral()) Histogram = MakeIntegralHist(Histogram, integrateDir) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) if 'reference' in source: if source['reference']: RefIndex = len(Histograms)-1 ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") # Legend.AddEntry(histogram,LegendEntries[legendIndex],"P") legendIndex = legendIndex+1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 for histogram in Histograms: currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin()) if(currentMax > finalMax): finalMax = currentMax finalMax = 1.5*finalMax if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots addOneToRatio = -1 if arguments.addOneToRatio: addOneToRatio = arguments.addOneToRatio yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.generic: plotting_options = "p,e" if arguments.plot_hist: plotting_options = "HIST" for histogram in Histograms: histogram.SetTitle(histoTitle) if arguments.verbose: print " Drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor()) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) histogram.SetMaximum(finalMax) if "_pfx" not in Histogram.GetName() and "_pfy" not in Histogram.GetName() and "_sigma" not in Histogram.GetName(): histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: plotting_options = plotting_options + " SAME" histCounter = histCounter + 1 #legend coordinates, empirically determined :-) x_left = 0.1677852 x_right = 0.9647651 y_min = 0.6765734 y_max = 0.9 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() # Deciding which text labels to draw and drawing them if arguments.makeFancy: HeaderLabel.Draw() LumiLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Comparisons = [] Canvas.cd(2) if RefIndex == -99: Reference = Histograms[0] else: Reference = Histograms[RefIndex] for Histogram in Histograms: if Histogram is Reference: continue if makeRatioPlots: makeRatio = functools.partial (ratioHistogram,Histogram, Reference) if arguments.ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, relErrMax = float(arguments.ratioRelErrMax)) if addOneToRatio != -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio)) Comparison = makeRatio() elif makeDiffPlots: Comparison = Reference.Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("X-ref") Comparison.SetLineColor(Histogram.GetLineColor()) Comparison.SetFillColor(Histogram.GetFillColor()) Comparison.SetFillStyle(Histogram.GetFillStyle()) Comparison.SetMarkerColor(Histogram.GetMarkerColor()) Comparison.SetMarkerStyle(Histogram.GetMarkerStyle()) Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) if addOneToRatio == -1: # it gets initialized to this dummy value of -1 Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange) else: Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) Comparisons.append(Comparison) option = "E0" for index,Comparison in enumerate(Comparisons): if index == 0: option += " SAME" Comparison.Draw(option) outputFile.cd(histogramDirectory) Canvas.Write() if arguments.verbose: print " Finished writing canvas: ", Canvas.GetName() if arguments.savePDFs: Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")
def MakeOneHist(dirName, histogramName): HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetTextFont(42) HeaderLabel.SetTextSize(0.697674) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") CMSLabel.SetTextAlign(32) CMSLabel.SetTextFont(42) CMSLabel.SetTextSize(0.697674) CMSLabel.SetBorderSize(0) CMSLabel.SetFillColor(0) CMSLabel.SetFillStyle(0) if makeFancy: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC") LumiLabel.SetTextFont(62) LumiLabel.SetTextSize(0.7) LumiLabel.SetTextAlign(12) else: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC") LumiLabel.SetTextAlign(32) LumiLabel.SetTextFont(42) LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) #legend coordinates, empirically determined :-) x_left = 0.4 x_right = 0.7 y_min = 0.15 y_max = 0.3 Legend = TLegend(x_left,y_min,x_right,y_max) Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) Canvas = TCanvas(histogramName) Histograms = [] HistogramClones = [] NBins = [] MaxXValues = [] MinXValues = [] LegendEntries = [] colorIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset']) inputFile = TFile(dataset_file) NumHistogramObj = inputFile.Get(source['num_channel'] + "Plotter/" + dirName + "/" + histogramName) if 'condor_dir_den' in source: # If specified, take the denominator histogram from a different condor directory. dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],source['dataset']) inputFileDen = TFile(dataset_fileDen) DenHistogramObj = inputFileDen.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName) else: # Default is to use the same condor directory DenHistogramObj = inputFile.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName) if not NumHistogramObj: print "WARNING: Could not find histogram " + source['num_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return if not DenHistogramObj: print "WARNING: Could not find histogram " + source['den_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = NumHistogramObj.Clone() if Histogram.Class().InheritsFrom("TH2"): Histogram.SetName(Histogram.GetName() + "__" + source['dataset']) Histogram.SetDirectory(0) DenHistogram = DenHistogramObj.Clone() DenHistogram.SetDirectory(0) inputFile.Close() nbinsN = Histogram.GetNbinsX() nbinsD = DenHistogram.GetNbinsX() if not noOverFlow: # Add overflow Histogram.SetBinContent( nbinsN, Histogram.GetBinContent(nbinsN) + Histogram.GetBinContent(nbinsN+1)) DenHistogram.SetBinContent(nbinsD, DenHistogram.GetBinContent(nbinsD) + DenHistogram.GetBinContent(nbinsD+1)) # Set the errors to be the sum in quadrature Histogram.SetBinError( nbinsN, math.sqrt(math.pow(Histogram.GetBinError(nbinsN),2) + math.pow(Histogram.GetBinError(nbinsN+1),2))) DenHistogram.SetBinError(nbinsD, math.sqrt(math.pow(DenHistogram.GetBinError(nbinsD),2) + math.pow(DenHistogram.GetBinError(nbinsD+1),2))) if not noUnderFlow: # Add underflow Histogram.SetBinContent( 1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) DenHistogram.SetBinContent(1, DenHistogram.GetBinContent(1) + DenHistogram.GetBinContent(0)) # Set the errors to be the sum in quadrature Histogram.SetBinError( 1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) DenHistogram.SetBinError(1, math.sqrt(math.pow(DenHistogram.GetBinError(1), 2) + math.pow(DenHistogram.GetBinError(0), 2))) if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1 and not Histogram.Class().InheritsFrom("TH2"): Histogram.Rebin(RebinFactor) DenHistogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] + " width)" else: yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" #check if bin content is consistent TEfficiency.CheckConsistency(Histogram,DenHistogram) for i in range(1,Histogram.GetNbinsX()+1): if Histogram.GetBinContent(i) > DenHistogram.GetBinContent(i): DenHistogram.SetBinContent(i,Histogram.GetBinContent(i)) #HistogramClone and HistogramClones only used for ratio plot HistogramClone = Histogram.Clone() HistogramClone.SetDirectory(0) HistogramClone.Divide(DenHistogram) Nbins = HistogramClone.GetNbinsX() MaxXValue = HistogramClone.GetXaxis().GetBinLowEdge(Nbins+1) MinXValue = HistogramClone.GetXaxis().GetBinLowEdge(1) #this Histogram becomes the main TEfficiency if Histogram.Class().InheritsFrom("TH2"): Histogram.Divide(DenHistogram) else: #using default methods (which give correct uncertainties) #see https://root.cern.ch/doc/master/classTEfficiency.html (c.f. section IV) Histogram = TEfficiency(Histogram,DenHistogram) if not arguments.makeFancy: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") # print splitTitle if len(splitTitle) > 1: histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = splitTitle[0] else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] Histogram.SetMarkerStyle(markerStyle) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) HistogramClones.append(HistogramClone) NBins.append(Nbins) MaxXValues.append(MaxXValue) MinXValues.append(MinXValue) ### scaling histograms as per user's specifications for histogram in Histograms: if arguments.normalizeToUnitArea and histogram.Integral() > 0: histogram.Scale(1./histogram.Integral()) ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") legendIndex = legendIndex+1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 1.1 if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots addOneToRatio = -1 if arguments.addOneToRatio: addOneToRatio = arguments.addOneToRatio dontRebinRatio = -1 if arguments.dontRebinRatio: dontRebinRatio = arguments.dontRebinRatio ratioRelErrMax = -1 if arguments.ratioRelErrMax: ratioRelErrMax = arguments.ratioRelErrMax yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.plot_hist: plotting_options = "HIST" h = TH2F("h1","",NBins[0],MinXValues[0],MaxXValues[0],110,0.,finalMax) h.SetTitle(";"+xAxisLabel+";"+yAxisLabel) h.Draw() for histogram in Histograms: if histogram.Class().InheritsFrom("TH2"): histogram.SetTitle(histoTitle) histogram.Draw("colz") DatasetName = histogram.GetName() DatasetName = DatasetName[DatasetName.rfind('__')+2:] # substring starting with the last underscore DatasetLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,DatasetName,"NDC") DatasetLabel.SetBorderSize(0) DatasetLabel.SetFillColor(0) DatasetLabel.SetFillStyle(0) DatasetLabel.Draw() outputFile.cd() Canvas.SetName(histogram.GetName()) Canvas.Write() else: if histogram.InheritsFrom("TEfficiency") and histCounter==0: plotting_options = "P SAME" histogram.SetTitle(histoTitle) histogram.Draw(plotting_options) if histogram.InheritsFrom("TH1"): histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if histCounter is 0: if histogram.InheritsFrom("TH1"): plotting_options = plotting_options + " SAME" elif histogram.InheritsFrom("TEfficiency"): plotting_options = "P" + " SAME" histCounter = histCounter + 1 if histogram.Class().InheritsFrom("TH2"): return Legend.Draw() if arguments.makeFancy: HeaderLabel.Draw() LumiLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: makeRatio = functools.partial (ratioHistogram,HistogramClones[0],HistogramClones[1]) if addOneToRatio != -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio)) if ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, relErrMax = float (ratioRelErrMax)) if dontRebinRatio is True: makeRatio = functools.partial (makeRatio, dontRebinRatio) Comparison = makeRatio () elif makeDiffPlots: Comparison = Histograms[0].Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("hist1-hist2") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) if addOneToRatio == -1: # it gets initialized to this dummy value of -1 Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange) else: Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") outputFile.cd(dirName) Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
def OLD_drawCorrEvolution(detector, labelList, drawErrors=False, drawLine=True, whichdof=-1): from ROOT import TCanvas from ROOT import TH1F from ROOT import gPad from ROOT import TLegend doDebug = True showErrors = True drawAllDofs = True nUsedDofs = 6 if (whichdof != -1): drawAllDofs = False if (whichdof > 5): nUsedDofs = 7 # 7/oct/2015 with the BowX we may have up to 7 dofs. Unless stated draw the ordinary 6. lowerDof = 0 upperDof = 5 if (not drawAllDofs): lowerDof = whichdof upperDof = whichdof # a canvas for all dofs ThisCanvas = TCanvas("AlignmentCorrectionsEvol", "Evolution of alignment corrections (All)") if (drawAllDofs): ThisCanvas.Divide(3, 2) hCorrectionsEvol = {} hCorrectionsEvolStruct = {} yrange = [0.002, 0.002, 0.002, 0.01, 0.01, 0.01, 0.002] # minimum is 0.001 (mm or mrad) # here detector = num of iterations numOfIterations = len(detector) if (doDebug): print " numOfIterations=", numOfIterations numOfAlignableStruct = detector[0].nModules() if (doDebug): print " numOfAlignableStructe=", numOfAlignableStruct EvolColor = AutoColors(numOfAlignableStruct) # find out range #for i in range(lowerDof, upperDof): for i in range(nUsedDofs): for iter in range(numOfIterations): for bin in range(detector[iter].nModules()): thisValue = abs(detector[iter].GetModule(bin).GetDoF( i)[1]) + detector[iter].GetModule(bin).GetDoFError(i)[1] if abs(thisValue) > yrange[i]: yrange[i] = thisValue yrange[i] *= 1.025 if (doDebug): print " dof=", i, " --> range: ", yrange[i] # maximum range maxTransRange = 0.100 if (yrange[0] > maxTransRange): yrange[0] = maxTransRange if (yrange[1] > maxTransRange): yrange[1] = maxTransRange if (yrange[2] > maxTransRange): yrange[2] = maxTransRange #yrange[0] = 0.04 #yrange[1] = 0.04 # Tx and Ty should have the same range if (yrange[0] > yrange[1]): yrange[1] = yrange[0] else: yrange[0] = yrange[1] # Tz range should be as minimum as Tx and Ty if (yrange[2] < yrange[0]): yrange[2] = yrange[0] # Rx and Ry should have the same range if (yrange[3] > yrange[4]): yrange[4] = yrange[3] else: yrange[3] = yrange[4] # Rz range should be as minimum as Rx and Ry #if (yrange[5] < yrange[3]): yrange[5] = yrange[3] # prepare the legend myLegend = TLegend(0.65, 0.65, 0.92, 0.92) # loop dof by dof (Tx, Ty...) and fill a polyline with teh corrections for each iteration if (doDebug): print " ** drawCorrEvolution ** lowerDof=", lowerDof, " upperDof = ", upperDof #for dof in range(nUsedDofs): for dof in range(lowerDof, upperDof + 1): if (doDebug): print " ** drawCorrEvolution ** going to draw dof=", dof ThisCanvas.cd() if (drawAllDofs): ThisCanvas.cd(dof + 1) name = detector[0].GetModule(0).GetDoF(dof)[0] hname = 'Dof_%s_corrections_Evol' % (name) htitle = 'Corrections evolution for %s' % (name) if (doDebug): print " ** drawCorrEvolution ** dof=", dof, " hname = ", hname print " htitle = ", htitle # this histogram is the main frame hCorrectionsEvol[dof] = TH1F(hname, htitle, numOfIterations - 1, -0.5, numOfIterations * 1. - 1.5) # set the x axis labels if (numOfIterations > 12): hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.03) hCorrectionsEvol[dof].GetXaxis().SetBit(18) for iter in range(numOfIterations - 1): # -1 do not include the total sum in the plot hCorrectionsEvol[dof].GetXaxis().SetBinLabel( iter + 1, 'Iter_%d' % (iter)) if (len(labelList) > iter): # use label given by user hCorrectionsEvol[dof].GetXaxis().SetBinLabel( iter + 1, labelList[iter]) # label Y axis if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hCorrectionsEvol[dof].SetYTitle("mm") else: hCorrectionsEvol[dof].SetYTitle("mrad") hCorrectionsEvol[dof].GetYaxis().SetRangeUser(-yrange[dof], yrange[dof]) hCorrectionsEvol[dof].SetStats(False) hCorrectionsEvol[dof].DrawCopy() gPad.SetGridx() gPad.SetGridy() #once the frame is plotted, loop on every structure and fill a histogram and draw it print " .. dealing with", name, "corrections .. with range for this dof: (", dof, ") range: +-", yrange[ dof] print " ** ==> numOfAlignableStruct = ", numOfAlignableStruct for struct in range(numOfAlignableStruct): #for struct in range(0,2): if (doDebug): print " >> looping on struct:", struct hCorrectionsEvolStruct[dof] = {} hname = 'Dof_%s_corrections_Evol_struct_%d' % (name, struct) htitle = 'Corrections evolution for structure %s (struct %d)' % ( name, struct) hCorrectionsEvolStruct[dof][struct] = TH1F( hname, htitle, numOfIterations, -0.5, numOfIterations * 1. - 0.5) hCorrectionsEvolStruct[dof][struct].SetLineColor(EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].SetStats(False) # once the histogram is created, fill it with the corrections of each iteration accumvalue = 0 for iter in range(numOfIterations - 1): # -1 to account for the overall integration value = detector[iter].GetModule(struct).GetDoF(dof)[1] accumvalue = accumvalue + value # if (doDebug): print " dof:",dof, " struct:",struct," iter:",iter," delta=",value hCorrectionsEvolStruct[dof][struct].SetBinContent( iter + 1, value) # if (doDebug): print "hCorrectionsEvolStruct[",dof,"][",struct,"].SetBinContent(",iter+1,",", value,")" if (drawErrors): hCorrectionsEvolStruct[dof][struct].SetBinError( iter + 1, detector[iter].GetModule(struct).GetDoFError(dof)[1]) # now draw the corrections for this structure if (doDebug): print "Accumulated", hname, ":", accumvalue # store the accumulated if (dof == 0): detector[numOfIterations - 1].GetModule(struct).setTx(accumvalue) if (dof == 1): detector[numOfIterations - 1].GetModule(struct).setTy(accumvalue) if (dof == 2): detector[numOfIterations - 1].GetModule(struct).setTz(accumvalue) if (dof == 3): detector[numOfIterations - 1].GetModule(struct).setRx(accumvalue) if (dof == 4): detector[numOfIterations - 1].GetModule(struct).setRy(accumvalue) if (dof == 5): detector[numOfIterations - 1].GetModule(struct).setRz(accumvalue) if (dof == 6): detector[numOfIterations - 1].GetModule(struct).setBx(accumvalue) if (drawErrors): hCorrectionsEvolStruct[dof][struct].SetFillColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].SetFillStyle(3354) # hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3') # --> original hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3') hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20) hCorrectionsEvolStruct[dof][struct].SetMarkerSize(0.5) hCorrectionsEvolStruct[dof][struct].SetMarkerColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].DrawCopy('same p e3 x0') for iter in range(numOfIterations - 1): hCorrectionsEvolStruct[dof][struct].SetBinError( iter + 1, 0) hCorrectionsEvolStruct[dof][struct].SetFillStyle(0) hCorrectionsEvolStruct[dof][struct].DrawCopy('same l') else: myOption = "same" if (drawLine): myOption += " l" else: myOption += " p" hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20) hCorrectionsEvolStruct[dof][struct].SetMarkerColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].DrawCopy(myOption) gPad.Update() if (dof == nUsedDofs - 1 and False): myLegend.AddEntry(hCorrectionsEvolStruct[dof][struct], detector[0].GetModule(struct).GetName(), "l") myLegend.Draw() gPad.Update() return ThisCanvas
def MakeOneDHist(pathToDir, distribution): numFittingSamples = 0 HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right, header_y_top, HeaderText, "NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right, topLeft_y_top, LumiText, "NDC") LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) NormLabel = TPaveLabel() NormLabel.SetDrawOption("NDC") NormLabel.SetX1NDC(topLeft_x_left) NormLabel.SetX2NDC(topLeft_x_right) NormLabel.SetBorderSize(0) NormLabel.SetFillColor(0) NormLabel.SetFillStyle(0) NormText = "" if arguments.normalizeToUnitArea: NormText = "Scaled to unit area" elif arguments.normalizeToData: NormText = "MC scaled to data" NormLabel.SetLabel(NormText) YieldsLabel = TPaveText(0.39, 0.7, 0.59, 0.9, "NDC") YieldsLabel.SetBorderSize(0) YieldsLabel.SetFillColor(0) YieldsLabel.SetFillStyle(0) YieldsLabel.SetTextAlign(12) RatiosLabel = TPaveText() RatiosLabel.SetDrawOption("NDC") RatiosLabel.SetBorderSize(0) RatiosLabel.SetFillColor(0) RatiosLabel.SetFillStyle(0) RatiosLabel.SetTextAlign(32) Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) fittingIntegral = 0 scaleFactor = 1 HistogramsToFit = [] TargetDataset = distribution['target_dataset'] FittingLegendEntries = [] DataLegendEntries = [] FittingHistogramDatasets = [] Stack_list = [] Stack_list.append(THStack("stack_before", distribution['name'])) Stack_list.append(THStack("stack_after", distribution['name'])) fileName = condor_dir + "/" + distribution['target_dataset'] + ".root" if not os.path.exists(fileName): return inputFile = TFile(fileName) if inputFile.IsZombie() or not inputFile.GetNkeys(): return Target = inputFile.Get("OSUAnalysis/" + distribution['channel'] + "/" + distribution['name']).Clone() Target.SetDirectory(0) inputFile.Close() Target.SetMarkerStyle(20) Target.SetMarkerSize(0.8) Target.SetFillStyle(0) Target.SetLineColor(colors[TargetDataset]) Target.SetLineStyle(1) Target.SetLineWidth(2) targetIntegral = Target.Integral() if (arguments.normalizeToUnitArea and Target.Integral() > 0): Target.Scale(1. / Target.Integral()) if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Target.GetNbinsX() >= RebinFactor * 5 and Target.GetName().find( "GenMatch") is -1: Target.Rebin(RebinFactor) ### formatting target histogram and adding to legend legendIndex = 0 Legend.AddEntry(Target, labels[TargetDataset], "LEP") legendIndex = legendIndex + 1 if not outputFile.Get("OSUAnalysis"): outputFile.mkdir("OSUAnalysis") if not outputFile.Get("OSUAnalysis/" + distribution['channel']): outputFile.Get("OSUAnalysis").mkdir(distribution['channel']) for sample in distribution[ 'datasets']: # loop over different samples requested to be fit dataset_file = "%s/%s.root" % (condor_dir, sample) inputFile = TFile(dataset_file) HistogramObj = inputFile.Get(pathToDir + "/" + distribution['channel'] + "/" + distribution['name']) if not HistogramObj: print "WARNING: Could not find histogram " + pathToDir + "/" + distribution[ 'channel'] + "/" + distribution[ 'name'] + " in file " + dataset_file + ". Will skip it and continue." continue Histogram = HistogramObj.Clone() Histogram.SetDirectory(0) inputFile.Close() if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetName( ).find("GenMatch") is -1: Histogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth( 1)) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] else: yAxisLabel = "Entries per bin (" + str( Histogram.GetXaxis().GetBinWidth(1)) + " width)" if not arguments.makeFancy: histoTitle = Histogram.GetTitle() else: histoTitle = "" legLabel = labels[sample] if (arguments.printYields): yieldHist = Histogram.Integral() legLabel = legLabel + " (%.1f)" % yieldHist FittingLegendEntries.append(legLabel) if (types[sample] == "bgMC"): numFittingSamples += 1 fittingIntegral += Histogram.Integral() Histogram.SetLineStyle(1) if (arguments.noStack): Histogram.SetFillStyle(0) Histogram.SetLineColor(colors[sample]) Histogram.SetLineWidth(2) else: Histogram.SetFillStyle(1001) Histogram.SetFillColor(colors[sample]) Histogram.SetLineColor(1) Histogram.SetLineWidth(1) elif (types[sample] == "signalMC"): numFittingSamples += 1 Histogram.SetFillStyle(0) Histogram.SetLineColor(colors[sample]) Histogram.SetLineStyle(1) Histogram.SetLineWidth(2) if (arguments.normalizeToUnitArea and Histogram.Integral() > 0): Histogram.Scale(1. / Histogram.Integral()) HistogramsToFit.append(Histogram) FittingHistogramDatasets.append(sample) #scaling histograms as per user's specifications if targetIntegral > 0 and fittingIntegral > 0: scaleFactor = targetIntegral / fittingIntegral for fittingHist in HistogramsToFit: if arguments.normalizeToData: fittingHist.Scale(scaleFactor) if arguments.normalizeToUnitArea and not arguments.noStack and fittingIntegral > 0: fittingHist.Scale(1. / fittingIntegral) elif arguments.normalizeToUnitArea and arguments.noStack and fittingHist.Integral( ) > 0: fittingHist.Scale(1. / fittingHist.Integral()) def fitf(x, par): xBin = HistogramsToFit[0].FindBin(x[0]) value = 0.0 for i in range(0, len(HistogramsToFit)): value += par[i] * HistogramsToFit[i].GetBinContent(xBin) + par[ i + len(HistogramsToFit)] * HistogramsToFit[i].GetBinError(xBin) return value lowerLimit = Target.GetBinLowEdge(1) upperLimit = Target.GetBinLowEdge(Target.GetNbinsX()) + Target.GetBinWidth( Target.GetNbinsX()) if 'lowerLimit' in distribution: lowerLimit = distribution['lowerLimit'] if 'upperLimit' in distribution: upperLimit = distribution['upperLimit'] func = TF1("fit", fitf, lowerLimit, upperLimit, 2 * len(HistogramsToFit)) for i in range(0, len(HistogramsToFit)): if 'fixed_datasets' in distribution and distribution['datasets'][ i] in distribution['fixed_datasets']: func.FixParameter(i, 1.0) else: func.SetParameter(i, 1.0) # func.SetParLimits (i, 0.0, 1.0e2) # comment this out so we don't have to pre-normalize the QCD input sample func.SetParName(i, labels[FittingHistogramDatasets[i]]) shiftedScaleFactors = [] if arguments.parametricErrors: # loop over all input histograms and shift them +- 1 sigma for i in range(0, len(HistogramsToFit)): sfs = [] # -1 => -1 sigma, +1 => +1 sigma for j in [-1, 1]: # loop over the parameters holding the errors for each dataset, fixing all to 0 for k in range(len(HistogramsToFit), 2 * len(HistogramsToFit)): func.FixParameter(k, 0) # fix the error of the dataset of interest to +-1 func.FixParameter(i + len(HistogramsToFit), j) # perform new fit for k in range(0, distribution['iterations'] - 1): if j == -1: print "Scale down " + labels[FittingHistogramDatasets[ i]] + " iteration " + str(k + 1) + "..." if j == 1: print "Scale up " + labels[FittingHistogramDatasets[ i]] + " iteration " + str(k + 1) + "..." Target.Fit("fit", "QEMR0") Target.Fit("fit", "VEMR0") # save the new scale factors for each dataset for k in range(0, len(HistogramsToFit)): sfs.append(func.GetParameter(k)) shiftedScaleFactors.append(sfs) # reset the parameters with the errors of each dataset to 0 for i in range(len(HistogramsToFit), 2 * len(HistogramsToFit)): func.FixParameter(i, 0) # do the fit to get the central values for i in range(0, distribution['iterations'] - 1): print "Iteration " + str(i + 1) + "..." Target.Fit("fit", "QEMR0") Target.Fit("fit", "VEMR0") if arguments.parametricErrors: # make a list of the largest errors on each contribution by shifting any other contribution parErrors = [] # loop over all the datasets for i in range(0, len(HistogramsToFit)): centralValue = func.GetParameter(i) maxError = 0 # find the maximum deviation from the central value and save that for shiftedScaleFactor in shiftedScaleFactors[i]: currentError = abs(shiftedScaleFactor - centralValue) if currentError > maxError: maxError = currentError parErrors.append(maxError) finalMax = 0 if not arguments.noStack: for fittingHist in HistogramsToFit: finalMax += fittingHist.GetMaximum() else: for fittingHist in HistogramsToFit: if (fittingHist.GetMaximum() > finalMax): finalMax = fittingHist.GetMaximum() if (Target.GetMaximum() > finalMax): finalMax = Target.GetMaximum() Target.SetMaximum(1.1 * finalMax) Target.SetMinimum(0.0001) Canvas = TCanvas(distribution['name'] + "_FitFunction") Canvas.cd(1) Target.Draw() func.Draw("same") outputFile.cd("OSUAnalysis/" + distribution['channel']) Canvas.Write() if arguments.savePDFs: if histogram == input_histograms[0]: Canvas.Print(pdfFileName + "(", "pdf") else: Canvas.Print(pdfFileName, "pdf") Target.SetStats(0) ### formatting bgMC histograms and adding to legend legendIndex = numFittingSamples - 1 for Histogram in reversed(HistogramsToFit): if (arguments.noStack): Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "L") else: Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "F") legendIndex = legendIndex - 1 ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) ### Draw everything to the canvases !!!! for i in range(0, 2): # 0 => before, 1 => after integrals = [] ratios = [] errors = [] if i == 1: # loop over each dataset, saving it's yield and the errors on it for j in range(0, len(HistogramsToFit)): integrals.append(HistogramsToFit[j].Integral()) HistogramsToFit[j].Scale(func.GetParameter(j)) ratios.append(func.GetParameter(j)) errors.append(func.GetParError(j)) for fittingHist in HistogramsToFit: if not arguments.noStack: Stack_list[i].Add(fittingHist) #creating the histogram to represent the statistical errors on the stack if not arguments.noStack: ErrorHisto = HistogramsToFit[0].Clone("errors") ErrorHisto.SetFillStyle(3001) ErrorHisto.SetFillColor(13) ErrorHisto.SetLineWidth(0) if i == 1: Legend.AddEntry(ErrorHisto, "Stat. Errors", "F") for Histogram in HistogramsToFit: if Histogram is not HistogramsToFit[0]: ErrorHisto.Add(Histogram) if i == 0: Canvas = TCanvas(distribution['name'] + "_Before") if i == 1: Canvas = TCanvas(distribution['name'] + "_After") if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1, 2) Canvas.cd(1) gPad.SetPad(0, 0.25, 1, 1) gPad.SetMargin(0.15, 0.05, 0.01, 0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0, 0, 1, 0.25) # format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15, 0.05, 0.4, 0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 if numFittingSamples is not 0 and not arguments.noStack: finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError( ErrorHisto.GetMaximumBin()) else: for bgMCHist in HistogramsToFit: if (bgMCHist.GetMaximum() > finalMax): finalMax = bgMCHist.GetMaximum() if (Target.GetMaximum() > finalMax): finalMax = Target.GetMaximum() + Target.GetBinError( Target.GetMaximumBin()) finalMax = 1.15 * finalMax if arguments.setYMax: finalMax = float(arguments.setYMax) if not arguments.noStack: # draw stacked background samples Stack_list[i].SetTitle(histoTitle) Stack_list[i].Draw("HIST") Stack_list[i].GetXaxis().SetTitle(xAxisLabel) Stack_list[i].GetYaxis().SetTitle(yAxisLabel) Stack_list[i].SetMaximum(finalMax) Stack_list[i].SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: Stack_list[i].GetHistogram().GetXaxis().SetLabelSize(0) #draw shaded error bands ErrorHisto.Draw("A E2 SAME") else: #draw the unstacked backgrounds HistogramsToFit[0].SetTitle(histoTitle) HistogramsToFit[0].Draw("HIST") HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel) HistogramsToFit[0].GetYaxis().SetTitle(yAxisLabel) HistogramsToFit[0].SetMaximum(finalMax) HistogramsToFit[0].SetMinimum(yAxisMin) for bgMCHist in HistogramsToFit: bgMCHist.Draw("A HIST SAME") Target.Draw("A E X0 SAME") #legend coordinates, empirically determined :-) x_left = 0.6761745 x_right = 0.9328859 x_width = x_right - x_left y_max = 0.9 entry_height = 0.05 if (numFittingSamples is not 0): #then draw the data & bgMC legend numExtraEntries = 2 # count the target and (lack of) title Legend.SetX1NDC(x_left) numExtraEntries = numExtraEntries + 1 # count the stat. errors entry Legend.SetY1NDC(y_max - entry_height * (numExtraEntries + numFittingSamples)) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() RatiosLabel.SetX1NDC(x_left - 0.1) RatiosLabel.SetX2NDC(x_right) RatiosLabel.SetY2NDC(Legend.GetY1NDC() - 0.1) RatiosLabel.SetY1NDC(RatiosLabel.GetY2NDC() - entry_height * (numFittingSamples)) # Deciding which text labels to draw and drawing them drawLumiLabel = False drawNormLabel = False offsetNormLabel = False drawHeaderLabel = False if not arguments.normalizeToUnitArea: #don't draw the lumi label if there's no data and it's scaled to unit area drawLumiLabel = True # move the normalization label down before drawing if we drew the lumi. label offsetNormLabel = True if arguments.normalizeToUnitArea or arguments.normalizeToData: drawNormLabel = True if arguments.makeFancy: drawHeaderLabel = True drawLumiLabel = False # now that flags are set, draw the appropriate labels if drawLumiLabel: LumiLabel.Draw() if drawNormLabel: if offsetNormLabel: NormLabel.SetY1NDC(topLeft_y_bottom - topLeft_y_offset) NormLabel.SetY2NDC(topLeft_y_top - topLeft_y_offset) else: NormLabel.SetY1NDC(topLeft_y_bottom) NormLabel.SetY2NDC(topLeft_y_top) NormLabel.Draw() if drawHeaderLabel: HeaderLabel.Draw() YieldsLabel.Clear() mcYield = Stack_list[i].GetStack().Last().Integral() dataYield = Target.Integral() if i == 0: YieldsLabel.AddText("Before Fit to Data") if i == 1: YieldsLabel.AddText("After Fit to Data") YieldsLabel.AddText("data yield: " + '%.1f' % dataYield) YieldsLabel.AddText("bkgd yield: " + '%.1f' % mcYield) YieldsLabel.AddText("data/bkgd: " + '%.2f' % (dataYield / mcYield)) if i == 1: for j in range(0, len(FittingLegendEntries)): if abs(ratios[j] - 1) < 0.001 and abs( errors[j] ) < 0.001: #then it probably was held fixed continue if arguments.showFittedYields: yield_ = ratios[j] * integrals[j] yielderror_ = errors[j] * yield_ text = FittingLegendEntries[ j] + " yield: " + '%.0f' % yield_ + ' #pm %.0f' % yielderror_ else: text = FittingLegendEntries[ j] + " ratio: " + '%.2f' % ratios[ j] + ' #pm %.2f' % errors[j] text = text + " (fit)" if arguments.parametricErrors: yield_ = ratios[j] * integrals[j] yieldParError_ = parErrors[j] * yield_ if arguments.showFittedYields: text += ' #pm %.2f' % yieldParError_ else: text += ' #pm %.2f' % parErrors[j] text = text + " (sys)" RatiosLabel.AddText(text) YieldsLabel.Draw() RatiosLabel.Draw() # drawing the ratio or difference plot if requested if (makeRatioPlots or makeDiffPlots): Canvas.cd(2) BgSum = Stack_list[i].GetStack().Last() if makeRatioPlots: if arguments.ratioRelErrMax: Comparison = ratioHistogram(Target, BgSum, arguments.ratioRelErrMax) else: Comparison = ratioHistogram(Target, BgSum) elif makeDiffPlots: Comparison = Target.Clone("diff") Comparison.Add(BgSum, -1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("Data-Bkgd") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser( -1.2 * YMax, 1.2 * YMax) else: Comparison.GetYaxis().SetRangeUser( -1.2 * YMin, 1.2 * YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") if i == 0: Canvas.Write(distribution['name'] + "_Before") if arguments.savePDFs: pathToDirString = plainTextString(pathToDir) Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" + pathToDirString + "/" + distribution['name'] + "_Before.pdf") if i == 1: Canvas.Write(distribution['name'] + "_After") if arguments.savePDFs: pathToDirString = plainTextString(pathToDir) Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" + pathToDirString + "/" + distribution['name'] + "_After.pdf")
def MakeOneHist(varXaxis, varConst, xvalues, constval): if len(xvalues)<=1: return # Do not make plot if there is only 1 xvalue Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) Canvas = TCanvas("sigEff_"+varConst+str(constval)+"_vs_"+varXaxis) Histograms = [] LegendEntries = [] colorIndex = 0 for source in input_sources: # loop over different input sources in config file # print "Debug: running over input_source from: ", source['condor_dir'], " for varXaxis=", varXaxis, ", varConst=", varConst # Create histogram of efficiencies with appropriate binning xAxisBins = array('d') xBinWidth = xvalues[1] - xvalues[0] for xval in xvalues: xAxisBins.append(xval - xBinWidth/2.0) xAxisBins.append(xvalues[-1] + xBinWidth/2.0) # add an extra bin boundary for the last bin. Histogram = TH1F("Histogram", ";x title;signal efficiency", len(xvalues), xAxisBins) Histogram.SetDirectory(0) # Now fill the histogram of efficiencies: for xval in xvalues: if varXaxis=="mass" and varConst=="lifetime": mass = xval lifetime = constval elif varXaxis=="lifetime" and varConst=="mass": lifetime = xval mass = constval else: print "Unrecognized value of varXaxis=", varXaxis return dataset_file = "condor/%s/%s.root" % (source['condor_dir'],dataset) dataset_file = dataset_file.replace("MASS", str(mass)) dataset_file = dataset_file.replace("LIFETIME", str(lifetime)) inputFile = TFile(dataset_file) HistCutflow = inputFile.Get("OSUAnalysis/" + source['channel'] + "CutFlow") if not HistCutflow: print "WARNING: Could not find histogram OSUAnalysis/" + source['channel'] + "CutFlow in file " + dataset_file + ". Will skip it and continue." return # calculate efficiency nbinsCutflow = HistCutflow.GetNbinsX() if arguments.xsecFile: xsec = float(signal_cross_sections[str(mass)]['value']) denom = xsec * intLumi else: denom = HistCutflow.GetBinContent(1) # denominator is the first entry in the cutflow histogram eff = HistCutflow.GetBinContent(nbinsCutflow) / denom effErr = HistCutflow.GetBinError (nbinsCutflow) / denom ibin = Histogram.FindBin(xval) Histogram.SetBinContent(ibin, eff) Histogram.SetBinError (ibin, effErr) print "Setting bin content for varConst = ", varConst, " = ", constval, " in ibin=", ibin, ", xval=", xval, ", eff=", eff, " +- ", effErr, ", fractional error =", effErr/eff, " numerator = ", HistCutflow.GetBinContent(nbinsCutflow), " denom = ", denom, " from file: ", dataset_file inputFile.Close() if varXaxis=="mass": xAxisLabel = "chargino mass [GeV]" elif varXaxis=="lifetime": xAxisLabel = "chargino c#tau [cm]" else: print "Unrecognized value of varXaxis=", varXaxis return yAxisLabel = "efficiency" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] Histogram.SetMarkerStyle(markerStyle) Histogram.SetMarkerSize(1) # Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) # Finish loop over input_sources # formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: # print "Adding entry to legend: ", LegendEntries[legendIndex] # Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") Legend.AddEntry(histogram,LegendEntries[legendIndex],"P") legendIndex = legendIndex+1 # finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 for histogram in Histograms: # currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin()) currentMax = histogram.GetMaximum() if(currentMax > finalMax): finalMax = currentMax finalMax = 1.5*finalMax if finalMax is 0: finalMax = 1 ## if arguments.setYMax: ## finalMax = float(arguments.setYMax) # Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots yAxisMin = 0.0 ## if arguments.setYMin: ## yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() ## if arguments.setLogY: ## gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "pe, x0" # x0 suppresses the error bar along x ## if arguments.plot_hist: ## plotting_options = "HIST" for histogram in Histograms: # histogram.SetTitle(histoTitle) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) if histogram.InheritsFrom("TH1"): histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: if histogram.InheritsFrom("TH1"): plotting_options = plotting_options + " SAME" elif histogram.InheritsFrom("TGraph"): plotting_options = "P" histCounter = histCounter + 1 x_left = 0.15 x_right = 0.55 y_min = 0.6 y_max = 0.8 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() customText = "chargino " + varConst + " " + str(constval) if varConst == "mass": customText += " GeV" elif varConst == "lifetime": customText += " cm" customText = customText.replace("lifetime", "c#tau") CustomLabel = TPaveLabel(x_left, 0.8, x_right, 0.9, customText, "NDC") CustomLabel.SetBorderSize(0) CustomLabel.SetFillColor(0) CustomLabel.SetFillStyle(0) CustomLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: # Comparison = ratioHistogram(Histograms[0],Histograms[1], 1000) Comparison = Histograms[0].Clone() Comparison.Divide(Histograms[1]) Comparison.GetYaxis().SetTitle("ratio") elif makeDiffPlots: Comparison = Histograms[0].Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("hist1-hist2") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: # RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) Comparison.GetYaxis().SetRangeUser(0.7, 1.3) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) # Comparison.Draw("E0") Comparison.Draw("PE, X0") # X0 suppresses error bar in x direction outputFile.cd() Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
def drawAllCorr(detector): from ROOT import TCanvas from ROOT import TH1F from ROOT import gPad debug = False if (debug): print " -- drawAllCorr -- starting for detector = ", detector showErrors = True Alldetector = TCanvas("AlignmentCorrections(All)", "Alignment Corrections (All)") Alldetector.Divide(3, 2) AllCorrections = {} yrange = [0, 0, 0, 0, 0, 0] if (debug): print " -- drawAllCorr -- finding out histogram ranges... " for i in range(6): if (debug): print " -- drawAllCorr -- extracting range for dof:", i for det in detector: for bin in range(detector[det].nModules()): #print " ** drawutils ** drawAllCorr ** det:",det," nModules = ",detector[det].nModules() if abs(detector[det].GetModule(bin).GetDoF(i)[1]) > yrange[i]: yrange[i] = abs(detector[det].GetModule(bin).GetDoF(i)[1]) yrange[i] *= 1.1 if (debug): print " -- drawAllCorr -- finding out colors ..." Color = AutoColors(len(detector)) for det in detector: for i in range(6): Alldetector.cd(i + 1) AllCorrections[det] = {} name, value = detector[det].GetModule(0).GetDoF(i) hname = 'All_%s_corrections_%d' % (name, det) htitle = 'All %s Corrections_%d' % (name, det) AllCorrections[det][name] = TH1F(hname, htitle, detector[det].nModules(), 0, detector[det].nModules()) if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': AllCorrections[det][name].SetYTitle("mm") else: AllCorrections[det][name].SetYTitle("mrad") for bin in range(detector[det].nModules()): AllCorrections[det][name].SetBinContent( bin + 1, detector[det].GetModule(bin).GetDoF(i)[1]) if showErrors: AllCorrections[det][name].SetBinError( bin + 1, detector[det].GetModule(bin).GetDoFError(i)[1]) if detector[det].nModules() < 35: AllCorrections[det][name].GetXaxis().SetBinLabel( bin + 1, detector[det].GetModule(bin).GetName()) #AllCorrections[det][name].SetMarkerStyle(20) AllCorrections[det][name].SetMarkerColor(Color[det]) AllCorrections[det][name].SetLineColor(Color[det]) AllCorrections[det][name].SetFillColor(Color[det]) AllCorrections[det][name].SetFillStyle(1001) AllCorrections[det][name].SetStats(False) if det == 0: AllCorrections[det][name].GetYaxis().SetRangeUser( -yrange[i], yrange[i]) AllCorrections[det][name].DrawCopy() else: AllCorrections[det][name].DrawCopy('same') gPad.SetGridx() gPad.SetGridy() gPad.Update() return Alldetector
def drawL3CorrVsHits(detector, det, bec): from ROOT import TCanvas from ROOT import TGraph from array import array from ROOT import gPad if det == 1: if bec == None: detname = "PIX" elif bec == 0: detname = "PIXBarrel" elif bec == -1: detname = "PIXECC" elif bec == 1: detname = "PIXECA" elif det == 2: if bec == None: detname = "SCT" elif bec == 0: detname = "SCTBarrel" elif bec == -1: detname = "SCTECC" elif bec == 1: detname = "SCTECA" L3CorrVsHits = TCanvas(detname + "CorrVsHits", detname + " Alignment Corrections vs hits") L3CorrVsHits.Divide(3, 2) hCorrVsHits = {} Color = AutoColors(len(detector)) for d in detector: hCorrVsHits[d] = {} for i in range(6): L3CorrVsHits.cd(i + 1) name, value = detector[d].GetModule(0).GetDoF(i) hname = '%s_CorrVsHits_%s_corrections' % (detname, name) htitle = '%s %s Corrections vs hits' % (detname, name) xpoints = [] ypoints = [] for j in detector[d].ReturnModules(det, bec): xpoints.append(detector[d].GetModule(j).Hits) ypoints.append(detector[d].GetModule(j).GetDoF(i)[1]) x = array("f", xpoints) y = array("f", ypoints) hCorrVsHits[d][name] = TGraph(len(x), x, y) hCorrVsHits[d][name].SetTitle(htitle) hCorrVsHits[d][name].GetXaxis().SetTitle("Hits per module") hCorrVsHits[d][name].GetYaxis().SetTitle(name) if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hCorrVsHits[d][name].GetYaxis().SetTitle(name + " (mm)") else: hCorrVsHits[d][name].GetYaxis().SetTitle(name + " (mrad)") hCorrVsHits[d][name].SetMarkerStyle(4) hCorrVsHits[d][name].SetMarkerSize(0.5) hCorrVsHits[d][name].SetMarkerColor(Color[d]) if d == 0: hCorrVsHits[d][name].Draw("Ap") else: hCorrVsHits[d][name].Draw("Ap") gPad.SetGridx() gPad.SetGridy() L3CorrVsHits.Update() return L3CorrVsHits, hCorrVsHits
def drawCorrEvolution(detector, labelList, drawErrors=False, drawLine=True, whichdof=-1, outputFormat=1): from ROOT import TCanvas from ROOT import TH1F from ROOT import gPad from ROOT import TLegend from ROOT import TLine import time import os #check with environment variable if server runs as local test runLocalTest = False try: runLocalTest = os.getenv('RUNLOCALTEST', False) except: runLocalTest = False doDebug = True showErrors = True drawAllDofs = True nUsedDofs = 7 if (whichdof != -1): drawAllDofs = False if (whichdof > 5): nUsedDofs = 7 # 7/oct/2015 with the BowX we may have up to 7 dofs. Unless stated draw the ordinary 6. lowerDof = 0 upperDof = 6 if (not drawAllDofs): lowerDof = whichdof upperDof = whichdof # output formats ALLINONE = 1 ONEBYONE = 2 SPLITBYSTRUCT = 3 Alldetector = {} # list of canvas finalName = ["", "", "", "", "", "", ""] #name of the output files gridALLENTRIES = 1 gridNEWRUN = 2 xGridType = gridNEWRUN # pathfiles = "." if (runLocalTest): pathfiles = "/Users/martis/projectes/atlas/alineament/webmonitoringtest/InDetAlignmentWebMonitor/trunk/WebPage/constant/" plotfile = {} rootSetup() # -- start the body of the code -- if (doDebug): print "\n -- drawCorrEvolution -- START -- \n" print " runLocalTest= ", runLocalTest print " pathfiles= ", pathfiles print " outputFormat= ", outputFormat # list of the histograms hCorrectionsEvol = {} hCorrectionsEvolStruct = {} # min axis range for each dof # Tx Ty Tz Rx Ry Rz Bx yrange = [0.002, 0.002, 0.002, 0.01, 0.01, 0.01, 0.002] # minimum is 0.001 (mm or mrad) # here detector = num of iterations numberOfSamples = len(detector) if (doDebug): print " -- drawCorrEvolution -- numberOfSamples=", numberOfSamples numOfAlignableStruct = detector[0].nModules() if (doDebug): print " numOfAlignableStructe=", numOfAlignableStruct EvolColor = AutoColors(numOfAlignableStruct) # a canvas for all dofs ThisCanvas = TCanvas("AlignmentCorrectionsEvol", "Evolution of alignment corrections (All)", 920, 600) if (drawAllDofs and outputFormat == ALLINONE): ThisCanvas.Divide(3, 2) # find out range #for i in range(lowerDof, upperDof): for i in range(nUsedDofs): for iter in range(numberOfSamples): for bin in range(detector[iter].nModules()): thisValue = abs(detector[iter].GetModule(bin).GetDoF( i)[1]) + detector[iter].GetModule(bin).GetDoFError(i)[1] if abs(thisValue) > yrange[i]: yrange[i] = thisValue yrange[i] *= 1.025 if (doDebug): print " dof=", i, " --> range: ", yrange[i] # # --- Y range of the plots --- cap the drawing range # maximum range maxTransRange = 0.100 if (yrange[0] > maxTransRange): yrange[0] = maxTransRange if (yrange[1] > maxTransRange): yrange[1] = maxTransRange if (yrange[2] > maxTransRange): yrange[2] = maxTransRange if (yrange[6] > maxTransRange): yrange[6] = maxTransRange #Bx # Tx and Ty should have the same range if (yrange[0] > yrange[1]): yrange[1] = yrange[0] else: yrange[0] = yrange[1] # Tz range should be as minimum as Tx and Ty if (yrange[2] < yrange[0]): yrange[2] = yrange[0] #Bx range --> keep it independent # Rx and Ry should have the same range if (yrange[3] > yrange[4]): yrange[4] = yrange[3] else: yrange[3] = yrange[4] # Rz keep it independent #yrange[0] = 0.004 yrange[1] = 0.0065 #yrange[2] = 0.040 #yrange[3] = 0.04 #yrange[4] = 0.04 #yrange[5] = 0.06 yrange[6] = 0.0025 # # prepare the legend # myLegend = TLegend(0.80, 0.85, 0.99, 0.99) myLegend.SetFillColor(0) # white # and a line to split the runs if xGridType = gridNEWRUN myGridLine = TLine() myGridLine.SetLineStyle(3) # loop dof by dof (Tx, Ty...) and fill a polyline with teh corrections for each iteration if (doDebug): print " -- drawCorrEvolution -- going to draw form lowerDof=", lowerDof, " to upperDof = ", upperDof #for dof in range(nUsedDofs): for dof in range(lowerDof, upperDof + 1): #for dof in range(lowerDof, 6): # extract dof name name = detector[0].GetModule(0).GetDoF(dof)[0] if (doDebug): print "\n -- drawCorrEvolution -- going to draw dof= %d (%s)" % ( dof, name) #dealing with canvases if (outputFormat == ALLINONE): ThisCanvas.cd() if (drawAllDofs): ThisCanvas.cd(dof + 1) if (outputFormat == ONEBYONE): Alldetector[dof] = {} Alldetector[dof] = TCanvas( "AlignCorrectionsEvol_%s" % (name), "Alignment_corrections_evolution_%s" % (name), 920, 600) print " -- drawCorrEvolution -- new canvas declared %s" % Alldetector[ dof].GetName() if (outputFormat == SPLITBYSTRUCT): Alldetector[dof] = {} Alldetector[dof] = TCanvas( "AlignCorrectionsEvol_%s_byDOF" % (name), "Alignment_corrections_evolution_%s_byDOF" % (name), 920, 600) if (numOfAlignableStruct >= 15): Alldetector[dof].Divide(5, 3) print " -- drawCorrEvolution -- Divide (5x3)" print " -- drawCorrEvolution -- new canvas declared %s for %d structures" % ( Alldetector[dof].GetName(), numOfAlignableStruct) # prepare the histogram that will store the corrections hname = 'Dof_%s_corrections_Evol' % (name) htitle = 'Evolution of %s corrections' % (name) htitle = 'Evolution of d%s/dLB corrections' % (name) if (doDebug): print " -- drawCorrEvolution -- dof= %d hname= %s" % (dof, hname) print " htitle= ", htitle # build the histogram that is the main frame to plot the corrections for this dof (evolution of dof for each sample) hCorrectionsEvol[dof] = TH1F( hname, htitle, numberOfSamples - 1, -0.5, numberOfSamples * 1. - 1.5) # the last sample is the accumulation # set the x axis labels hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.05) if (numberOfSamples > 8): # this is in case there are too many hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.04) hCorrectionsEvol[dof].GetXaxis().SetBit(18) if (numberOfSamples > 16): # reduce further the size hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.03) if (numberOfSamples > 24): # reduce further the size hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.02) hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.05) hCorrectionsEvol[dof].GetYaxis().SetLabelSize(0.05) for iter in range(numberOfSamples): hCorrectionsEvol[dof].GetXaxis().SetBinLabel( iter + 1, 'Iter_%d' % (iter)) if (len(labelList) > iter): # use label given by user hCorrectionsEvol[dof].GetXaxis().SetBinLabel( iter + 1, labelList[iter]) # label of the Y axis if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx': hCorrectionsEvol[dof].SetYTitle("mm") hCorrectionsEvol[dof].SetYTitle("dTy/dLB [mm/25LB]") else: hCorrectionsEvol[dof].SetYTitle("mrad") # set the range hCorrectionsEvol[dof].GetYaxis().SetRangeUser(-yrange[dof], yrange[dof]) hCorrectionsEvol[dof].SetStats(False) # going to draw the frame # -be ware, in case of drawing by structure need to change to the right pad if (outputFormat == ALLINONE or outputFormat == ONEBYONE): hCorrectionsEvol[dof].DrawCopy() gPad.SetGridy() if (xGridType == gridALLENTRIES): gridPad.SetGridx() # draw the frame #hCorrectionsEvol[dof].DrawCopy() #gPad.SetGridx() #gPad.SetGridy() # # once the frame is plotted, loop on every structure and fill a histogram and draw it # if (doDebug): print " -- drawCorrEvolution -- dealing with", name, "corrections. Y range for this dof: (", dof, ") range: +-", yrange[ dof] print " reminder: numOfAlignableStruct = ", numOfAlignableStruct #for struct in range(numOfAlignableStruct): for struct in range(2): if (doDebug and False): print " >> looping on struct:", struct if (outputFormat == SPLITBYSTRUCT): Alldetector[dof].cd(struct + 1) # then draw frame hCorrectionsEvol[dof].DrawCopy() gPad.SetGridy() if (xGridType == gridALLENTRIES): gridPad.SetGridx() hCorrectionsEvolStruct[dof] = {} hname = 'Dof_%s_corrections_Evol_struct_%d' % (name, struct) htitle = 'Corrections evolution for structure %s (struct %d)' % ( name, struct) hCorrectionsEvolStruct[dof][struct] = TH1F( hname, htitle, numberOfSamples - 1, -0.5, numberOfSamples * 1. - 1.5) # last point is for the accumulation --> do not show #print " -- drawCorrEvolution -- hCorrectionsEvolStruct has ",hCorrectionsEvolStruct[dof][struct].GetNbinsX(), ' bins in X' hCorrectionsEvolStruct[dof][struct].SetLineColor(EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].SetStats(False) # once the histogram is created, fill it with the corrections of each iteration currentLabel = "000000" # dummy value for iterval in range(numberOfSamples): value = detector[iterval].GetModule(struct).GetDoF(dof)[1] # derivatives if (iterval == 0): value = 0 if (iterval > 0): value = ( detector[iterval].GetModule(struct).GetDoF(dof)[1] - detector[iterval - 1].GetModule(struct).GetDoF(dof)[1]) print " iterval ", iterval, " dx=", value, " +-", detector[ iterval].GetModule(struct).GetDoFError(dof)[1] hCorrectionsEvolStruct[dof][struct].SetBinContent( iterval + 1, value) if (drawErrors): hCorrectionsEvolStruct[dof][struct].SetBinError( iterval + 1, detector[iterval].GetModule( struct).GetDoFError(dof)[1]) # check the label in case it needs to be marked if (xGridType == gridNEWRUN and len(labelList) > 0 and iterval < len(labelList)): thisLabel = labelList[iterval] if (thisLabel != currentLabel and "LB" in thisLabel): # new run found currentLabel = thisLabel #print " thisLabel = ", thisLabel," iterval = ",iterval myGridLine.DrawLine(iterval, -yrange[dof], iterval, yrange[dof]) # now draw the corrections for this structure if (drawErrors): hCorrectionsEvolStruct[dof][struct].SetFillColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].SetFillStyle(3354) # hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3') # --> original hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3') hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20) hCorrectionsEvolStruct[dof][struct].SetMarkerSize(0.5) hCorrectionsEvolStruct[dof][struct].SetMarkerColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].DrawCopy('same p e3 x0') for iterval in range(numberOfSamples): hCorrectionsEvolStruct[dof][struct].SetBinError( iterval + 1, 0) hCorrectionsEvolStruct[dof][struct].SetFillStyle(0) hCorrectionsEvolStruct[dof][struct].DrawCopy('l x0 e3 same') else: myOption = "same" if (drawLine): myOption += " l" else: myOption += " p" hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20) hCorrectionsEvolStruct[dof][struct].SetMarkerColor( EvolColor[struct]) hCorrectionsEvolStruct[dof][struct].DrawCopy(myOption) gPad.Update() #if (dof == 0 and True): if (True): if (dof == 0): myLegend.AddEntry(hCorrectionsEvolStruct[dof][struct], detector[0].GetModule(struct).GetName(), "l") myLegend.Draw() gPad.Update() t = time.time() finalName[dof] = "%f_evolution_%s" % (t, name) gPad.Update() if (outputFormat == ONEBYONE or outputFormat == SPLITBYSTRUCT): #print " -- drawCorrEvol -- saving plots from ONEBYONE " Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".png", "png") Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".pdf", "pdf") #Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".root", "root") #Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".C", "C") if (outputFormat == ALLINONE): #print " -- drawCorrEvol -- saving plots from ALLINONE " t = time.time() myFinalName = "%f_evolution_dofs" % (t) ThisCanvas.SaveAs(pathfiles + myFinalName + ".png", "png") ThisCanvas.SaveAs(pathfiles + myFinalName + ".pdf", "pdf") plotfile['png'] = {0: myFinalName + ".png"} plotfile['pdf'] = {0: myFinalName + ".pdf"} if (outputFormat == ONEBYONE or outputFormat == SPLITBYSTRUCT): plotfile['png'] = { 0: finalName[0] + ".png", 1: finalName[1] + ".png", 2: finalName[2] + ".png", 3: finalName[3] + ".png", 4: finalName[4] + ".png", 5: finalName[5] + ".png", 6: finalName[6] + ".png" } plotfile['pdf'] = { 0: finalName[0] + ".pdf", 1: finalName[1] + ".pdf", 2: finalName[2] + ".pdf", 3: finalName[3] + ".pdf", 4: finalName[4] + ".pdf", 5: finalName[5] + ".pdf", 6: finalName[6] + ".pdf" } #return plotfile return ThisCanvas
nc.cd() print colorlist[j] g.SetLineColor(colorlist[j]) g.SetMarkerColor(colorlist[j]) g.SetMarkerStyle(8) g.SetMarkerSize(0.8) g.SetTitle('') g.GetXaxis().SetTitle(ix[3]) g.GetYaxis().SetTitle(var[1]) g.GetYaxis().SetRangeUser(var[5][0], var[5][1]) graphs.append(g) nc.cd() for j, jgraph in enumerate(graphs): jgraph.Draw('AP' * (j == 0) + 'P same' * (j != 0)) if options.leg: l.AddEntry(jgraph, options.leg.split(',')[j], "pel") nc.Update() nc.Modified() if options.leg: l.Draw() gPad.SetGridx(True) gPad.SetGridy(True) nc.SaveAs('pull_resolution_plots/' + var[6] + 'vs' + ix[0] + '_Run278820_RelVal.pdf')
def mistagSFtopEMu(year_, ana_): if year_ == 2017: dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/" if year_ == 2018: dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/" print "Top Electron Region" print " " openfile1 = TFile(dir + "TopE.root") # topmatchTopE = openfile1.Get("h_TopMatch") WmatchTopE = openfile1.Get("h_Wmatch") unmatchTopE = openfile1.Get("h_unmatch") wjetsTopE = openfile1.Get("h_sumWJets") dibosonTopE = openfile1.Get("h_sumDiboson") unsubtractedDataTopE = openfile1.Get("h_Data") failMCsubtractTopE = openfile1.Get("h_ttFailed") passMCsubtractTopE = openfile1.Get("h_ttPassed") subtractedDataTopE = openfile1.Get("SubtractedData") datafailTopE = openfile1.Get("SubtractedDataFailed") datapassTopE = openfile1.Get("SubtractedDataPassed") # totaldataTopE = openfile1.Get("h_totaldata") totalMCtopE = openfile1.Get("h_tt") passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed") wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed") dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed") failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed") wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed") dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed") stTopE = openfile1.Get("h_sumST") stTopEpassed = openfile1.Get("h_sumSTPassed") stTopEfailed = openfile1.Get("h_sumSTFailed") print "Top Muon Region" print " " openfile2 = TFile(dir + "TopMu.root") # topmatchTopMu = openfile2.Get("h_TopMatch") WmatchTopMu = openfile2.Get("h_Wmatch") unmatchTopMu = openfile2.Get("h_unmatch") wjetsTopMu = openfile2.Get("h_sumWJets") dibosonTopMu = openfile2.Get("h_sumDiboson") unsubtractedDataTopMu = openfile2.Get("h_Data") failMCsubtractTopMu = openfile2.Get("h_ttFailed") passMCsubtractTopMu = openfile2.Get("h_ttPassed") subtractedDataTopMu = openfile2.Get("SubtractedData") datafailTopMu = openfile2.Get("SubtractedDataFailed") datapassTopMu = openfile2.Get("SubtractedDataPassed") # totaldataTopMu = openfile2.Get("h_totaldata") totalMCtopMu = openfile2.Get("h_tt") passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed") wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed") dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed") failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed") wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed") dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed") stTopMu = openfile2.Get("h_sumST") stTopMupassed = openfile2.Get("h_sumSTPassed") stTopMufailed = openfile2.Get("h_sumSTFailed") print "get histograms from root files: done" print " " SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE") SubtractedDataPassedTopMu = datapassTopMu.Clone( "SubtractedDataPassedTopMu") #merge histogram" print "merge histograms" print " " topmatchMerge = topmatchTopE + topmatchTopMu WmatchMerge = WmatchTopE + WmatchTopMu unmatchMerge = unmatchTopE + unmatchTopMu wjetsMerge = wjetsTopE + wjetsTopMu stMerge = stTopE + stTopMu dibosonMerge = dibosonTopE + dibosonTopMu unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge") failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge") passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu ttData_fraction = arr.array('d') ttData_error = arr.array('d') totaldataMerge = totaldataTopE + totaldataTopMu totaldata = totaldataMerge.Integral() totaldataMerge.Rebin(14) datafailMerge = datafailTopE + datafailTopMu faildata = datafailMerge.Integral() datafailMerge.Rebin(14) datafailMerge.Sumw2() datafailMerge.Divide(totaldataMerge) frac_ttData_fail = datafailMerge.Integral() ttData_fraction.append(frac_ttData_fail) ttData_error.append(datafailMerge.GetBinError(1)) datapassMerge = datapassTopE + datapassTopMu passdata = datapassMerge.Integral() datapassMerge.Rebin(14) datapassMerge.Sumw2() datapassMerge.Divide(totaldataMerge) frac_ttData_pass = datapassMerge.Integral() ttData_fraction.append(frac_ttData_pass) ttData_error.append(datapassMerge.GetBinError(1)) ttMC_fraction = arr.array('d') ttMC_error = arr.array('d') totalMCmerge = totalMCtopE + totalMCtopMu totalMCmerge.Rebin(14) MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE") MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu") MCfailMerge = MCfailTopE + MCfailTopMu MCfailMerge.Rebin(14) MCfailMerge.Sumw2() MCfailMerge.Divide(totalMCmerge) frac_Failed_fin = MCfailMerge.Integral() ttMC_fraction.append(frac_Failed_fin) ttMC_error.append(MCfailMerge.GetBinError(1)) MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE") MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu") MCpassMerge = MCpassTopE + MCpassTopMu MCpassMerge.Rebin(14) MCpassMerge.Sumw2() MCpassMerge.Divide(totalMCmerge) frac_Passed_fin = MCpassMerge.Integral() ttMC_fraction.append(frac_Passed_fin) ttMC_error.append(MCpassMerge.GetBinError(1)) #print "\nttMC_fraction:", ttMC_fraction #print "ttMC_error:", ttMC_error sfMerge = datapassMerge.Clone("sfMerge") sfMerge.Sumw2() sfMerge.Divide(MCpassMerge) stacklist = [] stacklist.append(dibosonMerge) stacklist.append(stMerge) stacklist.append(wjetsMerge) stacklist.append(unmatchMerge) stacklist.append(WmatchMerge) stacklist.append(topmatchMerge) print "merge histograms: done" print " " print "draw histograms" print " " #----------------------- canvas 1 -----------------------# c1 = TCanvas("c1", "", 800, 900) #width-height c1.SetTopMargin(0.4) c1.SetBottomMargin(0.05) c1.SetRightMargin(0.1) c1.SetLeftMargin(0.15) gStyle.SetOptStat(0) binvalues1 = [] for i in range(14): binvalue = unsubtractedDataMerge.GetBinContent(i) binvalues1.append(binvalue) totalmax = max(binvalues1) + 100 padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97) padMain.SetTopMargin(0.4) padMain.SetRightMargin(0.05) padMain.SetLeftMargin(0.17) padMain.SetBottomMargin(0.03) padMain.SetTopMargin(0.1) padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25) padRatio.SetRightMargin(0.05) padRatio.SetLeftMargin(0.17) padRatio.SetTopMargin(0.05) padRatio.SetBottomMargin(0.3) padMain.Draw() padRatio.Draw() padMain.cd() gPad.GetUymax() leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6]) unsubtractedDataMerge.SetMaximum(totalmax) unsubtractedDataMerge.SetLineColor(1) unsubtractedDataMerge.SetMarkerStyle(20) unsubtractedDataMerge.SetMarkerSize(1.5) unsubtractedDataMerge.GetXaxis().SetLabelSize(0) unsubtractedDataMerge.GetXaxis().SetTitleSize(0) unsubtractedDataMerge.GetXaxis().SetTitle("DDB") unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin") leg1.AddEntry(unsubtractedDataMerge, "Data", "lep") unsubtractedDataMerge.Draw("e1") stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821], backgroundlist_=stacklist, legendname_=[ "Diboson", "Single Top", "W+Jets", "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)" ]) stackhisto[0].Draw("histsame") unsubtractedDataMerge.Draw("e1same") stackhisto[1].Draw() leg1.Draw() lt = TLatex() lt.DrawLatexNDC(0.23, 0.85, "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}") if ana_ == "Inclusive": lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}") if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000": words = ana_.split("-") if words[2] == "2000": lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}") else: lt.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" + words[2] + " GeV}}") else: words = ana_.split("-") lt.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" + words[2] + " GeV}}") lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}") lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}") if year_ == 2017: lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}") if year_ == 2018: lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}") padRatio.cd() gPad.GetUymax() h_totalBkg = topmatchMerge.Clone("h_totalBkg") h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg) ratio.SetLineColor(1) ratio.SetLineWidth(3) ratio.SetMarkerSize(1.5) ratio.GetXaxis().SetLabelSize(0.13) ratio.GetXaxis().SetTitleOffset(1) ratio.GetXaxis().SetTitleSize(0.13) ratio.GetXaxis().SetTickLength(0.1) ratio.GetYaxis().SetLabelSize(0.12) ratio.GetYaxis().SetTitleOffset(0.5) ratio.GetYaxis().SetTitleSize(0.13) ratio.GetYaxis().SetNdivisions(405) ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}") ratio.GetXaxis().SetTitle("DDB") ratio.Draw("e1") c1.SaveAs(dir + "Merge_all.pdf") # #----------------------- canvas 2 -----------------------# c2 = myCanvas(c="c2") gPad.GetUymax() leg2 = myLegend() binvalues2 = [] for i in range(14): binvalue = subtractedDataMerge.GetBinContent(i) binvalues2.append(binvalue) ttmax = max(binvalues2) + 50 failMCsubtractMerge.SetMaximum(ttmax) failMCsubtractMerge.SetFillColor(821) failMCsubtractMerge.SetLineColor(821) #922 failMCsubtractMerge.GetXaxis().SetTitle("DDB") failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin") leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f") passMCsubtractMerge.SetFillColor(622) passMCsubtractMerge.SetLineColor(622) #passMCsubtractMerge.GetXaxis().SetTitle("DDB") #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin") leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f") subtractedDataMerge.SetLineColor(1) subtractedDataMerge.SetMarkerStyle(20) subtractedDataMerge.SetMarkerSize(1.5) #subtractedDataMerge.GetXaxis().SetTitle("DDB") #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin") leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep") failMCsubtractMerge.Draw("hist") passMCsubtractMerge.Draw("histsame") subtractedDataMerge.Draw("e1same") leg2.Draw() lt2 = TLatex() if ana_ == "Inclusive": lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}") if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000": words = ana_.split("-") if words[2] == "2000": lt2.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}") else: lt2.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" + words[2] + " GeV}}") else: words = ana_.split("-") lt2.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" + words[2] + " GeV}}") lt2.DrawLatexNDC(0.23, 0.85, "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}") lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}") lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}") if year_ == 2017: lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}") if year_ == 2018: lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}") c2.SaveAs(dir + "Merged_subtrac.pdf") # #----------------------- canvas 3 -----------------------# c3 = myCanvas(c="c3", size=[700, 900]) pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0) pad1.SetTopMargin(0.1) pad1.SetRightMargin(0.05) pad1.SetLeftMargin(0.17) pad1.SetBottomMargin(0.05) pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24) pad2.SetTopMargin(0.0) pad2.SetRightMargin(0.0) pad2.SetLeftMargin(0.0) pad2.SetBottomMargin(0.0) pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25) pad2.SetTopMargin(0.05) pad2.SetRightMargin(0.0) pad2.SetLeftMargin(0.45) pad2.SetBottomMargin(0.2) pad1.Draw() pad2.Draw() pad3.Draw() #* Pad 1 *# pad1.cd() leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5]) xaxisname = arr.array('d', [1, 2]) zero1 = np.zeros(2) gPad.Modified() gPad.SetGridy() gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error) gr1.SetTitle("t#bar{t}") gr1.SetLineColor(870) gr1.SetLineWidth(3) gr1.SetMarkerStyle(20) gr1.SetMarkerColor(870) leg3.AddEntry(gr1, "t#bar{t}", "lep") gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error) gr2.SetTitle("t#bar{t} Data") gr2.SetLineColor(1) gr2.SetLineWidth(2) gr2.SetMarkerStyle(20) gr2.SetMarkerColor(1) leg3.AddEntry(gr2, "t#bar{t} Data", "lep") mg = TMultiGraph("mg", "") mg.Add(gr1) mg.Add(gr2) mg.GetHistogram().SetMaximum(1.5) mg.GetHistogram().SetMinimum(0) mg.GetYaxis().SetTitle("Fraction") mg.GetXaxis().SetLimits(0, 3) mg.GetXaxis().SetTickLength(0.03) mg.GetXaxis().SetNdivisions(103) mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail") mg.GetXaxis().ChangeLabel(1, -1, 0) mg.GetXaxis().ChangeLabel(-1, -1, 0) mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass") mg.Draw("AP") leg3.Draw() lt3 = TLatex() if ana_ == "Inclusive": lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}") if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000": words = ana_.split("-") if words[2] == "2000": lt3.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}") else: lt3.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" + words[2] + " GeV}}") else: words = ana_.split("-") lt3.DrawLatexNDC( 0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" + words[2] + " GeV}}") lt3.DrawLatexNDC(0.19, 0.855, "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}") lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}") lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}") if year_ == 2017: lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}") if year_ == 2018: lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}") lt3.Draw() pad1.Update() #* Pad 2 *# pad2.cd() MCpassMerge.SetFillColor(0) MCpassMerge.SetLineColor(870) MCpassMerge.SetLineWidth(3) MCpassMerge.SetMarkerColor(870) MCpassMerge.SetMarkerStyle(20) MCpassMerge.GetYaxis().SetTitle("Fraction") MCpassMerge.GetYaxis().SetTitleSize(0.09) MCpassMerge.GetYaxis().SetLabelSize(0.1) MCpassMerge.GetYaxis().SetNdivisions(404) MCpassMerge.SetMaximum(0.3) MCpassMerge.SetMinimum(0.0) MCpassMerge.GetXaxis().SetTitle("") MCpassMerge.GetXaxis().SetLabelOffset(0.02) MCpassMerge.GetXaxis().SetLabelSize(0.09) MCpassMerge.GetXaxis().SetNdivisions(104) MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass") MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0) MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0) datapassMerge.SetFillColor(0) datapassMerge.SetLineColor(1) datapassMerge.SetLineWidth(2) datapassMerge.SetMarkerColor(1) datapassMerge.SetMarkerStyle(20) MCpassMerge.Draw("e1") datapassMerge.Draw("e1histsame") #* Pad 3 *# pad3.cd() SF = sfMerge.Integral() print "******" print "mistag SF:", SF SFfinal = round(SF, 3) SFtext = "SF = " + str(SFfinal) mistagSFmax = SF + 0.2 mistagSFmin = SF - 0.2 sfMerge.SetLineColor(797) sfMerge.SetMarkerColor(797) sfMerge.SetLineWidth(3) sfMerge.SetMaximum(mistagSFmax) sfMerge.SetMinimum(mistagSFmin) sfMerge.GetXaxis().SetTitle(" ") sfMerge.GetXaxis().SetLabelOffset(999) sfMerge.GetXaxis().SetLabelSize(0) sfMerge.GetXaxis().SetTickLength(0) sfMerge.GetYaxis().SetLabelSize(0.1) sfMerge.GetYaxis().SetNdivisions(404) sfMerge.GetYaxis().SetTitle(" ") sfMerge.Draw("e1hist") pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(42) pt.SetTextSize(0.1) pt.AddText(SFtext) pt.Draw() c3.SaveAs(dir + "Merge_SF.pdf") # passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract + passedTopMudataBfrSubtract).Integral() failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract + failedTopMudataBfrSubtract).Integral() passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed + dibosonTopMupassed + stTopEpassed + stTopMupassed).Integral() failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed + dibosonTopMufailed + stTopEfailed + stTopMufailed).Integral() totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral() #get the statistical uncertainty# dx = ttData_error[1] print "data efficiency error", dx dy = ttMC_error[1] print "MC efficiency error", dy x = datapassMerge.Integral() y = MCpassMerge.Integral() statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4))) #print "statistical Uncertainty in Top (e+muon) CR", statUnc #print " " print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %" print " " print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc, 3), " (stat)" #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral())) #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral())) #print " " header = ["Process", "Number of Events", "Top (e+muon)"] row1 = [ " ", "DDB mistag SF", str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)" ] row2 = ["tt MC", "Pass (not normalized)", ""] row3 = [ " ", "Pass (normalized)", str(round(passMCsubtractMerge.Integral(), 2)) ] row4 = [" ", "Fail (not normalized)", ""] row5 = [ " ", "Fail (normalized)", str(round(failMCsubtractMerge.Integral(), 2)) ] row6 = [" ", "Total (not normalized)", ""] row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))] inforMC = [row2, row3, row4, row5, row6, row7] row8 = [ "tt DATA", "Pass (before subtraction)", str(round(passedBfrSubtactDataMerge, 2)) ] row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))] row10 = [ " ", "Fail (before subtraction)", str(round(failedBfrSubtractDataMerge, 2)) ] row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))] row12 = [ " ", "Total (before subtraction)", str(round(unsubtractedDataMerge.Integral(), 2)) ] row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))] inforDATA = [row8, row9, row10, row11, row12, row13] row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))] row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))] row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))] inforBKG = [row14, row15, row16] DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
c = TCanvas('f2r_test', 'f2r Test', 600, 400) gStyle.SetPalette(1) gStyle.SetOptStat(0) gStyle.SetOptFit(0) # make a test plot and store plots in file for plot in plots: if plot.get_type() == '1DPLOT': if PLOT1D: plot.get_histo().Draw('P') plot.get_histo().Write() if plot.get_type() == '2DPLOT': if PLOT2D: gPad.SetLogz() gPad.SetGridx() gPad.SetGridy() plot.get_histo().Draw('COLZ') plot.get_histo().Write() if plot.get_type() == '3DPLOT': if PLOT3D: gPad.SetLogz() gPad.SetGridx() gPad.SetGridy() hist = plot.get_histo() for i in range(4): hist[i].Draw() raw_input('Close the window and press enter') hist[i].Write() file.Close()
defVeto_type = "%s_%s" % (iDefVeto, iSuffix) if (defVeto_type in h1Run_diffTwoYT.keys() and h1Run_diffTwoYT[defVeto_type].GetEntries() != 0): leg_diffTwoYT[defOrVeto_type].AddEntry( h1_diffTwoYT[defVeto_type], "#splitline{%s: %d runs}{Underflow: %d Overflow: %d}" % (defectVeto["description"][iDefVeto], h1_diffTwoYT[defVeto_type].GetEntries(), h1_diffTwoYT[defVeto_type].GetBinContent(0), h1_diffTwoYT[defVeto_type].GetBinContent( h1_diffTwoYT[defVeto_type].GetNbinsX() + 1)), "P") if (first): gPad.SetGridy(1) h1Run_diffTwoYT[defVeto_type].SetMinimum( -1.2 * maxAbsLumiDiff[defOrVeto_type]) h1Run_diffTwoYT[defVeto_type].SetMaximum( 1.2 * maxAbsLumiDiff[defOrVeto_type]) h1Run_diffTwoYT[defVeto_type].Draw("L") c_diffTwoYT[defOrVeto_type].cd(2) gPad.SetGrid(1) h1_diffTwoYT[defVeto_type].Draw("L") first = False else: h1Run_diffTwoYT[defVeto_type].Draw("L SAME") c_diffTwoYT[defOrVeto_type].cd(2) h1_diffTwoYT[defVeto_type].Draw("L SAME") c_diffTwoYT[defOrVeto_type].cd(2)
def MakeOneDHist(histogramName,integrateDir): HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC") LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) NormLabel = TPaveLabel() NormLabel.SetDrawOption("NDC") NormLabel.SetX1NDC(topLeft_x_left) NormLabel.SetX2NDC(topLeft_x_right) NormLabel.SetBorderSize(0) NormLabel.SetFillColor(0) NormLabel.SetFillStyle(0) NormText = "" if arguments.normalizeToUnitArea: NormText = "Scaled to unit area" Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) canvasName = histogramName if integrateDir is "left": canvasName += "_CumulativeLeft" elif integrateDir is "right": canvasName += "_CumulativeRight" Canvas = TCanvas(canvasName) Histograms = [] LegendEntries = [] colorIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset']) inputFile = TFile(dataset_file) if arguments.generic: HistogramObj = inputFile.Get(source['channel'] + "/" +histogramName) else: HistogramObj = inputFile.Get("OSUAnalysis/" + source['channel'] + "/" +histogramName) if not HistogramObj: print "WARNING: Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = HistogramObj.Clone() Histogram.SetDirectory(0) inputFile.Close() if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1: Histogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") xAxisLabelVar = xAxisLabel if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] xAxisLabelVar = xAxisLabel[0:unitBeginIndex] else: yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" if arguments.normalizeToUnitArea and arguments.makeSignificancePlots: unit = "Efficiency" else: unit = "Yield" if integrateDir is "left": yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" if integrateDir is "right": yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)" if not arguments.makeFancy and not arguments.generic: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") # print splitTitle histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] Histogram.SetMarkerStyle(markerStyle) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) if arguments.normalizeToUnitArea and Histogram.Integral() > 0: Histogram.Scale(1./Histogram.Integral()) Histogram = MakeIntegralHist(Histogram, integrateDir) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") legendIndex = legendIndex+1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 for histogram in Histograms: currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin()) if(currentMax > finalMax): finalMax = currentMax finalMax = 1.5*finalMax if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots #makeSignifPlots = arguments.makeSignificancePlots yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.generic: plotting_options = "p,e" if arguments.plot_hist: plotting_options = "HIST" for histogram in Histograms: histogram.SetTitle(histoTitle) if arguments.verbose: print "Debug: drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor()) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: plotting_options = plotting_options + " SAME" histCounter = histCounter + 1 #legend coordinates, empirically determined :-) x_left = 0.1677852 x_right = 0.9647651 y_min = 0.6765734 y_max = 0.9 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() # Deciding which text labels to draw and drawing them drawHeaderLabel = False if arguments.makeFancy: drawHeaderLabel = True #now that flags are set, draw the appropriate labels if drawHeaderLabel: HeaderLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: if arguments.ratioRelErrMax: Comparison = ratioHistogram(Histograms[0],Histograms[1],float(arguments.ratioRelErrMax)) else: Comparison = ratioHistogram(Histograms[0],Histograms[1]) elif makeDiffPlots: Comparison = Histograms[0].Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("hist1-hist2") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") outputFile.cd() Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")