Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
df105_WBosonAnalysis.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_dataframe
3## \notebook -draw
4## The W boson mass analysis from the ATLAS Open Data release of 2020, with RDataFrame.
5##
6## This tutorial is the analysis of the W boson mass taken from the ATLAS Open Data release in 2020
7## (http://opendata.atlas.cern/release/2020/documentation/). The data was recorded with the ATLAS detector
8## during 2016 at a center-of-mass energy of 13 TeV. W bosons are produced frequently at the LHC and
9## are an important background to studies of Standard Model processes, for example the Higgs boson analyses.
10##
11## The analysis is translated to a RDataFrame workflow processing up to 60 GB of simulated events and data.
12## By default the analysis runs on a preskimmed dataset to reduce the runtime. The full dataset can be used with
13## the --full-dataset argument and you can also run only on a fraction of the original dataset using the argument --lumi-scale.
14##
15## \macro_image
16## \macro_code
17## \macro_output
18##
19## \date March 2020
20## \author Stefan Wunsch (KIT, CERN)
21
22import ROOT
23import sys
24import json
25import argparse
26import os
27
28# Argument parsing
29parser = argparse.ArgumentParser()
30parser.add_argument("--lumi-scale", type=float, default=0.001,
31 help="Run only on a fraction of the total available 10 fb^-1 (only usable together with --full-dataset)")
32parser.add_argument("--full-dataset", action="store_true", default=False,
33 help="Use the full dataset (use --lumi-scale to run only on a fraction of it)")
34parser.add_argument("-b", action="store_true", default=False, help="Use ROOT batch mode")
35parser.add_argument("-t", action="store_true", default=False, help="Use implicit multi threading (for the full dataset only possible with --lumi-scale 1.0)")
36if 'df105_WBosonAnalysis.py' in sys.argv[0]:
37 # Script
38 args = parser.parse_args()
39else:
40 # Notebook
41 args = parser.parse_args(args=[])
42
43if args.b: ROOT.gROOT.SetBatch(True)
44if args.t: ROOT.EnableImplicitMT()
45
46if not args.full_dataset: lumi_scale = 0.001 # The preskimmed dataset contains only 0.01 fb^-1
47else: lumi_scale = args.lumi_scale
48lumi = 10064.0
49print('Run on data corresponding to {:.2f} fb^-1 ...'.format(lumi * lumi_scale / 1000.0))
50
51if args.full_dataset: dataset_path = "root://eospublic.cern.ch//eos/opendata/atlas/OutreachDatasets/2020-01-22"
52else: dataset_path = "root://eospublic.cern.ch//eos/root-eos/reduced_atlas_opendata/w"
53
54# Create a ROOT dataframe for each dataset
55# Note that we load the filenames from the external json file placed in the same folder than this script.
56files = json.load(open(os.path.join(ROOT.gROOT.GetTutorialsDir(), "dataframe/df105_WBosonAnalysis.json")))
57processes = files.keys()
58df = {}
59xsecs = {}
60sumws = {}
61samples = []
62for p in processes:
63 for d in files[p]:
64 # Construct the dataframes
65 folder = d[0] # Folder name
66 sample = d[1] # Sample name
67 xsecs[sample] = d[2] # Cross-section
68 sumws[sample] = d[3] # Sum of weights
69 num_events = d[4] # Number of events
70 samples.append(sample)
71 df[sample] = ROOT.RDataFrame("mini", "{}/1lep/{}/{}.1lep.root".format(dataset_path, folder, sample))
72
73 # Scale down the datasets if requested
74 if args.full_dataset and lumi_scale < 1.0:
75 df[sample] = df[sample].Range(int(num_events * lumi_scale))
76
77# Select events for the analysis
78
79# Just-in-time compile custom helper function performing complex computations
80ROOT.gInterpreter.Declare("""
81bool GoodElectronOrMuon(int type, float pt, float eta, float phi, float e, float trackd0pv, float tracksigd0pv, float z0)
82{
83 ROOT::Math::PtEtaPhiEVector p(pt / 1000.0, eta, phi, e / 1000.0);
84 if (abs(z0 * sin(p.theta())) > 0.5) return false;
85 if (type == 11 && abs(eta) < 2.46 && (abs(eta) < 1.37 || abs(eta) > 1.52)) {
86 if (abs(trackd0pv / tracksigd0pv) > 5) return false;
87 return true;
88 }
89 if (type == 13 && abs(eta) < 2.5) {
90 if (abs(trackd0pv / tracksigd0pv) > 3) return false;
91 return true;
92 }
93 return false;
94}
95""")
96
97for s in samples:
98 # Select events with a muon or electron trigger and with a missing transverse energy larger than 30 GeV
99 df[s] = df[s].Filter("trigE || trigM")\
100 .Filter("met_et > 30000")
101
102 # Find events with exactly one good lepton
103 df[s] = df[s].Define("good_lep", "lep_isTightID && lep_pt > 35000 && lep_ptcone30 / lep_pt < 0.1 && lep_etcone20 / lep_pt < 0.1")\
104 .Filter("ROOT::VecOps::Sum(good_lep) == 1")
105
106 # Apply additional cuts in case the lepton is an electron or muon
107 df[s] = df[s].Define("idx", "ROOT::VecOps::ArgMax(good_lep)")\
108 .Filter("GoodElectronOrMuon(lep_type[idx], lep_pt[idx], lep_eta[idx], lep_phi[idx], lep_E[idx], lep_trackd0pvunbiased[idx], lep_tracksigd0pvunbiased[idx], lep_z0[idx])")
109
110# Apply luminosity, scale factors and MC weights for simulated events
111for s in samples:
112 if "data" in s:
113 df[s] = df[s].Define("weight", "1.0")
114 else:
115 df[s] = df[s].Define("weight", "scaleFactor_ELE * scaleFactor_MUON * scaleFactor_LepTRIGGER * scaleFactor_PILEUP * mcWeight * {} / {} * {}".format(xsecs[s], sumws[s], lumi))
116
117# Compute transverse mass of the W boson using the lepton and the missing transverse energy and make a histogram
118ROOT.gInterpreter.Declare("""
119float ComputeTransverseMass(float met_et, float met_phi, float lep_pt, float lep_eta, float lep_phi, float lep_e)
120{
121 ROOT::Math::PtEtaPhiEVector met(met_et, 0, met_phi, met_et);
122 ROOT::Math::PtEtaPhiEVector lep(lep_pt, lep_eta, lep_phi, lep_e);
123 return (met + lep).Mt() / 1000.0;
124}
125""")
126
127histos = {}
128for s in samples:
129 df[s] = df[s].Define("mt_w", "ComputeTransverseMass(met_et, met_phi, lep_pt[idx], lep_eta[idx], lep_phi[idx], lep_E[idx])")
130 histos[s] = df[s].Histo1D(ROOT.RDF.TH1DModel(s, "mt_w", 24, 60, 180), "mt_w", "weight")
131
132# Run the event loop and merge histograms of the respective processes
133
134# RunGraphs allows to run the event loops of the separate RDataFrame graphs
135# concurrently. This results in an improved usage of the available resources
136# if each separate RDataFrame can not utilize all available resources, e.g.,
137# because not enough data is available.
138ROOT.RDF.RunGraphs([histos[s] for s in samples])
139
140def merge_histos(label):
141 h = None
142 for i, d in enumerate(files[label]):
143 t = histos[d[1]].GetValue()
144 if i == 0: h = t.Clone()
145 else: h.Add(t)
146 h.SetNameTitle(label, label)
147 return h
148
149data = merge_histos("data")
150wjets = merge_histos("wjets")
151zjets = merge_histos("zjets")
152ttbar = merge_histos("ttbar")
153diboson = merge_histos("diboson")
154singletop = merge_histos("singletop")
155
156# Create the plot
157
158# Set styles
159ROOT.gROOT.SetStyle("ATLAS")
160
161# Create canvas
162c = ROOT.TCanvas("c", "", 600, 600)
163c.SetTickx(0)
164c.SetTicky(0)
165c.SetLogy()
166
167# Draw stack with MC contributions
168stack = ROOT.THStack()
169for h, color in zip(
170 [singletop, diboson, ttbar, zjets, wjets],
171 [(208, 240, 193), (195, 138, 145), (155, 152, 204), (248, 206, 104), (222, 90, 106)]):
172 h.SetLineWidth(1)
173 h.SetLineColor(1)
174 h.SetFillColor(ROOT.TColor.GetColor(*color))
175 stack.Add(h)
176stack.Draw("HIST")
177stack.GetXaxis().SetLabelSize(0.04)
178stack.GetXaxis().SetTitleSize(0.045)
179stack.GetXaxis().SetTitleOffset(1.3)
180stack.GetXaxis().SetTitle("m_{T}^{W#rightarrow l#nu} [GeV]")
181stack.GetYaxis().SetTitle("Events")
182stack.GetYaxis().SetLabelSize(0.04)
183stack.GetYaxis().SetTitleSize(0.045)
184stack.SetMaximum(1e10 * args.lumi_scale)
185stack.SetMinimum(1)
186
187# Draw data
188data.SetMarkerStyle(20)
189data.SetMarkerSize(1.2)
190data.SetLineWidth(2)
191data.SetLineColor(ROOT.kBlack)
192data.Draw("E SAME")
193
194# Add legend
195legend = ROOT.TLegend(0.60, 0.65, 0.92, 0.92)
196legend.SetTextFont(42)
197legend.SetFillStyle(0)
198legend.SetBorderSize(0)
199legend.SetTextSize(0.04)
200legend.SetTextAlign(32)
201legend.AddEntry(data, "Data" ,"lep")
202legend.AddEntry(wjets, "W+jets", "f")
203legend.AddEntry(zjets, "Z+jets", "f")
204legend.AddEntry(ttbar, "t#bar{t}", "f")
205legend.AddEntry(diboson, "Diboson", "f")
206legend.AddEntry(singletop, "Single top", "f")
207legend.Draw()
208
209# Add ATLAS label
210text = ROOT.TLatex()
211text.SetNDC()
212text.SetTextFont(72)
213text.SetTextSize(0.045)
214text.DrawLatex(0.21, 0.86, "ATLAS")
215text.SetTextFont(42)
216text.DrawLatex(0.21 + 0.16, 0.86, "Open Data")
217text.SetTextSize(0.04)
218text.DrawLatex(0.21, 0.80, "#sqrt{{s}} = 13 TeV, {:.2f} fb^{{-1}}".format(lumi * args.lumi_scale / 1000.0))
219
220# Save the plot
221c.SaveAs("df105_WBosonAnalysis.png")
222print("Saved figure to df105_WBosonAnalysis.png")
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
unsigned int RunGraphs(std::vector< RResultHandle > handles)
Trigger the event loop of multiple RDataFrames concurrently.
void EnableImplicitMT(UInt_t numthreads=0)
Enable ROOT's implicit multi-threading for all objects and methods that provide an internal paralleli...
Definition TROOT.cxx:539
A struct which stores the parameters of a TH1D.
Ta Range(0, 0, 1, 1)