def __init__(self, datasets, name, lumi=None): self.histos = HistoManager(datasets, name) #print "\n".join(histos.getDatasetNames()) if lumi == None: self.histos.normalizeMCByLuminosity() else: self.histos.normalizeMCToLuminosity(lumi) hasData = self.histos.hasHisto("Data") styleGenerator.reset() self.histos.forEachMCHisto(styleGenerator) if hasData: styles.getDataStyle()(self.histos.getHisto("Data")) self.histos.setHistoDrawStyle("Data", "EP")
def distComparison(datasets): # Create a comparison plot of two distributions (must have the same binning) # Set the names of DatasetRootHisto objects in order to be able easily reference them later drh1 = datasets.getDataset("Data").getDatasetRootHisto(analysis+"/MET_BaseLineTauId") drh1.setName("Base") drh1.normalizeToOne() drh2 = datasets.getDataset("Data").getDatasetRootHisto(analysis+"/MET_InvertedTauId") drh2.setName("Inv") drh2.normalizeToOne() plot = plots.ComparisonPlot(drh1, drh2) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) plot.histoMgr.forHisto("Base", st1) plot.histoMgr.forHisto("Inv", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({"Base": "Baseline Tau ID", "Inv": "Inverted Tau ID"}) # Set the legend styles plot.histoMgr.setHistoLegendStyleAll("L") plot.histoMgr.setHistoLegendStyle("Base", "P") # exception to the general rule # Set the drawing styles plot.histoMgr.setHistoDrawStyleAll("HIST") plot.histoMgr.setHistoDrawStyle("Base", "EP") # exception to the general rule # Rebin, if necessary plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) # Create frame with a ratio pad plot.createFrame("METbaseVSinvertedTauID", opts={"ymin":1e-5, "ymaxfactor": 1.5}, createRatio=True, opts2={"ymin": -10, "ymax": 50}, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad1().SetLogy(True) # Create legend to the default position plot.setLegend(histograms.createLegend()) # Set the X/Y axis labels plot.frame.GetXaxis().SetTitle("MET (GeV)") plot.frame.GetYaxis().SetTitle("Arbitrary units") # Draw the plot plot.draw() # Add the various texts to histograms.addCmsPreliminaryText() histograms.addEnergyText() histograms.addLuminosityText(x=None, y=None, lumi=datasets.getDataset("Data").getLuminosity()) # Save the plot to files plot.save()
def distComparison(datasets): # Create a comparison plot of two distributions (must have the same binning) # Set the names of DatasetRootHisto objects in order to be able easily reference them later drh1 = datasets.getDataset("Data").getDatasetRootHisto("ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections") drh1.setName("AfterStandardSelections") drh2 = datasets.getDataset("Data").getDatasetRootHisto("ForDataDrivenCtrlPlots/SelectedTau_pT_AfterMtSelections") drh2.setName("AfterMtSelections") plot = plots.ComparisonPlot(drh1, drh2) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) plot.histoMgr.forHisto("AfterStandardSelections", st1) plot.histoMgr.forHisto("AfterMtSelections", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({"AfterStandardSelections": "After standard selections", "AfterMtSelections": "After all selections"}) # Set the legend styles plot.histoMgr.setHistoLegendStyleAll("L") #plot.histoMgr.setHistoLegendStyle("afterTauID", "P") # exception to the general rule # Set the drawing styles plot.histoMgr.setHistoDrawStyleAll("HIST") #plot.histoMgr.setHistoDrawStyleAll("afterTauID", "EP") # exception to the general rule # Rebin, if necessary plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) # Create frame with a ratio pad plot.createFrame("tauPtComparison", opts={"ymin":1e-1, "ymaxfactor": 10}, createRatio=True, opts2={"ymin": 0, "ymax": 150}, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad1().SetLogy(True) # Create legend to the default position plot.setLegend(histograms.createLegend()) # Set the X/Y axis labels plot.frame.GetXaxis().SetTitle("Tau p_{T} (GeV/c)") plot.frame.GetYaxis().SetTitle("Number of events") # Draw the plot plot.draw() # Add the various texts to histograms.addStandardTexts(lumi=datasets.getDataset("Data").getLuminosity()) # Save the plot to files plot.save()
def plotIntegral(self, plot_orig, objectName, canvasName="Integral"): # plot = copy.deepcopy(plot_orig) plot = plot_orig st = styles.getDataStyle().clone() st.append(styles.StyleFill(fillColor=ROOT.kYellow)) plot.histoMgr.forHisto(objectName, st) plot.setFrameName(plot.cf.canvas.GetName() + canvasName) plot.draw() plot.save() st.append(styles.StyleFill(fillColor=0)) plot.histoMgr.forHisto(objectName, st)
def plotIntegral(self, plot_orig, objectName, canvasName = "Integral"): # plot = copy.deepcopy(plot_orig) plot = plot_orig st = styles.getDataStyle().clone() st.append(styles.StyleFill(fillColor=ROOT.kYellow)) plot.histoMgr.forHisto(objectName, st) plot.setFrameName(plot.cf.canvas.GetName()+canvasName) plot.draw() plot.save() st.append(styles.StyleFill(fillColor=0)) plot.histoMgr.forHisto(objectName, st)
### Normalize the area of *all* histograms to 1 #tauNProngs.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults tauNProngs.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles tauNProngs.setHistoLegendStyleAll("F") tauNProngs.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) tauNProngs.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking tauNProngs.forHisto("Data", styles.getDataStyle()) #tauNProngs.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #tauNProngs.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(tauNProngs, "tauNProngs", ymin=0.01, ymax=None, xmin=0.0, xmax=15.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#tau-jet nProngs")
def doPlotsWTauMu(datasetsEmb, name, btag=True): if btag: selection = And(metCut, bTaggingCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger*weightBTagging") else: selection = And(metCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger") tdMt = treeDraw.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)") (hall, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=selection)) (hpure, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24"))) tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff")) heff = datasetsEmb.getEfficiency(name, tdEff.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")), tdEff.clone(selection=selection)) hall.SetName("All") hpure.SetName("Pure") nall = hall.Integral(0, hall.GetNbinsX()) npure = hpure.Integral(0, hall.GetNbinsX()) print {True: "Btagging", False: "NoBTag"}[btag], npure/nall, (1-npure/nall)*100 p = plots.ComparisonPlot(hall, hpure) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) if btag: fname = "transverseMass_4AfterDeltaPhi160_wtaumu_"+name else: fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_"+name hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue-7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed-7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05}) styles.getDataStyle().apply(heff) p.setRatios([heff]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1-0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) p.appendPlotObjectToRatio(histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})") p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth()) p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18)) p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.save()
### Normalize the area of *all* histograms to 1 #TauLeadTrk.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauLeadTrk.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles TauLeadTrk.setHistoLegendStyleAll("F") TauLeadTrk.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauLeadTrk.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking TauLeadTrk.forHisto("Data", styles.getDataStyle()) #TauLeadTrk.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation TauLeadTrk.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauLeadTrk, "TauLeadTrk", ymin=0.01, ymax=None, xmin=0.0, xmax=100.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#tau-jet, Ldg Trk p_{T} (GeV/c)")
### Normalize the area of *all* histograms to 1 #Rtau.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults Rtau.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles Rtau.setHistoLegendStyleAll("F") Rtau.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) Rtau.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking Rtau.forHisto("Data", styles.getDataStyle()) #Rtau.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #Rtau.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(Rtau, "Rtau", ymin=0.01, ymax=None, xmin=0.0, xmax=1.05) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("R_{#tau}") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) Rtau.addToLegend(legend)
def doPlotsWTauMu(datasets, name, datasetName, ntupleCache, selectorName, unweighted, fitFunction, rebin=None): ds = datasets.getDataset(datasetName) # Take first unweighted histograms for the fraction plot drh_all = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection" + unweighted, selectorName)) drh_pure = ds.getDatasetRootHisto( ntupleCache.histogram( "selectedMuonPt_AfterJetSelection_MuFromW" + unweighted, selectorName)) def Rebin(th1, div=False): if rebin is None: return th1 else: h = th1.Rebin( len(rebin) - 1, th1.GetName(), array.array("d", rebin)) if div: h.Scale(1, "width") return h def createTEfficiency(drhAll, drhPure): hallUn = Rebin(drhAll.getHistogram()) hpureUn = Rebin(drhPure.getHistogram()) teff = ROOT.TEfficiency(hpureUn, hallUn) teff.SetDirectory(0) teff.SetWeight(drhAll.getDataset().getCrossSection()) return teff teffs = drh_all.forEach(createTEfficiency, drh_pure) #coll = ROOT.TList() #for o in teffs: # coll.AddLast(o) #ratio = ROOT.TEfficiency.Combine(coll) ratio = teffs[0] for e in teffs[1:]: ratio.Add(e) styles.getDataStyle().apply(ratio) ratio.SetName(datasetName) ROOT.gStyle.SetStatY(0.99) ROOT.gStyle.SetStatX(0.52) ROOT.gStyle.SetStatW(0.18) ROOT.gStyle.SetStatH(0.23) expFit = ROOT.TF1("purityFit", [ "1/(1+[0]*exp(-[1]*x))", "1-[0]*exp(-[1]*x)", "1-([0]/(x^[1]))", ][fitFunction], aux.th1Xmin(ratio.GetPassedHistogram()), aux.th1Xmax(ratio.GetPassedHistogram())) expFit.SetParameter(0, 0.05) ratio.Fit(expFit, "N") expFit.SetLineColor(ROOT.kRed) expFit.SetLineWidth(2) # expFit = None # Then the correctly weighted for the main plot drh_all = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection", selectorName)) drh_pure = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection_MuFromW", selectorName)) if mcOnly: lumi = mcLuminosity else: lumi = datasets.getDataset("Data").getLuminosity() drh_all.normalizeToLuminosity(lumi) drh_pure.normalizeToLuminosity(lumi) hall = Rebin(drh_all.getHistogram(), div=True) hpure = Rebin(drh_pure.getHistogram(), div=True) hall.SetName("All") hpure.SetName("Pure") p = plots.ComparisonPlot(hall, hpure) p.setLuminosity(lumi) p.setEnergy(ds.getEnergy()) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", # "Pure": "W#rightarrow#tau#rightarrow#mu" "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue - 7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed - 7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame(era + "_" + name + "_selectedMuonPt_AFterJetSelection_MuFromW_%s_fit%d" % (datasetName, fitFunction) + unweighted, createRatio=True, opts={ "ymin": 1e-1, "ymaxfactor": 2 }, opts2={ "ymin": 0.9, "ymax": 1.05 }) p.setRatios([ratio]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1 - 0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.appendPlotObjectToRatio( histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue)) if expFit is not None: p.appendPlotObjectToRatio(expFit) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.getPad().SetLogy(True) p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)") p.frame.GetYaxis().SetTitle("Events / #Deltap_{T} %.0f-%.0f GeV/c" % (min(p.binWidths()), max(p.binWidths()))) p.appendPlotObject( histograms.PlotText(0.5, 0.9, plots._legendLabels.get(datasetName, datasetName), size=18)) p.draw() p.addStandardTexts() p.save() # Clear list of functions ratio.GetListOfFunctions().Delete() return (ratio, expFit)
#TauIsoMaxlTrkPt.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauIsoMaxlTrkPt.setHistoLegendLabelMany( legendLabels) # many datasets, with dict ### Example how to modify legend styles TauIsoMaxlTrkPt.setHistoLegendStyleAll("F") TauIsoMaxlTrkPt.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauIsoMaxlTrkPt.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking TauIsoMaxlTrkPt.forHisto("Data", styles.getDataStyle()) #TauIsoMaxlTrkPt.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #TauIsoMaxlTrkPt.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauIsoMaxlTrkPt, "TauIsoMaxlTrkPt", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle(
### Normalize the area of *all* histograms to 1 #TauLeadTrk.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauLeadTrk.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles TauLeadTrk.setHistoLegendStyleAll("F") TauLeadTrk.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauLeadTrk.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking TauLeadTrk.forHisto("Data", styles.getDataStyle()) #TauLeadTrk.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation TauLeadTrk.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauLeadTrk, "TauLeadTrk", ymin=0.01, ymax=None, xmin=0.0, xmax=100.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#tau-jet, Ldg Trk p_{T} (GeV/c)") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) TauLeadTrk.addToLegend(legend)
#TauNTrksVSPtcut.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauNTrksVSPtcut.setHistoLegendLabelMany( legendLabels) # many datasets, with dict ### Example how to modify legend styles TauNTrksVSPtcut.setHistoLegendStyleAll("F") TauNTrksVSPtcut.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauNTrksVSPtcut.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking TauNTrksVSPtcut.forHisto("Data", styles.getDataStyle()) #TauNTrksVSPtcut.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #TauNTrksVSPtcut.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauNTrksVSPtcut, "TauNTrksVSPtcut", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("???")
### Normalize the area of *all* histograms to 1 #TauIsoMaxlTrkPt.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauIsoMaxlTrkPt.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles TauIsoMaxlTrkPt.setHistoLegendStyleAll("F") TauIsoMaxlTrkPt.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauIsoMaxlTrkPt.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking TauIsoMaxlTrkPt.forHisto("Data", styles.getDataStyle()) #TauIsoMaxlTrkPt.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #TauIsoMaxlTrkPt.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauIsoMaxlTrkPt, "TauIsoMaxlTrkPt", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#tau-jet, Max Ldg Trk in Isol Annulus, p_{T} (GeV/c)") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) TauIsoMaxlTrkPt.addToLegend(legend)
### Normalize the area of *all* histograms to unity. Canno be used with mergeDatasets #transverseMass.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults transverseMass.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles transverseMass.setHistoLegendStyleAll("F") transverseMass.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) transverseMass.forEachMCHisto(styles.generator(fill=True)) transverseMass.forHisto("Data", styles.getDataStyle()) #transverseMass.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #transverseMass.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(transverseMass, "transverseMass", ymin=0.01, ymax=None, xmin=0.0, xmax=300.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("M_{T} GeV/c^{2}") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) transverseMass.addToLegend(legend)
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 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()
### Normalize the area of *all* histograms to 1 #tauInvMass.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults tauInvMass.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles tauInvMass.setHistoLegendStyleAll("F") tauInvMass.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) tauInvMass.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking tauInvMass.forHisto("Data", styles.getDataStyle()) #tauInvMass.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #tauInvMass.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(tauInvMass, "tau_InvMass", ymin=0.01, ymax=None, xmin=0.0, xmax=2.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("Inv-Mass (GeV/c^{2})") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) tauInvMass.addToLegend(legend)
import ROOT ROOT.gROOT.SetBatch(True) ROOT.PyConfig.IgnoreCommandLineOptions = True import HiggsAnalysis.HeavyChHiggsToTauNu.tools.dataset as dataset import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots import HiggsAnalysis.HeavyChHiggsToTauNu.tools.counter as counter import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tauEmbedding as tauEmbedding analysisEmb = "signalAnalysis" dataEra = "Run2012ABCD" myStyles = [styles.getDataStyle()] for st in styles.getStyles(): myStyles.append(st) #myStyles.append(styles.StyleCompound([st, styles.StyleLine(lineStyle=2)])) def main(): dirAve = "." # dirSeeds = [] # inputInfoPath = os.path.join(dirAve, "inputInfo.txt") # f = open(inputInfoPath) # input_re = re.compile("Embedded input directory: (?P<dir>\S+)") # for line in f: # m = input_re.search(line) # if m: # dirSeeds.append(os.path.join("..", m.group("dir")))
def distComparison(datasets): # Create a comparison plot of two distributions (must have the same binning) # Set the names of DatasetRootHisto objects in order to be able easily reference them later drh1 = datasets.getDataset("Data").getDatasetRootHisto( analysis + "/MET_BaseLineTauId") drh1.setName("Base") drh1.normalizeToOne() drh2 = datasets.getDataset("Data").getDatasetRootHisto( analysis + "/MET_InvertedTauId") drh2.setName("Inv") drh2.normalizeToOne() plot = plots.ComparisonPlot(drh1, drh2) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) plot.histoMgr.forHisto("Base", st1) plot.histoMgr.forHisto("Inv", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({ "Base": "Baseline Tau ID", "Inv": "Inverted Tau ID" }) # Set the legend styles plot.histoMgr.setHistoLegendStyleAll("L") plot.histoMgr.setHistoLegendStyle("Base", "P") # exception to the general rule # Set the drawing styles plot.histoMgr.setHistoDrawStyleAll("HIST") plot.histoMgr.setHistoDrawStyle("Base", "EP") # exception to the general rule # Rebin, if necessary plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) # Create frame with a ratio pad plot.createFrame( "METbaseVSinvertedTauID", opts={ "ymin": 1e-5, "ymaxfactor": 1.5 }, createRatio=True, opts2={ "ymin": -10, "ymax": 50 }, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad1().SetLogy(True) # Create legend to the default position plot.setLegend(histograms.createLegend()) # Set the X/Y axis labels plot.frame.GetXaxis().SetTitle("MET (GeV)") plot.frame.GetYaxis().SetTitle("Arbitrary units") # Draw the plot plot.draw() # Add the various texts to plot.setLuminosity(datasets.getDataset("Data").getLuminosity()) plot.addStandardTexts() # Save the plot to files plot.save()
### Normalize the area of *all* histograms to 1 #tauNProngs.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults tauNProngs.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles tauNProngs.setHistoLegendStyleAll("F") tauNProngs.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) tauNProngs.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking tauNProngs.forHisto("Data", styles.getDataStyle()) #tauNProngs.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #tauNProngs.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(tauNProngs, "tauNProngs", ymin=0.01, ymax=None, xmin=0.0, xmax=15.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#tau-jet nProngs") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) tauNProngs.addToLegend(legend)
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 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 doPlotsWTauMu(datasetsEmb, name, btag=True): if btag: selection = And(metCut, bTaggingCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw( analysisEmb + "/tree", weight="weightPileup*weightTrigger*weightBTagging") else: selection = And(metCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw(analysisEmb + "/tree", weight="weightPileup*weightTrigger") tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) (hall, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=selection)) (hpure, tmp) = datasetsEmb.getHistogram( name, tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24"))) tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff")) heff = datasetsEmb.getEfficiency( name, tdEff.clone( selection=And(selection, "abs(temuon_mother_pdgid) == 24")), tdEff.clone(selection=selection)) hall.SetName("All") hpure.SetName("Pure") nall = hall.Integral(0, hall.GetNbinsX()) npure = hpure.Integral(0, hall.GetNbinsX()) print { True: "Btagging", False: "NoBTag" }[btag], npure / nall, (1 - npure / nall) * 100 p = plots.ComparisonPlot(hall, hpure) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) if btag: fname = "transverseMass_4AfterDeltaPhi160_wtaumu_" + name else: fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_" + name hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue - 7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed - 7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05}) styles.getDataStyle().apply(heff) p.setRatios([heff]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1 - 0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) p.appendPlotObjectToRatio( histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})") p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth()) p.appendPlotObject( histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18)) p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.save()
### Normalize the area of *all* histograms to 1 #alphaT.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults alphaT.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles alphaT.setHistoLegendStyleAll("F") alphaT.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) alphaT.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking alphaT.forHisto("Data", styles.getDataStyle()) #alphaT.setHistoDrawStyle("Data", "EP") #alphaT.forHisto("BTau_146240-147116", styles.getDataStyle()) #alphaT.setHistoDrawStyle("BTau_146240-147116", "EP") #alphaT.forHisto("BTau_141950-144114", styles.getDataStyle()) #alphaT.setHistoDrawStyle("BTau_141950-144114", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation alphaT.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(alphaT, "alphaT", ymin=0.01, ymax=None, xmin=0.0, xmax=1.2) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("#alpha_{T}") cf.frame.GetYaxis().SetTitle(ylabel)
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()
### Normalize the area of *all* histograms to 1 #TauNTrksVSPtcut.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauNTrksVSPtcut.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles TauNTrksVSPtcut.setHistoLegendStyleAll("F") TauNTrksVSPtcut.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauNTrksVSPtcut.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking TauNTrksVSPtcut.forHisto("Data", styles.getDataStyle()) #TauNTrksVSPtcut.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #TauNTrksVSPtcut.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauNTrksVSPtcut, "TauNTrksVSPtcut", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("???") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) TauNTrksVSPtcut.addToLegend(legend)
### Normalize the area of *all* histograms to 1 #alphaTInvMass.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults alphaTInvMass.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles alphaTInvMass.setHistoLegendStyleAll("F") alphaTInvMass.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) alphaTInvMass.forEachMCHisto(styles.generator( fill=True)) # Apply SetFillColor too, needed for histogram stacking alphaTInvMass.forHisto("Data", styles.getDataStyle()) #alphaTInvMass.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #alphaTInvMass.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(alphaTInvMass, "alphaTInvMass", ymin=0.01, ymax=None, xmin=0.0, xmax=1000.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("Di-jet InvMass [GeV/c^{2}]")
### Normalize the area of *all* histograms to 1 #TauIsoltrkPtsumVSPtcut.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults TauIsoltrkPtsumVSPtcut.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles TauIsoltrkPtsumVSPtcut.setHistoLegendStyleAll("F") TauIsoltrkPtsumVSPtcut.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) TauIsoltrkPtsumVSPtcut.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking TauIsoltrkPtsumVSPtcut.forHisto("Data", styles.getDataStyle()) #TauIsoltrkPtsumVSPtcut.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #TauIsoltrkPtsumVSPtcut.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(TauIsoltrkPtsumVSPtcut, "TauIsoltrkPtsumVSPtcut", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("???") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) TauIsoltrkPtsumVSPtcut.addToLegend(legend)
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 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 distComparison(datasets): # Create a comparison plot of two distributions (must have the same binning) # Set the names of DatasetRootHisto objects in order to be able easily reference them later drh1 = datasets.getDataset("Data").getDatasetRootHisto( "ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections") drh1.setName("AfterStandardSelections") drh2 = datasets.getDataset("Data").getDatasetRootHisto( "ForDataDrivenCtrlPlots/SelectedTau_pT_AfterMtSelections") drh2.setName("AfterMtSelections") plot = plots.ComparisonPlot(drh1, drh2) # Set the styles st1 = styles.getDataStyle().clone() st2 = st1.clone() st2.append(styles.StyleLine(lineColor=ROOT.kRed)) plot.histoMgr.forHisto("AfterStandardSelections", st1) plot.histoMgr.forHisto("AfterMtSelections", st2) # Set the legend labels plot.histoMgr.setHistoLegendLabelMany({ "AfterStandardSelections": "After standard selections", "AfterMtSelections": "After all selections" }) # Set the legend styles plot.histoMgr.setHistoLegendStyleAll("L") #plot.histoMgr.setHistoLegendStyle("afterTauID", "P") # exception to the general rule # Set the drawing styles plot.histoMgr.setHistoDrawStyleAll("HIST") #plot.histoMgr.setHistoDrawStyleAll("afterTauID", "EP") # exception to the general rule # Rebin, if necessary plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10)) # Create frame with a ratio pad plot.createFrame( "tauPtComparison", opts={ "ymin": 1e-1, "ymaxfactor": 10 }, createRatio=True, opts2={ "ymin": 0, "ymax": 150 }, # bounds of the ratio plot ) # Set Y axis of the upper pad to logarithmic plot.getPad1().SetLogy(True) # Create legend to the default position plot.setLegend(histograms.createLegend()) # Set the X/Y axis labels plot.frame.GetXaxis().SetTitle("Tau p_{T} (GeV/c)") plot.frame.GetYaxis().SetTitle("Number of events") # Draw the plot plot.draw() # Add the various texts to histograms.addStandardTexts( lumi=datasets.getDataset("Data").getLuminosity()) # Save the plot to files plot.save()
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 Save(self, name): hObserved = self.CreateGraph("Observed") hExpected = self.CreateGraph("Expected") hExpected1s = self.CreateGraph("Expected1") hExpected1s.SetFillColor(ROOT.kYellow) hExpected2s = self.CreateGraph("Expected2") hExpected2s.SetFillColor(ROOT.kOrange) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot( histograms.HistoGraph(hObserved, "Observed"), [ histograms.HistoGraph(hExpected, "Expected"), histograms.HistoGraph(hExpected1s, "Expected1"), histograms.HistoGraph(hExpected2s, "Expected2") ]) obsStyle = styles.getDataStyle().clone() plot.histoMgr.forHisto("Observed", styles.getDataStyle().clone()) plot.histoMgr.setHistoDrawStyle("Observed", "PL") expStyle = styles.getDataStyle().clone() expStyle.append(styles.StyleLine(lineStyle=2)) expStyle.append(styles.StyleLine(lineColor=ROOT.kRed)) expStyle.append(styles.StyleMarker(markerStyle=ROOT.kFullSquare)) expStyle.append(styles.StyleMarker(markerColor=ROOT.kRed)) plot.histoMgr.forHisto("Expected", expStyle) plot.histoMgr.setHistoDrawStyle("Expected", "PL") plot.histoMgr.setHistoDrawStyle("Expected1", "PL3") plot.histoMgr.setHistoDrawStyle("Expected2", "PL3") plot.createFrame(name, opts={ "xmin": 70.1, "xmax": 169.9, "ymin": 0, "ymax": 0.2 }) plot.frame.GetXaxis().SetTitle(self.xtitle) plot.frame.GetYaxis().SetTitle(self.ytitle) plot.histoMgr.setHistoLegendStyle("Observed", "PL") plot.histoMgr.setHistoLegendStyle("Expected", "PL") plot.histoMgr.setHistoLegendStyle("Expected1", "F") plot.histoMgr.setHistoLegendStyle("Expected2", "F") plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected median", "Expected1": "Expected median #pm1#sigma", "Expected2": "Expected median #pm2#sigma" }) 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) textSize = 16 textX = 0.19 textY = 0.8 textDY = 0.038 histograms.addText(textX, textY + 2 * textDY, "t#rightarrowbH^{#pm}, H^{#pm}#rightarrow#tau#nu", textSize) histograms.addText(textX, textY + textDY, "Fully hadronic final state", textSize) histograms.addText(textX, textY, "BR(H^{#pm}#rightarrow#tau^{#pm} #nu) = 1", textSize) plot.draw() plot.save()
### Normalize the area of *all* histograms to unity. Canno be used with mergeDatasets #transverseMass.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults transverseMass.setHistoLegendLabelMany( legendLabels) # many datasets, with dict ### Example how to modify legend styles transverseMass.setHistoLegendStyleAll("F") transverseMass.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) transverseMass.forEachMCHisto(styles.generator(fill=True)) transverseMass.forHisto("Data", styles.getDataStyle()) #transverseMass.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #transverseMass.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(transverseMass, "transverseMass", ymin=0.01, ymax=None, xmin=0.0, xmax=300.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("M_{T} GeV/c^{2}")
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")
### Normalize the area of *all* histograms to 1 #NSelJets.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults NSelJets.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles NSelJets.setHistoLegendStyleAll("F") NSelJets.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) NSelJets.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking NSelJets.forHisto("Data", styles.getDataStyle()) #NSelJets.setHistoDrawStyle("Data", "EP") NSelJets.forHisto("BTau_146240-147116", styles.getDataStyle()) NSelJets.setHistoDrawStyle("BTau_146240-147116", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation NSelJets.stackMCHistograms() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(NSelJets, "NSelJets", ymin=0.01, ymax=None, xmin=0.0, xmax=10.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("Number of Selected Jets") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend
def main(): # Create all datasets from a multicrab task datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters) # 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()
import ROOT ROOT.gROOT.SetBatch(True) ROOT.PyConfig.IgnoreCommandLineOptions = True import HiggsAnalysis.HeavyChHiggsToTauNu.tools.dataset as dataset import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots import HiggsAnalysis.HeavyChHiggsToTauNu.tools.counter as counter import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tauEmbedding as tauEmbedding analysisEmb = "signalAnalysis" dataEra = "Run2012ABCD" myStyles = [styles.getDataStyle()] for st in styles.getStyles(): myStyles.append(st) #myStyles.append(styles.StyleCompound([st, styles.StyleLine(lineStyle=2)])) def main(): dirAve = "." # dirSeeds = [] # inputInfoPath = os.path.join(dirAve, "inputInfo.txt") # f = open(inputInfoPath) # input_re = re.compile("Embedded input directory: (?P<dir>\S+)") # for line in f: # m = input_re.search(line) # if m: # dirSeeds.append(os.path.join("..", m.group("dir"))) # f.close()
def Save(self,name): hObserved = self.CreateGraph("Observed") hExpected = self.CreateGraph("Expected") hExpected1s = self.CreateGraph("Expected1") hExpected1s.SetFillColor(ROOT.kYellow) hExpected2s = self.CreateGraph("Expected2") hExpected2s.SetFillColor(ROOT.kOrange) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot( histograms.HistoGraph(hObserved, "Observed"), [ histograms.HistoGraph(hExpected, "Expected"), histograms.HistoGraph(hExpected1s, "Expected1"), histograms.HistoGraph(hExpected2s, "Expected2") ] ) obsStyle = styles.getDataStyle().clone() plot.histoMgr.forHisto("Observed", styles.getDataStyle().clone()) plot.histoMgr.setHistoDrawStyle("Observed", "PL") expStyle = styles.getDataStyle().clone() expStyle.append(styles.StyleLine(lineStyle=2)) expStyle.append(styles.StyleLine(lineColor=ROOT.kRed)) expStyle.append(styles.StyleMarker(markerStyle=ROOT.kFullSquare)) expStyle.append(styles.StyleMarker(markerColor=ROOT.kRed)) plot.histoMgr.forHisto("Expected", expStyle) plot.histoMgr.setHistoDrawStyle("Expected", "PL") plot.histoMgr.setHistoDrawStyle("Expected1", "PL3") plot.histoMgr.setHistoDrawStyle("Expected2", "PL3") plot.createFrame(name, opts={"xmin": 70.1, "xmax": 169.9, "ymin":0, "ymax": 0.2}) plot.frame.GetXaxis().SetTitle(self.xtitle) plot.frame.GetYaxis().SetTitle(self.ytitle) plot.histoMgr.setHistoLegendStyle("Observed", "PL") plot.histoMgr.setHistoLegendStyle("Expected", "PL") plot.histoMgr.setHistoLegendStyle("Expected1", "F") plot.histoMgr.setHistoLegendStyle("Expected2", "F") plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected median", "Expected1": "Expected median #pm1#sigma", "Expected2": "Expected median #pm2#sigma" }) 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) textSize = 16 textX = 0.19 textY = 0.8 textDY = 0.038 histograms.addText(textX,textY+2*textDY,"t#rightarrowbH^{#pm}, H^{#pm}#rightarrow#tau#nu",textSize) histograms.addText(textX,textY+textDY,"Fully hadronic final state",textSize) histograms.addText(textX,textY,"BR(H^{#pm}#rightarrow#tau^{#pm} #nu) = 1",textSize) plot.draw() plot.save()
# tauPts.normalizeToOne() # ylabel = "A.u." # Example how to set legend labels from defaults # tauPts.setHistoLegendLabel("TTbar_Htaunu_M80", "H^{#pm} M=80") # one dataset at a time tauPts.setHistoLegendLabelMany(legendLabels) # many datasets, with dict # Example how to modify legend styles tauPts.setHistoLegendStyleAll("F") tauPts.setHistoLegendStyle("Data", "p") # Apply the default styles (for all histograms, for MC histograms, for a single histogram) # tauPts.forEachHisto(styles.generator()) # tauPts.forEachMCHisto(styles.generator(fill=True, fillStyle=3002)) # Example how to set non-default fill style tauPts.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking tauPts.forHisto("Data", styles.getDataStyle()) tauPts.setHistoDrawStyle("Data", "EP") # Example how to stack all MC datasets # Note: this MUST be done after all legend/style manipulation tauPts.stackMCHistograms() # Example how to add MC uncertainty tauPts.addMCUncertainty(styles.getErrorStyle()) # tauPts.addMCUncertainty(styles.getErrorStyle(), "MC uncertainty") # Create TCanvas and TH1F such that they cover all histograms cf = histograms.CanvasFrame(tauPts, "taupt") # cf = histograms.CanvasFrame(tauPts, "taupt", ymin=10, ymax=1e9) # for logy
def main(): datasets = dataset.getDatasetsFromMulticrabCfg(weightedCounters=False) 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 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()
### Normalize the area of *all* histograms to 1 #NBtagJets.normalizeToOne() #ylabel = "a.u" ############################### STYLES ############################### ### Example how to set legend labels from defaults NBtagJets.setHistoLegendLabelMany(legendLabels) # many datasets, with dict ### Example how to modify legend styles NBtagJets.setHistoLegendStyleAll("F") NBtagJets.setHistoLegendStyle("Data", "p") ### Apply the default styles (for all histograms, for MC histograms, for a single histogram) NBtagJets.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking NBtagJets.forHisto("Data", styles.getDataStyle()) #NBtagJets.setHistoDrawStyle("Data", "EP") ### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation #NBtagJets.stackMCDatasets() ### Create TCanvas and TH1F such that they cover all histograms cf = CanvasFrame(NBtagJets, "NBtagJets", ymin=0.01, ymax=None, xmin=0.0, xmax=8.0) ### Set the frame options, e.g. axis labels cf.frame.GetXaxis().SetTitle("Number of Btag Jets") cf.frame.GetYaxis().SetTitle(ylabel) ### Legend legend = createLegend(0.7, 0.5, 0.9, 0.8) NBtagJets.addToLegend(legend)