def createMuon2Plot(dset, name, postfix): datasetName = dset.getName() treeDraw = dataset.TreeDraw("tree", selection="Obj2Type == 3 && LeptonVetoStatus == 0 && (TauIDStatus == 1 || TauIDStatus == 2 || TauIDStatus == 3)") # nothing passes lepton veto tdFullIsolation = treeDraw.clone(varexp="(muon2_f_chargedHadronIso + max(muon2_f_photonIso+muon2_f_neutralHadronIso-0.5*muon2_f_puChargedHadronIso, 0))/muon2_p4.Pt() >>tmp(50, 0, 0.5)") tdChargedIsolation = treeDraw.clone(varexp="(muon2_f_chargedHadronIso)/muon2_p4.Pt() >>tmp(50, 0, 0.5)") tdNeutralIsolation = treeDraw.clone(varexp="(max(muon2_f_photonIso+muon2_f_neutralHadronIso-0.5*muon2_f_puChargedHadronIso, 0))/muon2_p4.Pt() >>tmp(50, 0, 0.5)") h = dset.getDatasetRootHisto(tdFullIsolation).getHistogram() p = plots.PlotBase([histograms.Histo(h, "histo")]) p.createFrame("muon2fullIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save() h = dset.getDatasetRootHisto(tdChargedIsolation).getHistogram() integralAll = h.Integral(0, h.GetNbinsX()+1) integral = h.Integral(0, h.FindBin(0.1)+1) p = plots.PlotBase([histograms.Histo(h, "histo")]) p.appendPlotObject(histograms.PlotText(0.5, 0.55, "%d events in total" % int(integralAll))) p.appendPlotObject(histograms.PlotText(0.5, 0.5, "%d events in <= 0.1" % int(integral))) p.createFrame("muon2chargedIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save() h = dset.getDatasetRootHisto(tdNeutralIsolation).getHistogram() p = plots.PlotBase([histograms.Histo(h, "histo")]) p.createFrame("muon2neutralIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save()
def compare(raw, type1, quantity, name): rawTh1 = raw.histoMgr.getHisto(name).getRootHisto().Clone("Raw") type1Th1 = type1.histoMgr.getHisto(name).getRootHisto().Clone("Type1") styles.dataStyle.apply(rawTh1) styles.mcStyle.apply(type1Th1) plot = plots.ComparisonPlot( histograms.Histo(rawTh1, "Raw"), histograms.Histo(type1Th1, "Type 1") ) q = " "+quantity if quantity == "Et": q = "" plot.setLegend(histograms.moveLegend(histograms.createLegend(), dh=0.15)) plot.createFrame("metres_%s_%s" % (name, quantity)) plot.frame.GetXaxis().SetTitle("MET%s/genMET%s" % (q, q)) plot.frame.GetYaxis().SetTitle("Events / %.2f" % raw.binWidth()) plot.draw() l = ROOT.TLatex() l.SetNDC() x = 0.5 y = 0.7 dy = 0.05 l.DrawLatex(x, y, name); y -= dy l.SetTextSize(l.GetTextSize()*0.7) l.SetTextColor(rawTh1.GetLineColor()) l.DrawLatex(x, y, "Raw mean %.2f, stddev %.2f" % (rawTh1.GetMean(), rawTh1.GetRMS())); y -= dy l.SetTextColor(type1Th1.GetLineColor()) l.DrawLatex(x, y, "Type 1 mean %.2f, stddev %.2f" % (type1Th1.GetMean(), type1Th1.GetRMS())); y -= dy plot.save()
def plotHisto(self, histo, canvasName): plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName())) plot.createFrame(canvasName + self.label, opts={ "ymin": 0.1, "ymaxfactor": 2. }) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) plot.getPad().SetLogy(True) integralValue = int(0.5 + histo.Integral(0, histo.GetNbinsX(), "width")) print histo.GetName(), "Integral", histo.Integral( 0, histo.GetNbinsX(), "width") histograms.addText(0.4, 0.7, "Integral = %s ev" % integralValue) match = re.search("aseline", histo.GetName()) if match: self.nBaseQCD = integralValue match = re.search("nverted", histo.GetName()) if match: self.nInvQCD = integralValue self.plotIntegral(plot, histo.GetName())
def doQcdPurPlots(p, drawPlot, datasets, hExpr, hName, xLabel, yLabel, SaveExtension): if getBool("bRemoveEwk"): print "*** WARNING: No Ewk samples found. Skipping QCD Purity plots." return histograms.createLegend.setDefaults(x1=xLegMin * (0.90), x2=xLegMax * (0.95), y1=yLegMin, y2=yLegMax * 1.2) saveName = "%s_%s" % (hName, SaveExtension + "_QcdPurity") ### Setup the histogram text mode and create plot p2 = createTH1Plot(datasets, hExpr, normalizeToOne=False) ### Define the purity histogram binning Bins = [40.0, 50.0, 60.0, 70.0, 80.0, 100.0, 120.0, 150.0, 200.0] myBins = array.array('d', Bins) ### Loop over all histograms to determine the number of signal and bkg events to calculate qcdPurity for htmp in p.histoMgr.getHistos(): name = htmp.getName() h = htmp.getRootHisto().Rebin(len(myBins) - 1, name, myBins) htmp.setRootHisto(h) if (name in "Data"): hQcdPur = p.histoMgr.getHisto("Data").getRootHisto().Clone( "hQcdPur") p2.histoMgr.removeHisto(name) elif (name in ["TTToHplus", "QCD"]): p2.histoMgr.removeHisto(name) else: hQcdPur.Add(h, -1) p2.histoMgr.removeHisto(name) hQcdPur.Divide(p.histoMgr.getHisto("Data").getRootHisto()) Purity = histograms.Histo(setQcdPurityHistoStyle(hQcdPur), "Purity = #frac{Data-Ewk MC}{Data}", "", "") p2.histoMgr.appendHisto(Purity) ### Draw the plot with custom options and save drawPlot = plots.PlotDrawer(stackMCHistograms=getBool("bStackHistos"), addMCUncertainty=getBool("bAddMCUncertainty"), log=False, ratio=getBool("bStackHistos"), addLuminosityText=getBool("bAddLumiText"), opts={ "ymin": yMinPurity, "ymax": yMaxPurity }) drawPlot(p2, saveName, rebin=1, xlabel=xLabel, ylabel=yLabel) return
def __init__(self, plot): plots.PlotBase.__init__(self, [], plot.saveFormats) with SetTH1Directory(False): for histo in plot.histoMgr.getHistos(): hpass = dist2pass(histo.getRootHisto()) h = histograms.Histo(histo.getDataset(), hpass, histo.getName()) self.histoMgr.appendHisto(h) self.histoMgr.setHistoDrawStyleAll("P") self.histoMgr.setHistoLegendStyleAll("P") self._setLegendLabels() self._setPlotStyles()
def createPlot(graph_, **kwargs): if isinstance(graph_, ROOT.TH1): defaults = {"legendStyle": "l"} defaults.update(kwargs) graph_.GetZaxis().SetTitle("") #### return plots.PlotBase([histograms.HistoBase(graph_, "efficiency", **defaults)]) return plots.PlotBase( [histograms.Histo(graph_, "efficiency", **defaults)]) else: defaults = {"drawStyle": "EP"} defaults.update(kwargs) return plots.PlotBase( [histograms.HistoGraph(graph_, "efficiency", **defaults)])
def getPlots(opts, histoName, dsetMgr, myDir, luminosity, myHistograms, samples): def handleOverflow(h): h.SetBinContent(1, h.GetBinContent(0) + h.GetBinContent(1)) h.SetBinError(1, math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2)) h.SetBinContent( h.GetNbinsX() + 1, h.GetBinContent(h.GetNbinsX() + 1) + h.GetBinContent(h.GetNbinsX() + 2)) h.SetBinError( h.GetNbinsX() + 1, math.sqrt( h.GetBinError(h.GetNbinsX() + 1)**2 + h.GetBinError(h.GetNbinsX() + 2)**2)) h.SetBinContent(0, 0.0) h.SetBinError(0, 0.0) h.SetBinContent(h.GetNbinsX() + 2, 0.0) h.SetBinError(h.GetNbinsX() + 2, 0.0) for sample in samples: dseth = dsetMgr.getDataset(sample).getDatasetRootHisto(histoName) dseth.normalizeToLuminosity(luminosity) h = dseth.getHistogram() # Get short name mySplit = histoName.split("/") histoNameShort = mySplit[len(mySplit) - 1] # Rebin and handle overflow if histoName.startswith("shape"): h = h.Rebin(2) #myBinning = systematics.getBinningForPlot(histoNameShort) #myArray = array.array("d",myBinning) #h = h.Rebin(len(myBinning)-1,"",myArray) handleOverflow(h) # Plot h.SetLineColor(styles.styles[len(myHistograms)].color) h.SetMarkerColor(styles.styles[len(myHistograms)].color) h.SetMarkerStyle(styles.styles[len(myHistograms)].marker) # Remove stat uncert if optionRemoveStatUncert: for i in range(1, h.GetNbinsX() + 1): h.SetBinError(i, 0.0) myMass = sample.split("_") histo = histograms.Histo(h, "H^{+}, m=%s" % myMass[len(myMass) - 1].replace("M", ""), drawStyle="", legendStyle="lp") myHistograms.append(histo)
def createDrawPlot(name, h): h.SetMarkerSize(800) p = plots.PlotBase([histograms.Histo(h, "histo", drawStyle="TEXT")]) p.createFrame(name, opts={"ymaxfactor": 1, "nbinsx": h.GetNbinsX(), "nbinsy": h.GetNbinsY(), }) for bin in xrange(1, h.GetNbinsX()+1): p.frame.GetXaxis().SetBinLabel(bin, h.GetXaxis().GetBinLabel(bin)) for bin in xrange(1, h.GetNbinsY()+1): p.frame.GetYaxis().SetBinLabel(bin, h.GetYaxis().GetBinLabel(bin)) p.draw() p.save()
def plotDataEwkDiff(mT, name): data = dataEwkDiff(mT, name) # Draw the subtracted plot plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(data, "Data-EWK")) plot.createFrame(name, opts={"ymin": 1e-1, "ymaxfactor": 10}) plot.frame.GetXaxis().SetTitle("MET (GeV)") plot.frame.GetYaxis().SetTitle("Data - EWK") # Set Y axis to logarithmic plot.getPad().SetLogy(True) plot.draw() # Add the various texts to plot.addStandardTexts() plot.save()
def plot(datasets): # datasetName = "TTJets_TuneZ2_Summer11" # datasetName = "TTToHplusBWB_M120_Summer11" datasetName = "WJets_TuneZ2_Summer11" den_selection = "jets_p4.Pt()>30 && ( abs(jets_flavour) < 4 || jets_flavour > 20)" # den_selection = "jets_p4.Pt()>30" num_selection = den_selection + "&&jets_btag>1.7" ds = datasets.getDataset(datasetName) den = ds.getDatasetRootHisto( treeDraw.clone(varexp="jets_p4.Pt()>>dist1(100,0.,500.)", selection=den_selection)).getHistogram() num = ds.getDatasetRootHisto( treeDraw.clone(varexp="jets_p4.Pt()>>dist2(100,0.,500.)", selection=num_selection)).getHistogram() canvas = ROOT.TCanvas("canvas", "", 500, 700) canvas.Divide(1, 3) canvas.cd(1) den.Draw() canvas.cd(2) num.Draw() canvas.cd(3) # eff = ROOT.TEfficiency(num,den) eff = num.Clone() eff.Divide(den) eff.Draw() canvas.Print("canvas.C") plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(eff, eff.GetName())) plot.createFrame("BtaggingEff", opts={"ymin": 0.1, "ymaxfactor": 2.}) plot.frame.GetXaxis().SetTitle("jet E_{T} (GeV)") plot.frame.GetYaxis().SetTitle("B-tagging eff.") histograms.addText(0.2, 0.8, "MC: " + datasetName, 25) plot.addStandardTexts() plot.draw() plot.save()
def purityGraph(i, datasets, histo): inverted = plots.DataMCPlot(datasets, histo) # inverted.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(5)) inverted.histoMgr.forEachHisto( lambda h: h.setRootHisto(h.getRootHisto().Rebin( len(binning) - 1, h.getRootHisto().GetName(), array.array('d', binning)))) invertedData = inverted.histoMgr.getHisto("Data").getRootHisto().Clone( histo) invertedData.Scale(QCDInvertedNormalization["inclusive"]) invertedEWK = inverted.histoMgr.getHisto("EWK").getRootHisto().Clone(histo) invertedEWK.Scale(QCDInvertedNormalization["inclusiveEWK"]) numerator = invertedData.Clone() numerator.SetName("numerator") numerator.Add(invertedEWK, -1) denominator = invertedData.Clone() denominator.SetName("denominator") numerator.Divide(denominator) purityGraph = ROOT.TGraphAsymmErrors(numerator) """ purity = ROOT.TEfficiency(numerator,denominator) purity.SetStatisticOption(ROOT.TEfficiency.kFNormal) collection = ROOT.TObjArray() collection.Add(purity) weights = [] weights.append(1) purityGraph = ROOT.TEfficiency.Combine(collection,"",len(weights),array.array("d",weights)) """ purityGraph.SetMarkerStyle(20 + i) purityGraph.SetMarkerColor(2 + i) if i == 3: purityGraph.SetMarkerColor(6) defaults = {"drawStyle": "EP", "legendStyle": "p"} return histograms.Histo(purityGraph, "Purity%s" % i, **defaults)
def __init__(self, passedPlots, names, legendLabels={}): plots.PlotBase.__init__(self, [], passedPlots[0].saveFormats) legends = { "sumIsoRel": "Rel iso", "pfSumIsoRel": "PF rel iso", } legends.update(legendLabels) with SetTH1Directory(False): rootHistos = [] for plot, name in zip(passedPlots, names): mcSum = histograms.sumRootHistos([getSumOrRootHisto(histo) for histo in filter(lambda h: h.isMC(), plot.histoMgr.getHistos())]) qcdHisto = plot.histoMgr.getHisto("QCD_Pt20_MuEnriched") qcd = getSumOrRootHisto(qcdHisto).Clone(name+"_QCDfraction") qcd.Divide(mcSum) # qcd/mcSum h = histograms.Histo(qcdHisto.getDataset(), qcd, name) h.setLegendLabel(legends.get(name, "")) self.histoMgr.appendHisto(h) self.histoMgr.forEachHisto(styles.generator()) self.histoMgr.setHistoLegendStyleAll("l")
def doPlot(datasetsEmb, analyses, path, name, text): histos = [] legends = { "Plus": "#tau-jet energy scale variated by +3 %", "Minus": "#tau-jet energy scale variated by -3 %" } for aname, analysis in analyses: (rootHisto, tmp) = datasetsEmb.getHistogram("Data", analysis + "/" + path) h = histograms.Histo(rootHisto, aname) h.setLegendLabel(legends.get(aname, aname)) h.setDrawStyle("EP") h.setLegendStyle("p") histos.append(h) p = plots.ComparisonManyPlot(histos[0], histos[1:]) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20)) styles.dataStyle(p.histoMgr.getHisto("Baseline")) styles.mcStyle(p.histoMgr.getHisto("Plus")) styles.mcStyle2(p.histoMgr.getHisto("Minus")) p.histoMgr.getHisto("Minus").getRootHisto().SetMarkerSize(2) p.setLuminosity(datasetsEmb.getLuminosity()) p.createFrame(name, createRatio=True, opts2={"ymax": 2}, opts={"ymax": 35}) yaxis = p.getFrame2().GetYaxis() yaxis.SetTitle("Ratio") #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.8) p.setLegend(histograms.moveLegend(histograms.createLegend())) p.appendPlotObject(histograms.PlotText(0.5, 0.55, text, size=20)) p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})") p.frame.GetYaxis().SetTitle("Events / 20 GeV/c^{2}") p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.addLuminosityText() p.save()
def doPurityPlots(opts, histoName, dsetMgr, moduleInfoString, myDir, luminosity, myShapePurityHistograms): def handleOverflow(h): h.SetBinContent(1, h.GetBinContent(0) + h.GetBinContent(1)) h.SetBinError(1, math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2)) h.SetBinContent( h.GetNbinsX() + 1, h.GetBinContent(h.GetNbinsX() + 1) + h.GetBinContent(h.GetNbinsX() + 2)) h.SetBinError( h.GetNbinsX() + 1, math.sqrt( h.GetBinError(h.GetNbinsX() + 1)**2 + h.GetBinError(h.GetNbinsX() + 2)**2)) h.SetBinContent(0, 0.0) h.SetBinError(0, 0.0) h.SetBinContent(h.GetNbinsX() + 2, 0.0) h.SetBinError(h.GetNbinsX() + 2, 0.0) myQCDShape = DataDrivenQCDShape(dsetMgr, "Data", "EWK", histoName, luminosity) mySplit = histoName.split("/") histoName = mySplit[len(mySplit) - 1] # Get data and EWK histograms hData = myQCDShape.getIntegratedDataHisto() hEWK = myQCDShape.getIntegratedEwkHisto() # Rebin and handle overflow if "EWKGenuineTaus" in histoName: myBinning = [0, 20, 40, 60, 80, 100, 120, 140, 160, 200, 300, 700] else: myBinning = systematics.getBinningForPlot( histoName) #(histoName.replace("EWKGenuineTaus","")) myArray = array.array("d", myBinning) hData = hData.Rebin(len(myBinning) - 1, "", myArray) hEWK = hEWK.Rebin(len(myBinning) - 1, "", myArray) handleOverflow(hData) handleOverflow(hEWK) # Create purity histo hPurity = aux.Clone(hData) hPurity.Reset() # Calculate purity for i in xrange(1, hPurity.GetNbinsX() + 1): myPurity = 0.0 myUncert = 0.0 nData = hData.GetBinContent(i) nEWK = hEWK.GetBinContent(i) if (nData > 0.0): myPurity = (nData - nEWK) / nData if myPurity < 0.0: myPurity = 0.0 myUncert = 0.0 else: myUncert = sqrt(myPurity * (1.0 - myPurity) / nData) # Assume binomial error hPurity.SetBinContent(i, myPurity) hPurity.SetBinError(i, myUncert) # Find out tail killer scenario myScenario = "" if "QCDTailKillerLoose" in moduleInfoString: myScenario = "Loose" elif "QCDTailKillerMedium" in moduleInfoString: myScenario = "Medium" if "QCDTailKillerTight" in moduleInfoString: myScenario = "Tight" myScenario += " R_{bb}^{min.}" # Make histogram hPurity.SetLineColor(styles.styles[len(myShapePurityHistograms)].color) hPurity.SetMarkerColor(styles.styles[len(myShapePurityHistograms)].color) hPurity.SetMarkerStyle(styles.styles[len(myShapePurityHistograms)].marker) # Plot histo = histograms.Histo(hPurity, myScenario, drawStyle="", legendStyle="lp") myShapePurityHistograms.append(histo)
def fitData(self, histo): parInvQCD = self.parInvQCD parMCEWK = self.parMCEWK nInvQCD = self.nInvQCD nFitInvQCD = self.nFitInvQCD nMCEWK = self.nMCEWK class FitFunction: def __call__(self, x, par): return par[0] * ( par[1] * QCDFunction(x, parInvQCD, 1 / nFitInvQCD) + (1 - par[1]) * EWKFunction(x, parMCEWK, 1 / nMCEWK)) class QCDOnly: def __call__(self, x, par): return par[0] * par[1] * QCDFunction(x, parInvQCD, 1 / nFitInvQCD) rangeMin = histo.GetXaxis().GetXmin() rangeMax = histo.GetXaxis().GetXmax() numberOfParameters = 2 print "Fit range ", rangeMin, " - ", rangeMax theFit = TF1("theFit", FitFunction(), rangeMin, rangeMax, numberOfParameters) plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName())) plot.createFrame("combinedfit" + self.label, opts={ "ymin": 1e-5, "ymaxfactor": 2. }) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) print "data events ", histo.Integral(0, histo.GetNbinsX()) histo.Fit(theFit, "R") theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax()) theFit.SetLineStyle(2) theFit.Draw("same") par = theFit.GetParameters() qcdOnly = TF1("qcdOnly", QCDOnly(), rangeMin, rangeMax, numberOfParameters) qcdOnly.FixParameter(0, par[0]) qcdOnly.FixParameter(1, par[1]) qcdOnly.SetLineStyle(2) qcdOnly.Draw("same") histograms.addText(0.35, 0.8, "Data, Baseline TauID") histograms.addText(0.4, 0.3, "QCD", 15) plot.histoMgr.appendHisto(histograms.Histo(qcdOnly, "qcdOnly")) plot.getPad().SetLogy(True) plot.draw() plot.save() fitPars = "fit parameters " i = 0 while i < numberOfParameters: fitPars = fitPars + " " + str(par[i]) i = i + 1 print fitPars nBaseQCD = par[0] self.QCDfraction = par[1] if len(self.label) > 0: print "Bin ", self.label print "Integral ", nBaseQCD print "QCD fraction ", self.QCDfraction return theFit
def fitEWK(self, histo, options="R"): rangeMin = histo.GetXaxis().GetXmin() rangeMax = histo.GetXaxis().GetXmax() # rangeMin = 120 # rangeMax = 120 numberOfParameters = 4 print "Fit range ", rangeMin, " - ", rangeMax class FitFunction: def __call__(self, x, par): return EWKFunction(x, par, 1, 1) # return SumFunction(x,par) # return TestFunction(x,par,1) class PlotFunction: def __call__(self, x, par): return EWKFunction(x, par, 0) theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax, numberOfParameters) thePlot = TF1('thePlot', PlotFunction(), rangeMin, rangeMax, numberOfParameters) theFit.SetParLimits(0, 5, 30) theFit.SetParLimits(1, 90, 120) theFit.SetParLimits(2, 30, 50) theFit.SetParLimits(3, 0.001, 1) if self.label == "4050": theFit.SetParLimits(0, 5, 20) theFit.SetParLimits(1, 90, 120) theFit.SetParLimits(2, 30, 50) theFit.SetParLimits(3, 0.001, 1) if self.label == "5060": theFit.SetParLimits(0, 5, 20) theFit.SetParLimits(1, 90, 120) theFit.SetParLimits(2, 20, 50) theFit.SetParLimits(3, 0.001, 1) if self.label == "6070": theFit.SetParLimits(0, 5, 50) theFit.SetParLimits(1, 90, 150) theFit.SetParLimits(2, 20, 50) theFit.SetParLimits(3, 0.001, 1) if self.label == "7080": theFit.SetParLimits(0, 5, 60) theFit.SetParLimits(1, 90, 200) theFit.SetParLimits(2, 20, 100) theFit.SetParLimits(3, 0.001, 1) if self.label == "80100": theFit.SetParLimits(0, 5, 50) theFit.SetParLimits(1, 50, 170) theFit.SetParLimits(2, 20, 60) theFit.SetParLimits(3, 0.001, 1) if self.label == "100120": theFit.SetParLimits(0, 5, 50) theFit.SetParLimits(1, 90, 170) theFit.SetParLimits(2, 20, 60) theFit.SetParLimits(3, 0.001, 1) if self.label == "120150": theFit.SetParLimits(0, 5, 50) theFit.SetParLimits(1, 60, 170) theFit.SetParLimits(2, 10, 100) theFit.SetParLimits(3, 0.001, 1) if self.label == "150": theFit.SetParLimits(0, 5, 50) theFit.SetParLimits(1, 70, 170) theFit.SetParLimits(2, 20, 100) theFit.SetParLimits(3, 0.001, 1) plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName())) plot.createFrame("ewkfit" + self.label, opts={ "ymin": 1e-5, "ymaxfactor": 2. }) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) self.normEWK = histo.Integral(0, histo.GetNbinsX()) histo.Scale(1 / self.normEWK) histo.Fit(theFit, options) theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax()) theFit.SetLineStyle(2) theFit.Draw("same") self.parMCEWK = theFit.GetParameters() fitPars = "fit parameters " i = 0 while i < numberOfParameters: fitPars = fitPars + " " + str(self.parMCEWK[i]) thePlot.SetParameter(i, theFit.GetParameter(i)) i = i + 1 thePlot.Draw("same") histograms.addText(0.2, 0.2, "EWK MC, baseline TauID") plot.histoMgr.appendHisto(histograms.Histo(theFit, "Fit")) plot.getPad().SetLogy(True) plot.draw() plot.save() self.parMCEWK = theFit.GetParameters() print fitPars self.nMCEWK = theFit.Integral(0, 1000, self.parMCEWK) print "Integral ", self.normEWK * self.nMCEWK
def fitQCD(self, origHisto): histo = origHisto.Clone("histo") rangeMin = histo.GetXaxis().GetXmin() rangeMax = histo.GetXaxis().GetXmax() numberOfParameters = 8 print "Fit range ", rangeMin, " - ", rangeMax class FitFunction: def __call__(self, x, par): return QCDFunction(x, par, 1) theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax, numberOfParameters) theFit.SetParLimits(0, 1, 20) theFit.SetParLimits(1, 20, 40) theFit.SetParLimits(2, 10, 25) theFit.SetParLimits(3, 1, 10) theFit.SetParLimits(4, 0, 150) theFit.SetParLimits(5, 10, 100) theFit.SetParLimits(6, 0.0001, 1) theFit.SetParLimits(7, 0.001, 0.05) if self.label == "Baseline": rangeMax = 240 if self.label == "7080": theFit.SetParLimits(5, 10, 100) # if self.label == "100120": # theFit.SetParLimits(0,1,20) # theFit.SetParLimits(2,1,25) # theFit.SetParLimits(3,0.1,20) if self.label == "120150": theFit.SetParLimits(0, 1, 20) theFit.SetParLimits(3, 0.1, 5) gStyle.SetOptFit(0) plot = plots.PlotBase() plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName())) plot.createFrame("qcdfit" + self.label, opts={ "ymin": 1e-5, "ymaxfactor": 2. }) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) self.normInvQCD = histo.Integral(0, histo.GetNbinsX()) histo.Scale(1 / self.normInvQCD) histo.Fit(theFit, "LR") theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax()) theFit.SetLineStyle(2) theFit.Draw("same") histograms.addText(0.4, 0.8, "Inverted TauID") plot.histoMgr.appendHisto(histograms.Histo(theFit, "Fit")) plot.getPad().SetLogy(True) plot.draw() plot.save() self.parInvQCD = theFit.GetParameters() fitPars = "fit parameters " i = 0 while i < numberOfParameters: fitPars = fitPars + " " + str(self.parInvQCD[i]) i = i + 1 print fitPars self.nFitInvQCD = theFit.Integral(0, 1000, self.parInvQCD) print "Integral ", self.normInvQCD * self.nFitInvQCD
def doPlots(datasetsEmb): datasetNames = datasetsEmb.getAllDatasetNames() isCorrected = isinstance(datasetsEmb, result.DatasetsDYCorrection) def createPlot(name, dyx=0.67, dyy=0.64): name2 = name if isinstance(name, basestring): name2 = analysisEmb + "/" + name rootHistos = [] for datasetName in datasetNames: (histo, tmp) = datasetsEmb.getHistogram(datasetName, name2) histo.SetName(datasetName) rootHistos.append(histo) p = plots.DataMCPlot2(rootHistos) histos = p.histoMgr.getHistos() for h in histos: if h.getName() == "Data": h.setIsDataMC(True, False) else: h.setIsDataMC(False, True) p.setLuminosity(datasetsEmb.getLuminosity()) p.setDefaultStyles() if isCorrected: p.appendPlotObject( histograms.PlotText(dyx, dyy, "DY correction applied", size=15)) return p prefix = "embdatamc_" opts2 = {"ymin": 0, "ymax": 2} # Control plots def drawControlPlot(path, xlabel, **kwargs): drawPlot(createPlot("ControlPlots/" + path), prefix + path, xlabel, opts2=opts2, **kwargs) drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 40, "greaterThan": True }) drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts={ "xmin": -2.2, "xmax": 2.2 }, ylabel="Events / %.1f", rebin=4, moveLegend={ "dy": -0.52, "dx": -0.2 }) drawControlPlot("SelectedTau_phi_AfterStandardSelections", "#tau-jet #phi", rebin=10, ylabel="Events / %.2f") drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts={ "xmin": 0.65, "xmax": 1.05, "ymin": 1e-1, "ymaxfactor": 10 }, rebin=5, ylabel="Events / %.2f", moveLegend={ "dx": -0.4, "dy": 0.01, "dh": -0.03 }, cutBox={ "cutValue": 0.7, "greaterThan": True }) #drawControlPlot("SelectedTau_p_AfterStandardSelections", "#tau-jet p (GeV/c)", rebin=2) #drawControlPlot("SelectedTau_LeadingTrackP_AfterStandardSelections", "#tau-jet ldg. charged particle p (GeV/c)", rebin=2) #drawControlPlot("IdentifiedElectronPt_AfterStandardSelections", "Electron p_{T} (GeV/c)") #drawControlPlot("IdentifiedMuonPt_AfterStandardSelections", "Muon p_{T} (GeV/c)") #drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") drawControlPlot("MET", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50) # After MET drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", cutLine=1) treeDraw = dataset.TreeDraw(analysisEmb + "/tree", weight="weightPileup*weightTrigger") tdMet = treeDraw.clone(varexp="met_p4.Phi() >> tmp(16, -3.2, 3.2)") drawPlot(createPlot(tdMet.clone()), prefix + "METPhi_1AfterTauID", "\MET #phi", log=False, ylabel="Events / %.1f", opts={"ymaxfactor": 2}, opts2={ "ymin": 0, "ymax": 2 }) # After b-tagging treeDraw = treeDraw.clone( weight="weightPileup*weightTrigger*weightBTagging") tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) tdDeltaPhi = treeDraw.clone( varexp= "acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 >>tmp(18, 0, 180)" ) metCut = "(met_p4.Et() > 50)" bTaggingCut = "passedBTagging" deltaPhi160Cut = "(acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 <= 160)" deltaPhi130Cut = "(acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 <= 130)" # DeltapPhi def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) drawPlot(createPlot(tdDeltaPhi.clone(selection=And(metCut, bTaggingCut))), prefix + "deltaPhi_3AfterBTagging", "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})", log=False, opts={"ymax": 30}, opts2=opts2, ylabel="Events / %.0f^{o}", function=customDeltaPhi, moveLegend={"dx": -0.22}, cutLine=[130, 160]) # mT for name, label, selection in [ ("3AfterBTagging", "Without #Delta#phi(#tau jet, E_{T}^{miss}) cut", [metCut, bTaggingCut]), ("4AfterDeltaPhi160", "#Delta#phi(#tau jet, E_{T}^{miss}) < 160^{o}", [metCut, bTaggingCut, deltaPhi160Cut]), ("5AfterDeltaPhi130", "#Delta#phi(#tau jet, E_{T}^{miss}) < 130^{o}", [metCut, bTaggingCut, deltaPhi130Cut]) ]: p = createPlot(tdMt.clone(selection=And(*selection))) h = p.histoMgr.getHisto("Data").getRootHisto() s = "" for bin in xrange(1, h.GetNbinsX() + 1): val = h.GetBinContent(bin) err = h.GetBinError(bin) if val != 0: s += "%.2f " % (err / val * 100) else: s += "0 " print "%s rel. stat. unc. %s" % (name, s) p.appendPlotObject(histograms.PlotText(0.5, 0.62, label, size=20)) drawPlot(p, prefix + "transverseMass_" + name, "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts={"ymax": 32}, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False) return prefix = "avg10" if isCorrected: prefix += "_dycorrected" opts2 = {"ymin": 0, "ymax": 3} drawPlot(createPlot( treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), prefix + "_selectedTauPt_4AfterDeltaPhi160", "#tau-jet p_{T} (GeV/c)", opts2=opts2) drawPlot(createPlot( treeDraw.clone(varexp="met_p4.Pt() >>tmp(16,0,400)", selection=selection)), prefix + "_MET_4AfterDeltaPhi160", "E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", opts2=opts2) #opts = {"ymaxfactor": 1.2} opts = {"ymax": 40} p = createPlot(tdMt.clone(selection=selection)) addAN = False if addAN: mtAN = ROOT.TH1F("mt_AN", "mt_AN", 20, 0, 400) mtAN.SetDirectory(0) mtAN.SetBinContent(1, 27.70106) mtAN.SetBinContent(2, 15.93031) mtAN.SetBinContent(3, 11.06969) mtAN.SetBinContent(4, 4.613092) mtAN.SetBinContent(5, 5.13239) mtAN.SetBinContent(6, 3.998591) mtAN.SetBinContent(7, 1.497308) mtAN.SetBinContent(9, 0.7270167) mtAN.SetBinError(1, 5.035656) mtAN.SetBinError(2, 3.771818) mtAN.SetBinError(3, 3.058925) mtAN.SetBinError(4, 2.107709) mtAN.SetBinError(5, 2.15077) mtAN.SetBinError(6, 2.023928) mtAN.SetBinError(7, 1.090971) mtAN.SetBinError(9, 0.7270168) styles.mcStyle2.apply(mtAN) h = histograms.Histo(mtAN, "Data in AN v4", "p", "EP") h.setIsDataMC(False, False) p.histoMgr.insertHisto(1, h, legendIndex=1) p.setDataDatasetNames(["Data", h.getName()]) drawPlot(p, prefix + "_transverseMass_4AfterDeltaPhi160", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False)
def cutefficiency(self, histo1, histo2): h1 = histo1.Clone("h1") h2 = histo2.Clone("h2") h1.Scale(1 / h1.GetMaximum()) h2.Scale(1 / h2.GetMaximum()) # check that no bin has negative value, negative values possible after subtracting EWK from data iBin = 1 nBins = h1.GetNbinsX() while iBin < nBins: value1 = h1.GetBinContent(iBin) value2 = h2.GetBinContent(iBin) if value1 < 0: h1.SetBinContent(iBin, 0) if value2 < 0: h2.SetBinContent(iBin, 0) iBin = iBin + 1 h1cut = h1.Clone("h1cut") h1cut.Reset() h1cut.GetYaxis().SetTitle("Efficiency") h1cut.GetXaxis().SetTitle("PF MET cut (GeV)") h2cut = h2.Clone("h2cut") h2cut.Reset() h2cut.SetLineColor(2) integralError = ROOT.Double(0.0) integralValue = h1.IntegralAndError(1, h1cut.GetNbinsX(), integralError) h1_integral = h1.Integral(0, h1.GetNbinsX()) h2_integral = h2.Integral(0, h2.GetNbinsX()) iBin = 1 nBins = h1cut.GetNbinsX() while iBin < nBins: error = ROOT.Double(0.0) selected1 = h1.IntegralAndError(iBin, nBins, error) if selected1 > 0: error = error / selected1 else: error = integralError / integralValue efficiency1 = selected1 / h1_integral h1cut.SetBinContent(iBin, efficiency1) if self.errorBars: h1cut.SetBinError(iBin, error) error = ROOT.Double(0.0) selected2 = h2.IntegralAndError(iBin, nBins, error) if selected2 > 0: error = error / selected2 else: error = integralError / integralValue efficiency2 = selected2 / h2_integral h2cut.SetBinContent(iBin, efficiency2) if self.errorBars: h2cut.SetBinError(iBin, error) iBin = iBin + 1 plot = plots.ComparisonPlot( histograms.Histo(h1cut, "Inv"), histograms.Histo(h2cut, "Base"), ) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) st2.append(styles.StyleMarker(markerColor=ROOT.kRed)) plot.histoMgr.forHisto("Base", st1) plot.histoMgr.forHisto("Inv", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({ "Inv": h1.GetTitle(), "Base": h2.GetTitle() }) # Set the legend styles #plot.histoMgr.setHistoLegendStyleAll("L") plot.histoMgr.setHistoLegendStyleAll("P") # Set the drawing styles #plot.histoMgr.setHistoDrawStyleAll("HIST") plot.histoMgr.setHistoDrawStyleAll("EP") # Create frame with a ratio pad plot.createFrame( "cuteff" + self.label, opts={ "ymin": 1e-5, "ymaxfactor": 2 }, createRatio=True, opts2={ "ymin": 0, "ymax": 2 }, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad().SetLogy(True) plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93)) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) plot.draw() plot.save() ###### hError = h1cut.Clone("hError") hError.Divide(h2cut) iBin = 1 nBins = hError.GetNbinsX() while iBin < nBins: hError.SetBinContent(iBin, abs(hError.GetBinContent(iBin) - 1)) iBin = iBin + 1 hError.GetYaxis().SetTitle( "abs( (#varepsilon^{Inverted} - #varepsilon^{Baseline})/#varepsilon^{Baseline} )" ) hError.GetXaxis().SetTitle("PF MET cut (GeV)") plot2 = plots.PlotBase() plot2.histoMgr.appendHisto(histograms.Histo(hError, "ShapeUncertainty")) plot2.histoMgr.forHisto("ShapeUncertainty", st1) plot2.histoMgr.setHistoDrawStyleAll("EP") # plot2.createFrame("shapeUncertainty"+self.label, opts={"ymin":-1, "ymax": 1}) plot2.createFrame("shapeUncertainty" + self.label, opts={ "ymin": -0.1, "ymax": 1.1 }) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) rangeMin = hError.GetXaxis().GetXmin() rangeMax = hError.GetXaxis().GetXmax() # rangeMax = 80 rangeMax = 120 # rangeMax = 380 numberOfParameters = 2 class FitFunction: def __call__(self, x, par): # return Linear(x,par) return ErrorFunction(x, par) theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax, numberOfParameters) theFit.SetParLimits(0, 0.01, 0.03) theFit.SetParLimits(1, 50, 150) # theFit.FixParameter(0,0.02) # theFit.FixParameter(1,100) hError.Fit(theFit, "LRN") print "Error MET > 40", theFit.Eval(40) print "Error MET > 50", theFit.Eval(50) print "Error MET > 70", theFit.Eval(70) plot2.histoMgr.appendHisto(histograms.Histo(theFit, "Fit")) plot2.draw() plot2.save()
def doHistosCompare(HistoList, myPath, QCDscheme, ErrorType, mySaveName, bNormalizeToOne, bRatio, bInvertRatio): # Get the integrated luminosity of the data-era (only used for addind lumi text) myLumi = Helper.getLumi(myDataEra) # Check that the user-defined options are valid Helper.checkUserOptions(QCDscheme, ErrorType) # Get the relevant Tail-Killer directories to be read myDirsDict = Helper.getTailKillerDir(myTailKillers, myDataEra) counter = 0 #for tailKiller in myDirsDict.keys(): #this is not used as it screws-up the ordering (dictionaries have no order) for tailKiller in myTailKillers: dirName = myDirsDict[tailKiller] rootFile = Helper.getRootFile(dirName + "/" + myPath) # Plot all histograms defined in the HistoList print "*** There are \"%s\" histogram(s) in the plotting queue (QCDscheme = \"%s\" , Tail-Killer = \"%s\"):" % ( len(HistoList), QCDscheme, tailKiller) for h in HistoList: pathName, histoName = Helper.getHistoNameAndPath( QCDscheme, ErrorType, h) histo = Helper.getHisto(rootFile, pathName) saveName = Helper.getFullSaveName(myDataEra, None, bNormalizeToOne, mySaveName) # Get histogram attributes as defined in QCDHistoHelper.py xLabel = h.xLabel yLabel = h.yLabel xMin = h.xMin xMax = h.xMax logX = h.bLogX yMin = h.yMin yMax = h.yMax logY = h.bLogY legendLabel = tailKiller legendHeader = h.legendHeader # Create and draw the plots if counter == 0: print " Creating \"%s\" (%s)" % (histoName, tailKiller) p = Helper.createPlot(histo, myLumi, legendLabel, sLegStyle, sDrawStyle) h = histograms.Histo(Helper.setHistoStyle(histo, counter), legendLabel, sLegStyle, sDrawStyle) else: h = histograms.Histo(Helper.setHistoStyle(histo, counter), legendLabel, sLegStyle, sDrawStyle) histograms.Histo(h, histoName, sLegStyle, sDrawStyle) print " Appending \"%s\" (%s)" % (histoName, tailKiller) p.histoMgr.appendHisto(h) # Increment counter counter = counter + 1 binValue = h.getRootHisto().GetBinContent(2) if bNormalizeToOne == True: p.histoMgr.forEachHisto( lambda h: dataset._normalizeToOne(h.getRootHisto())) yMinLog == yMinLogNorm # Customize the plots drawPlot = Helper.customizePlot(logY, bAddLumiText, bRatio, bInvertRatio, "Ratio", yMin, yMax, yMaxFactor, yMinRatio, yMaxRatio, yMinLog, yMaxFactorLog) # Save the plots drawPlot(p, saveName, xlabel=xLabel, ylabel=yLabel, customizeBeforeDraw=Helper.setLabelOption) print "*** Saved canvas as \"%s\"\n" % (saveName) return
def doSignifPlots(p, drawPlot, datasets, histo, hName, xLabel, yLabel, saveName, cutDir): ''' def doSignifPlots(p, drawPlot, datasets, histo, hName, xLabel, yLabel, saveName, CutDir): ''' nDataDatasets = len(datasets.getDataDatasets()) nMCDatasets = len(datasets.getMCDatasets()) if nMCDatasets < 1: print "*** WARNING: No MC datasets found. Skipping significance plots." return if cutDir == "<": saveName = saveName + "_SignifLessThan" saveName = saveName.replace("/", "_") MyIntegral = lambda h, bin: h.Integral(0, bin) elif cutDir == ">": saveName = saveName + "_SignifGreaterThan" saveName = saveName.replace("/", "_") MyIntegral = lambda h, bin: h.Integral(bin, nBins) else: print "%sERROR! Unsupported cut-direction string %s used. Exiting ROOT" % ( cutDir) sys.exit() yLabel = "Significance" + "(" + cutDir + ")" # Legend and save-name histograms.createLegend.setDefaults(x1=0.65, x2=0.90, y1=0.8, y2=0.92) ### Setup the histogram text mode and create plot histograms.cmsTextMode = histograms.CMSMode.SIMULATION p2 = createTH1Plot(datasets, hName, normalizeToOne=False) ### Construct an empty histogram (same binning as variable distribution) hBinSignif = p.histoMgr.getHisto( "TTToHplus_M" + signalMass).getRootHisto().Clone(saveName + "_Clone") hBinSignif.Reset() nBinsX = hBinSignif.GetNbinsX() nBins = nBinsX + 1 ### Loop over all histogram bins for iBin in xrange(0, nBins): ### Initialise variables to be used in Significance calculation nSignal = 0 nBackgr = 0 signifError = 0 signifValue = 0 # Loop over all histograms to determine the number of signal and bkg events to calculate significance for htmp in p.histoMgr.getHistos(): h = htmp.getRootHisto() name = htmp.getName() if ("Data" in name or "sum_errors" in name): continue elif ("TTToHplus_M" + signalMass in name): #print "*** Signal-Histo = ", (name) nSignal = MyIntegral(h, iBin) else: if name == "StackedMC": hStackedMC = p.histoMgr.getHisto( "StackedMC").getRootHisto().Clone("hStackedMC_Clone") for htmp in hStackedMC.GetHists(): name = htmp.GetName() if ("MCuncertainty") in name: continue #print "*** Bkg-Histo = ", (name) nBackgr += MyIntegral(htmp, iBin) eBackgr = 0 #FIXME else: if ("MCuncertainty") in name: continue #print "*** Bkg-Histo = ", (name) nBackgr += MyIntegral(h, iBin) eBackgr = 0 #FIXME if nSignal < 9e-04: nSignal = 0.0 if nBackgr > 0: #FIXME signifValue = math.sqrt( 2 * ((nSignal + nBackgr) * math.log(1 + (nSignal / nBackgr)) - nSignal)) #G. Cowan (sysErrorBackgr=0) signifError = 0.0001 #FIXME else: signifValue = 0 signifError = 0.0001 #FIXME # Calculate error on significance if nSignal > 0 and nBackgr > 0: #signifErrorSquared = ( (1+2*math.log(1+nSignal/nBackgr)/(2*signifValue) )**2)*nSignal + ( ( (2*math.log(1+nSignal/nBackgr) - 2*nSignal/nBackgr)/(2*signifValue**2) )**2)**nBackgr #signifErrorSquared = ((signifValue/nSignal)**2)*nSignal + ((0.5*(signifValue/nBackgr))**2)*nBackgr #signifError = math.sqrt(signifErrorSquared) signifError = 0.0001 else: signifError = 0.0001 #print " nSignal = %s, nBackgr = %s, signifValue = %s, signifError = %s" % (nSignal, nBackgr, signifValue, signifError) #attikis #print "*** iBin=%s ; Sig=%s ; S=%s ; B=%s" % (iBin, signifValue, nSignal, nBackgr) hBinSignif.SetBinContent(iBin, signifValue) hBinSignif.SetBinError(iBin, signifError) # Loop over histograms and remove all histos for htmp in p2.histoMgr.getHistos(): h = htmp.getRootHisto() name = htmp.getName() if name == "StackedMC": hStackedMC = p.histoMgr.getHisto("StackedMC").getRootHisto().Clone( "hStackedMC_Clone") for htmp in hStackedMC.GetHists(): p2.histoMgr.removeHisto(name) else: p2.histoMgr.removeHisto(name) ### Add the significance plots to the histo-manager h = histograms.Histo(setSignificanceHistoStyle(hBinSignif), " m_{H^{#pm}} = " + signalMass + " GeV/c^{2}", "HP", "HP") h.setIsDataMC(False, True) p2.histoMgr.appendHisto(h) ### Draw the plot with custom options and save drawPlot = plots.PlotDrawer(stackMCHistograms=False, addMCUncertainty=False, log=False, ratio=False, addLuminosityText=True, opts={"ymaxfactor": 1.2}) drawPlot(p2, saveName, xlabel=histo.xlabel, ylabel=yLabel, rebinToWidthX=histo.binWidthX, cutLine=getHistoCutLines(histo)) return
def doHistosCompare(HistoList, myPath, QCDscheme, ErrorType, mySaveName, bNormalizeToOne, bRatio, bInvertRatio): # Determine the Tail-Killer scenario myTailKiller = Helper.getTailKillerFromDir(myTailKillers) # Check the current working directory name for a valid data-era myDataEra = Helper.getDataEra(myValidDataEras) # Get the integrated luminosity of the data-era (only used for addind lumi text) myLumi = Helper.getLumi(myDataEra) # Check that the user-defined options are valid Helper.checkUserOptions(QCDscheme, ErrorType) # Get the ROOT file rootFile = Helper.getRootFile(myPath) # Plot all histograms defined in the HistoList print "*** There are \"%s\" histogram(s) in the plotting queue (QCDscheme = \"%s\" , Tail-Killer = \"%s\"):" % ( len(HistoList), QCDscheme, myTailKiller) counter = 0 for h in HistoList: pathName, histoName = Helper.getHistoNameAndPath( QCDscheme, ErrorType, h) histo = Helper.getHisto(rootFile, pathName) saveName = Helper.getFullSaveName(myDataEra, myTailKiller, bNormalizeToOne, mySaveName) # Get histogram attributes as defined in QCDHistoHelper.py xLabel = h.xLabel yLabel = h.yLabel xMin = h.xMin xMax = h.xMax logX = h.bLogX yMin = h.yMin yMax = h.yMax logY = h.bLogY legendLabel = h.legendLabel legendHeader = h.legendHeader # Create and draw the plots if counter == 0: print " Creating \"%s\"" % (histoName) p = Helper.createPlot(histo, myLumi, legendLabel, sLegStyle, sDrawStyle) h = histograms.Histo(Helper.setHistoStyle(histo, counter), legendLabel, sLegStyle, sDrawStyle) else: if len(HistoList) <= 2: h = histograms.Histo(Helper.setHistoStyle(histo, counter), legendLabel, "f", "HIST") else: h = histograms.Histo(Helper.setHistoStyle(histo, counter), legendLabel, sLegStyle, sDrawStyle) histograms.Histo(h, histoName, sLegStyle, sDrawStyle) print " Appending \"%s\"" % (histoName) p.histoMgr.appendHisto(h) if bNormalizeToOne == True: p.histoMgr.forEachHisto( lambda h: dataset._normalizeToOne(h.getRootHisto())) yMinLog = yMinLogNorm # Customize the plots drawPlot = Helper.customizePlot(logY, bAddLumiText, bRatio, bInvertRatio, "Ratio", yMin, yMax, yMaxFactor, yMinRatio, yMaxRatio, yMinLog, yMaxFactorLog) # Increment counter counter = counter + 1 # Save the plots if legendHeader is not None: drawPlot(p, saveName, xlabel=xLabel, ylabel=yLabel, customizeBeforeDraw=lambda plot: plot.legend.SetHeader( legendHeader)) else: drawPlot(p, saveName, xlabel=xLabel, ylabel=yLabel, customizeBeforeDraw=Helper.setLabelOption) print "*** Saved canvas as \"%s\"\n" % (saveName) return
def doDataMinusEwk(p, drawPlot, datasets, hPath, hName, xLabel, yLabel, binWidth, SaveExtension, **kwargs): ''' def doDataMinusEwk(p, drawPlot, datasets, hPath, hName, xLabel, yLabel, SaveExtension): For each histogram plotted with doPlots() an identical one with QCD=Data-Ewk MC is also plotted using this method. Loops over all histograms defined in HistoHelper.py and customises each plot accordingly. The global boolean options are also taken care of including x- and y- min, max, ratio, logY, etc.. ''' args = kwargs.get("hType", None) if len(args) < 1: raise Exception( "*** Should pass at least one keyword argument; Either \"TH1\" or \"TH2\"." ) if "TH1" not in args.keys() and "TH2" not in args.keys(): raise Exception( "*** Should pass at least one keyword argument; Either \"TH1\" or \"TH2\"." ) hType = args.keys() if not getBool("bDataMinusEwk") or getBool("bRemoveData"): print "*** Skipping replacement of QCD with Data-Ewk. bRemoveData==", getBool( "bRemoveData") return if "TH1" in hType: p2 = createTH1Plot(datasets, hPath, normalizeToOne=False) else: p2 = createTH2Plot(datasets, hPath, normalizeToOne=False) hDataClone = p.histoMgr.getHisto("Data").getRootHisto().Clone( "hData_Clone") if (p.histoMgr.getHisto("Data").getRootHisto()) == None: raise Exception( "*** Cannot replace QCD with Data-Ewk since \"Data\" histogram is empty." ) ### Copy Data histo to a new histo which will be the QCD=Data-EwkMc histo hDataMinusEwk = hDataClone.Clone("hDataMinusEwkMc_Clone") ### Loop over all histograms for h in p.histoMgr.getHistos(): htmp = h.getRootHisto() if ("StackedMC" in htmp.GetName()): hStackedMC = htmp.Clone("hStackedMC_Clone") for htmp in hStackedMC.GetHists(): #print "***1) histo = ", (htmp.GetName()) if (htmp.GetName() in ["Data", "TTToHplus", "sum_errors"]): continue elif ("QCD" in htmp.GetName()): qcd = htmp continue else: #print "*** Subtracting %s from Data histo to get QCD=Data-EwkMc" % (htmp.GetName()) hDataMinusEwk.Add(htmp, -1) else: #print "***2) histo = ", (htmp.GetName()) if (h.isData()): continue else: if ("TTToHplus" in htmp.GetName() or "sum_errors" in htmp.GetName()): continue elif ("QCD" in htmp.GetName()): qcd = htmp continue else: #print "*** Subtracting %s from Data histo to get QCD=Data-EwkMc" % (htmp.GetName()) hDataMinusEwk.Add(htmp, -1) ### Customise QCD=Data-EwkMc histo aux.copyStyle(qcd, hDataMinusEwk) if "TH1" in hType: if getBool("bStackHistos"): DataMinusEwk = histograms.Histo(hDataMinusEwk, "hDataMinusEwkMc", "f", "HIST") else: DataMinusEwk = histograms.Histo(hDataMinusEwk, "hDataMinusEwkMc", "P", "P") else: DataMinusEwk = histograms.Histo(hDataMinusEwk, "hDataMinusEwkMc", "", "P") DataMinusEwk.setIsDataMC(False, True) DataMinusEwk.setLegendLabel("Data - EWK_{MC}") ### Add QCD=Data-EwkMc histo to histograms list, remove QCD-MC histo from histograms list and customise plot p2.histoMgr.insertHisto( 2, DataMinusEwk ) #insert QCD=Data-EwkMc histo at position 2 (correct order) p2.histoMgr.removeHisto("QCD") # ## For TH2 case remove the "Data" and "EWK MC" histos and setup the temperature style if "TH2" in hType: p2.histoMgr.removeHisto("Data") p2.histoMgr.removeHisto("EWK MC") #fixme p2.histoMgr.setHistoDrawStyleAll("COLZ") setHistoContours(p2, 30) ### Draw the plot with custom options and save if not getBool("bStackHistos"): saveName = "%s_%s" % (hName, SaveExtension + "_DataMinusEwk") else: saveName = "%s_%s" % (hName, SaveExtension + "_DataMinusEwk_Stacked") drawPlot(p2, saveName, xlabel=xLabel, ylabel=yLabel, rebinToWidthX=binWidth) return
def main(): # Create all datasets from a multicrab task datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters) datasets.updateNAllEventsToPUWeighted() # Read integrated luminosities of data datasets from lumi.json datasets.loadLuminosities() # Include only 120 mass bin of HW and HH datasets datasets.remove( filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames())) # Default merging nad ordering of data and MC datasets # All data datasets to "Data" # All QCD datasets to "QCD" # All single top datasets to "SingleTop" # WW, WZ, ZZ to "Diboson" plots.mergeRenameReorderForDataMC(datasets) # Set BR(t->H) to 0.2, keep BR(H->tau) in 1 xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1) # Merge WH and HH datasets to one (for each mass bin) # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX" plots.mergeWHandHH(datasets) # Merge EWK datasets datasets.merge("EWK", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"]) # Apply TDR style style = tdrstyle.TDRStyle() # Create the normalized plot of transverse mass # Read the histogram from the file #mT = plots.DataMCPlot(datasets, analysis+"/transverseMass") # Create the histogram from the tree (and see the selections explicitly) td = dataset.TreeDraw( analysis + "/tree", weight="weightPileup*weightTrigger*weightPrescale", selection="met_p4.Et() > 70 && Max$(jets_btag) > 1.7") # mT = plots.DataMCPlot(datasets, td.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))>>dist(400, 0, 400)")) # met = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.Et()>>dist(400, 0, 400)")) met5060 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging5060") met6070 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging6070") met7080 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging7080") met80100 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging80100") met100120 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging100120") met120150 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging120150") met150 = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging150") # Rebin before subtracting met5060.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met6070.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met7080.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met80100.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met100120.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met120150.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) met150.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1)) data5060 = met5060.histoMgr.getHisto("Data").getRootHisto().Clone("Data") data6070 = met6070.histoMgr.getHisto("Data").getRootHisto().Clone("Data") data7080 = met7080.histoMgr.getHisto("Data").getRootHisto().Clone("Data") data80100 = met80100.histoMgr.getHisto("Data").getRootHisto().Clone("Data") data100120 = met100120.histoMgr.getHisto("Data").getRootHisto().Clone( "Data") data120150 = met120150.histoMgr.getHisto("Data").getRootHisto().Clone( "Data") data150 = met150.histoMgr.getHisto("Data").getRootHisto().Clone("Data") # Create the data-EWK histogram and draw it # diffBase = dataEwkDiff(metBase, "MET_base_data-ewk") # diffInverted = dataEwkDiff(metInver,"MET_inverted_data-ewk") # Draw the MET distribution # transverseMass(metBase,"MET_base") # transverseMass(metInver,"MET_inverted") # Set the styles # dataset._normalizeToOne(diffBase) # dataset._normalizeToOne(diffInverted) plot = plots.PlotBase() plot.histoMgr.appendHisto( histograms.Histo(data5060, "50 < p_{T}^{#tau jet} < 60 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data6070, "60 < p_{T}^{#tau jet} < 70 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data7080, "70 < p_{T}^{#tau jet} < 80 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data80100, "80 < p_{T}^{#tau jet} < 100 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data100120, "100 < p_{T}^{#tau jet} < 120 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data120150, "120 < p_{T}^{#tau jet} < 150 GeV")) plot.histoMgr.appendHisto( histograms.Histo(data150, "p_{T}^{#tau jet} > 150 GeV")) st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) st3 = st1.clone() st3.append(styles.StyleLine(lineColor=ROOT.kBlue)) st4 = st1.clone() st4.append(styles.StyleLine(lineColor=ROOT.kGreen)) st5 = st1.clone() st5.append(styles.StyleLine(lineColor=ROOT.kMagenta, lineStyle=2)) st6 = st1.clone() st6.append(styles.StyleLine(lineColor=ROOT.kPink, lineStyle=8)) # lineWidth=6)) st7 = st1.clone() st7.append(styles.StyleLine(lineColor=ROOT.kBlue - 2, lineStyle=3)) plot.histoMgr.forHisto("50 < p_{T}^{#tau jet} < 60 GeV", st1) plot.histoMgr.forHisto("60 < p_{T}^{#tau jet} < 70 GeV", st2) plot.histoMgr.forHisto("70 < p_{T}^{#tau jet} < 80 GeV", st3) plot.histoMgr.forHisto("80 < p_{T}^{#tau jet} < 100 GeV", st4) plot.histoMgr.forHisto("100 < p_{T}^{#tau jet} < 120 GeV", st5) plot.histoMgr.forHisto("120 < p_{T}^{#tau jet} < 150 GeV", st6) plot.histoMgr.forHisto("p_{T}^{#tau jet} > 150 GeV", st7) plot.createFrame( "METinBins", opts={ "xmax": 200, "ymin": 1e-1, "ymaxfactor": 1.5 }, # createRatio=True, opts2={"ymin": -5 , "ymax": 6 }, # bounds of the ratio plot ) plot.getPad().SetLogy(True) plot.setLegend(histograms.createLegend(0.6, 0.68, 0.8, 0.93)) plot.frame.GetXaxis().SetTitle("MET (GeV)") plot.frame.GetYaxis().SetTitle("Data") # Draw the plot plot.draw() plot.save()
def main(): datasets = dataset.getDatasetsFromMulticrabCfg() datasets.loadLuminosities() #mc = "WJets" mc = "QCD" data = "2010" #data = "2011" # maxVtx = 15 maxVtx = 20 if data == "2010": datasets.remove( filter(lambda name: "Prompt" in name, datasets.getAllDatasetNames())) elif data == "2011": datasets.remove( filter(lambda name: "Dec22" in name, datasets.getAllDatasetNames())) plots.mergeRenameReorderForDataMC(datasets) style = tdrstyle.TDRStyle() if mc == "QCD": datasets.remove(["WJets"]) elif mc == "WJets": datasets.remove(["QCD"]) h = histograms.HistoManager(datasets, "signalAnalysis/verticesBeforeWeight") h.normalizeToOne() h.forEachMCHisto(styles.generator()) h.forHisto("Data", styles.getDataStyle()) h.setHistoDrawStyle("Data", "EP") h.setHistoLegendStyle("Data", "p") cf = histograms.CanvasFrame(h, "vertex_%s_%s" % (data, mc), xmax=maxVtx) cf.frame.GetXaxis().SetTitle("N(vtx)") cf.frame.GetYaxis().SetTitle("A.u.") legend = histograms.createLegend() h.addToLegend(legend) h.draw() legend.Draw() cf.canvas.SaveAs(".png") cf.canvas.SaveAs(".eps") cf.canvas.SaveAs(".C") # Weight dataHisto = h.getHisto("Data").getRootHisto() mcHisto = h.getHisto(mc).getRootHisto() # For normalization, see https://twiki.cern.ch/twiki/bin/view/CMS/PileupReweighting weightHisto = dataHisto.Clone("weights") weightHisto.Divide(mcHisto) print "Weight histo integral", weightHisto.Integral() #weightHisto.Scale(1/dataHisto.Integral()) #weightHisto.Scale(1/weightHisto.Integral()) print "Weight histo integral", weightHisto.Integral() print "Sum of [weight*prob]", sum([ weightHisto.GetBinContent(bin) * mcHisto.GetBinContent(bin) for bin in xrange(1, weightHisto.GetNbinsX()) ]) print "weights = cms.vdouble(%s)" % ", ".join([ "%.8f" % weightHisto.GetBinContent(bin) for bin in xrange(1, min(maxVtx, weightHisto.GetNbinsX()) + 1) ]) h = histograms.HistoManager(datasetRootHistos=[]) h.appendHisto(histograms.Histo(weightHisto, "Weight", "", "HIST")) h.forEachHisto(styles.generator()) cf = histograms.CanvasFrame(h, "vertex_weight_%s_%s" % (data, mc), xmax=maxVtx) cf.frame.GetXaxis().SetTitle("N(vtx)") cf.frame.GetYaxis().SetTitle("Weight") h.draw() cf.canvas.SaveAs(".png") cf.canvas.SaveAs(".eps") cf.canvas.SaveAs(".C")
def comparison(self, histo1, histo2, norm=1): h1 = histo1.Clone("h1") h2 = histo2.Clone("h2") if norm == 1: h1.Scale(1 / h1.GetMaximum()) h2.Scale(1 / h2.GetMaximum()) # check that no bin has negative value, negative values possible after subtracting EWK from data iBin = 1 nBins = h1.GetNbinsX() while iBin < nBins: value1 = h1.GetBinContent(iBin) value2 = h2.GetBinContent(iBin) if value1 < 0: h1.SetBinContent(iBin, 0) if value2 < 0: h2.SetBinContent(iBin, 0) iBin = iBin + 1 if norm > 0: h1.GetYaxis().SetTitle("Arbitrary units") plot = plots.ComparisonPlot( histograms.Histo(h1, "Inv"), histograms.Histo(h2, "Base"), ) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleMarker(markerColor=ROOT.kRed)) plot.histoMgr.forHisto("Base", st1) plot.histoMgr.forHisto("Inv", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({ "Inv": h1.GetTitle(), "Base": h2.GetTitle() }) # Set the legend styles plot.histoMgr.setHistoLegendStyleAll("P") # Set the drawing styles plot.histoMgr.setHistoDrawStyleAll("EP") # Create frame with a ratio pad plot.createFrame( "comparison" + self.label, opts={ "ymin": 1e-5, "ymaxfactor": 2 }, createRatio=True, opts2={ "ymin": 0, "ymax": 2 }, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad1().SetLogy(True) plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93)) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) plot.draw() plot.save()
def doDataMinusEWk(p, drawPlot, datasets, counter, histo, hName, xLabel, yLabel, SaveExtension): if bDataMinusEwk==False or bMcOnly==True: return ### Create QCD=Data-EwkMc by copying data histo and then subtracting EwkMc if bStackHistos==True: ### Copy Data histo to a new histo which will be the QCD=Data-EwkMc histo hDataMinusEwk = p.histoMgr.getHisto("Data").getRootHisto().Clone("hDataMinusEwkMc_Clone") hDataMinusEwk.Reset() hDataMinusEwk.Add(p.histoMgr.getHisto("Data").getRootHisto()) hStackedMC = p.histoMgr.getHisto("StackedMC").getRootHisto().Clone("hStackedMC_Clone") for htmp in hStackedMC.GetHists(): if("TTToHplus" in htmp.GetName()): #print "Skipping: ", htmp.GetName() continue if("QCD" in htmp.GetName()): #print "Skipping: ", htmp.GetName() continue #print "Subtracting: ", htmp.GetName() hDataMinusEwk.Add(htmp, -1) p2 = createTH1Plot(datasets, histo, normalizeToOne = False) qcd = histograms.Histo(hDataMinusEwk, "hDataMinusEwkMc", "f", "HIST") qcd.setIsDataMC(False, True) qcd.setLegendLabel("Data - EWK_{MC}") #p2.histoMgr.insertHisto(1, qcd) #insert QCD histo at position 1 (correct order) #p2.histoMgr.appendHisto(qcd) p2.histoMgr.insertHisto(2, qcd) #insert QCD histo at position 2 (correct order) p2.histoMgr.removeHisto("QCD") plots._plotStyles["hDataMinusEwkMc"] = styles.qcdStyle saveName = "%s_%s" % (hName, SaveExtension + "_DataMinusEwk") drawPlot(p2, saveName, rebin=1, xlabel=xLabel, ylabel=yLabel) counter = counter+1 return else: ### Copy Data histo to a new histo which will be the QCD=Data-EwkMc histo hDataMinusEwk = p.histoMgr.getHisto("QCD").getRootHisto().Clone("hDataMinusEwkMc_Clone") hDataMinusEwk.Reset() ### Loop over histograms for h in p.histoMgr.getHistos(): htmp = h.getRootHisto() #print "*** htmp.GetName() = ", htmp.GetName() if(h.isData()): #print "*** Adding: ", htmp.GetName() hDataMinusEwk.Add(htmp, +1) else: if("TTToHplus" in htmp.GetName() or "QCD" in htmp.GetName()): #print "*** Skipping: ", htmp.GetName() continue else: #print "*** Subtracting: ", htmp.GetName() hDataMinusEwk.Add(htmp, -1) p2 = createTH1Plot(datasets, histo, normalizeToOne = False) qcd = histograms.Histo(hDataMinusEwk, "hDataMinusEwkMc", "P", "P") qcd.setIsDataMC(False, True) qcd.setLegendLabel("Data - EWK_{MC}") p2.histoMgr.insertHisto(2, qcd) #insert QCD histo at position 1 (correct order) p2.histoMgr.removeHisto("QCD") plots._plotStyles["hDataMinusEwkMc"] = styles.qcdStyle saveName = "%s_%s" % (hName, SaveExtension + "_DataMinusEwk") drawPlot(p2, saveName, rebin=1, xlabel=xLabel, ylabel=yLabel) counter = counter+1 return
def Save(self, name): if len(self.histogramsNotFound) > 0: for name in self.histogramsNotFound: print "Histo", name, "not found" self.histogramsNotFound = [] return hObserved = self.histograms[self.FindHistoIndex( self.dataHistos[0].name)].Clone("Data") hObserved.Reset() for histo in self.dataHistos: hObserved.Add(self.histograms[self.FindHistoIndex(histo.label)]) print " Data: ", hObserved.Integral( 0, hObserved.GetNbinsX()), "events" hEstimatedEWKfake = self.histograms[self.FindHistoIndex( "EWKfake")].Clone("hEstimatedEWKfake") print " EWKfake: ", hEstimatedEWKfake.Integral( 0, hEstimatedEWKfake.GetNbinsX()), "events" hEstimatedEWK = self.histograms[self.FindHistoIndex("EWK")].Clone( "hEstimatedEWK") print " EWK: ", hEstimatedEWK.Integral( 0, hEstimatedEWK.GetNbinsX()), "events" hEstimatedEWK.Add(hEstimatedEWKfake) hEstimatedQCD = self.histograms[self.FindHistoIndex("QCD")].Clone( "hEstimatedQCD") print " QCD: ", hEstimatedQCD.Integral( 0, hEstimatedQCD.GetNbinsX()), "events" hEstimatedQCD.Add(hEstimatedEWK) hUncertainty = hEstimatedQCD.Clone("BackgrUncertainty") hUncertainty.SetFillColor(1) hUncertainty.SetFillStyle(3354) hUncertainty.SetLineColor(0) hUncertainty.SetLineStyle(0) hUncertainty.SetLineWidth(0) hUncertainty.SetMarkerColor(0) hUncertainty.SetMarkerSize(0) hSignal = self.histograms[self.FindHistoIndex("Signal")].Clone( "hSignal") print " Signal: ", hSignal.Integral(0, hSignal.GetNbinsX()), "events" hSignal.Add(hEstimatedQCD) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot(histograms.Histo(hObserved, "Data"), [ histograms.Histo(hUncertainty, "Backgr.Uncertainty"), histograms.Histo(hEstimatedEWKfake, "EWKfake"), histograms.Histo(hEstimatedEWK, "EWK"), histograms.Histo(hEstimatedQCD, "QCD"), histograms.Histo(hSignal, "Signal") ]) plot.histoMgr.forHisto("Data", styles.getDataStyle()) plot.histoMgr.forHisto("EWK", styles.getEWKStyle()) plot.histoMgr.forHisto("EWKfake", styles.getEWKFakeStyle()) plot.histoMgr.forHisto("QCD", styles.getQCDStyle()) plot.histoMgr.forHisto("Signal", styles.getSignalStyle()) plot.histoMgr.forHisto("Backgr.Uncertainty", styles.getErrorStyle()) plot.histoMgr.setHistoDrawStyleAll("HIST") plot.histoMgr.setHistoDrawStyle("Data", "EP") plot.histoMgr.setHistoDrawStyle("Backgr.Uncertainty", "E2") plot.histoMgr.setHistoLegendStyleAll("F") plot.histoMgr.setHistoLegendStyle("Data", "P") plot.histoMgr.setHistoLegendStyle("Signal", "L") plot.createFrame(name, opts={"ymin": 0, "ymaxfactor": 1.2}) plot.frame.GetXaxis().SetTitle(self.xtitle) plot.frame.GetYaxis().SetTitle(self.ytitle) plot.histoMgr.reorderLegend( ["Data", "Signal", "QCD", "EWK", "EWKfake", "Backgr.Uncertainty"]) self.setLegendLabels(plot) plot.setLegend(histograms.createLegend(0.55, 0.68, 0.9, 0.93)) histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=self.lumi) plot.draw() plot.save()
def main(): # Create all datasets from a multicrab task datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters) # As we use weighted counters for MC normalisation, we have to # update the all event count to a separately defined value because # the analysis job uses skimmed pattuple as an input datasets.updateNAllEventsToPUWeighted() # Read integrated luminosities of data datasets from lumi.json datasets.loadLuminosities() # Include only 120 mass bin of HW and HH datasets datasets.remove( filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames())) # Default merging nad ordering of data and MC datasets # All data datasets to "Data" # All QCD datasets to "QCD" # All single top datasets to "SingleTop" # WW, WZ, ZZ to "Diboson" plots.mergeRenameReorderForDataMC(datasets) # Set BR(t->H) to 0.2, keep BR(H->tau) in 1 xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1) # Merge WH and HH datasets to one (for each mass bin) # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX" plots.mergeWHandHH(datasets) # Merge EWK datasets datasets.merge("EWK", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"]) # Apply TDR style style = tdrstyle.TDRStyle() # Create the normalized plot of transverse mass # Read the histogram from the file #mT = plots.DataMCPlot(datasets, analysis+"/transverseMass") # Create the histogram from the tree (and see the selections explicitly) td = dataset.TreeDraw( analysis + "/tree", weight="weightPileup*weightTrigger*weightPrescale", selection="met_p4.Et() > 70 && Max$(jets_btag) > 1.7") # mT = plots.DataMCPlot(datasets, td.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))>>dist(400, 0, 400)")) # met = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.Et()>>dist(400, 0, 400)")) metBase = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets") metInver = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets") metBase4050 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJet4070") metInver4050 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets4070") metBase5060 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets5060") metInver5060 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets5060") metBase6070 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets6070") metInver6070 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets6070") metBase7080 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets7080") metInver7080 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets7080") metBase80100 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets80100") metInver80100 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets80100") metBase100120 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets100120") metInver100120 = plots.DataMCPlot( datasets, analysis + "/MET_InvertedTauIdJets100120") metBase120150 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets120150") metInver120150 = plots.DataMCPlot( datasets, analysis + "/MET_InvertedTauIdJets120150") metBase150 = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets150") metInver150 = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets150") # metInver = plots.DataMCPlot(datasets, analysis+"/MET_InvertedTauIdLoose") # Rebin before subtracting metBase.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) metInver.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) metBase4050.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) metInver4050.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) metInverted_data = metInver.histoMgr.getHisto("Data").getRootHisto().Clone( analysis + "/MET_InvertedTauIdJets") metInverted_data4050 = metInver.histoMgr.getHisto( "Data").getRootHisto().Clone(analysis + "/MET_InvertedTauIdJets4050") print "print inverted met" print metInverted_data.GetEntries() # Create the data-EWK histogram and draw it diffBase = dataEwkDiff(metBase, "MET_base_data-ewk") # diffInverted = dataEwkDiff(metInver,"MET_inverted_data-ewk") diffInverted = dataEwkNoDiff(metInver, "MET_inverted_data-ewk") diffBase4050 = dataEwkDiff(metBase, "MET_base_data-ewk-4050") # diffInverted4070 = dataEwkDiff(metInver,"MET_inverted_data-ewk-4070") diffInverted4050 = dataEwkNoDiff(metInver, "MET_inverted_data-ewk-4050") # Draw the MET distribution transverseMass(metBase, "MET_base") transverseMass(metInver, "MET_inverted") # Draw the MET distribution transverseMass(metBase4050, "MET_base4050") transverseMass(metInver4050, "MET_inverted4050") # Set the styles dataset._normalizeToOne(diffBase) dataset._normalizeToOne(diffInverted) plot = plots.ComparisonPlot(histograms.Histo(diffBase, "Baseline"), histograms.Histo(diffInverted, "Inverted")) dataset._normalizeToOne(diffBase4050) dataset._normalizeToOne(diffInverted4050) plot2 = plots.ComparisonPlot( histograms.Histo(diffBase4050, "Baseline4050"), histograms.Histo(diffInverted4050, "Inverted4050")) st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) plot.histoMgr.forHisto("Baseline", st1) plot.histoMgr.forHisto("Inverted", st2) plot.createFrame( "METbaseVSinverted-ewk", opts={ "xmax": 400, "ymin": 1e-5, "ymaxfactor": 1.5 }, createRatio=True, opts2={ "ymin": -5, "ymax": 6 }, # bounds of the ratio plot ) plot.getPad().SetLogy(True) plot.setLegend(histograms.createLegend(0.7, 0.68, 0.9, 0.93)) plot.frame.GetXaxis().SetTitle("MET (GeV)") plot.frame.GetYaxis().SetTitle("Data - EWK") # Draw the plot plot.draw() plot.save() plot2.createFrame( "METbaseVSinverted-ewk-4070", opts={ "xmax": 400, "ymin": 1e-5, "ymaxfactor": 1.5 }, createRatio=True, opts2={ "ymin": -5, "ymax": 6 }, # bounds of the ratio plot ) plot2.getPad().SetLogy(True) plot2.setLegend(histograms.createLegend(0.7, 0.68, 0.9, 0.93)) plot2.frame.GetXaxis().SetTitle("MET (GeV)") plot2.frame.GetYaxis().SetTitle("Data - EWK") # Draw the plot plot2.draw() plot2.save()
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") maxBin = h.GetXaxis().GetBinUpEdge(h.GetNbinsX()) if maxBin < myBinning[-1]: print WarningLabel( ) + "Adjust rebinning last bin from %.0f to %.0f because that is the up edge of last bin in the historam" % ( myBinning[-1], maxBin) myBinning[-1] = 500 myArray = array.array("d", myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning) - 1, "", myArray) histogramsExtras.makeFlowBinsVisible(h) return h #hbase.SetFillColor(ROOT.kGray) hbase.SetLineColor(ROOT.kGray) hbase.SetFillColor(hbase.GetLineColor()) hinv.SetLineColor(ROOT.kBlue) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events" % (hbase.Integral(), hinv.Integral()) toUnitArea = True if toUnitArea: hbase.Scale(1.0 / hbase.Integral()) hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="F") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST E", legendStyle="l") plot = plots.ComparisonPlot(invHisto, baseHisto) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) if toUnitArea: plot.appendPlotObject( histograms.PlotText(0.5, 0.6, "Normalized to unit area", size=20)) myPlotName = "%s/QCDInv_ClosureTest_%s" % (myDir, histoName) myParams = {} if toUnitArea: myParams["ylabel"] = "A.u. " else: myParams["ylabel"] = "< Events / GeV >" myParams["xlabel"] = "m_{T} (GeV)" myParams["log"] = False myParams["opts2"] = {"ymin": 0.0, "ymax": 2.0} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Anti-isol./Isol." myParams["ratioCreateLegend"] = True myParams["ratioMoveLegend"] = {"dx": -0.05, "dy": -0.4, "dh": -0.1} myParams["cmsTextPosition"] = "right" myParams["addLuminosityText"] = True myParams["divideByBinWidth"] = True plots._legendLabels["BackgroundStatError"] = "Isol. stat. unc." plots.drawPlot(plot, myPlotName, **myParams)