ATLAS Offline Software
example_METMaker_METSystematicsTool.cxx
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
3 */
4 
5 //Author: Russell Smith
6 //Email : rsmith@cern.ch
7 //Date : February 2015
8 #ifndef XAOD_ANALYSIS
9 #include <cstdio>
10 int main() {
11  std::cout << "Examples are only defined in the analysis release." << std::endl;
12  return 0;
13 }
14 #else
15 
16 #ifdef XAOD_STANDALONE
17 #include "xAODRootAccess/Init.h"
18 #include "xAODRootAccess/TEvent.h"
19 #include "xAODRootAccess/TStore.h"
20 #else
21 #include "POOLRootAccess/TEvent.h"
22 #include "StoreGate/StoreGateSvc.h"
23 #endif
24 
25 // FrameWork includes
28 
33 
35 #include "xAODCore/ShallowCopy.h"
36 #include "xAODJet/JetContainer.h"
39 #include "xAODMuon/MuonContainer.h"
42 
43 #include <memory>
44 #undef NDEBUG
45 #include <cassert>
46 #include "TFile.h"
47 #include "TSystem.h"
48 
50 
52 #include "METInterface/IMETMaker.h"
54 
56 
57 #include "xAODCore/tools/IOStats.h"
59 
60 using namespace asg::msgUserCode;
61 
62 int main( int argc, char* argv[]) {std::cout << __PRETTY_FUNCTION__ << std::endl;
63  // Initialize the application
64 #ifdef XAOD_STANDALONE
65  xAOD::Init() ;
66  //enable status code failures
68  StatusCode::enableFailure();
69 #else
70  IAppMgrUI* app = POOL::Init(); //important to do this first!
71 #endif
72 
73  TString fileName = gSystem->Getenv("ASG_TEST_FILE_MC");
74  std::string jetType = "AntiKt4EMTopo";
75  bool debug = false;
76  bool calibjets = true;
77  size_t evtmax = 100;
78  for (int i=0; i<argc; ++i) {
79  if (std::string(argv[i]) == "-filen" && i+1<argc) {
80  fileName = argv[i+1];
81  } else if (std::string(argv[i]) == "-jetcoll" && i+1<argc) {
82  jetType = argv[i+1];
83  } else if (std::string(argv[i]) == "-nocalib") { // useful for checking smart slimming content
84  calibjets = false;
85  } else if (std::string(argv[i]) == "-evtmax" && i+1<argc) {
86  evtmax = atoi(argv[i+1]);
87  } else if (std::string(argv[i]) == "-debug") {
88  debug = true;
89  }
90  }
91 
92  //this test file should work. Feel free to contact me if there is a problem with the file.
93  std::unique_ptr< TFile > ifile( TFile::Open( fileName, "READ" ) );
94  assert( ifile.get() );
95 
96  // Create a TEvent object to read from file and a transient store in which to place items
97 #ifdef XAOD_STANDALONE
98  std::unique_ptr<xAOD::TEvent> event(new xAOD::TEvent( xAOD::TEvent::kClassAccess ) );
99  std::unique_ptr<xAOD::TStore> store(new xAOD::TStore());
100 #else // Athena "Store" is the same StoreGate used by the TEvent
101  std::unique_ptr<POOL::TEvent> event(new POOL::TEvent( POOL::TEvent::kClassAccess ));
102  ServiceHandle<StoreGateSvc>& store = event->evtStore();
103 #endif
104  ANA_CHECK( event->readFrom( ifile.get() ) );
105 
106  // creation and set properties of the tools
107  // if you need to set properties, you should do so before initialization
108 
110  ANA_CHECK( ASG_MAKE_ANA_TOOL( jetCalibrationTool, JetCalibrationTool ) );
111  jetCalibrationTool.setName("jetCalibTool");
112  ANA_CHECK( jetCalibrationTool.setProperty("JetCollection", jetType) );
113  ANA_CHECK( jetCalibrationTool.setProperty("ConfigFile", "JES_MC15cRecommendation_May2016_rel21.config") );
114  ANA_CHECK( jetCalibrationTool.setProperty("CalibSequence", "JetArea_Residual_EtaJES_GSC") );
115  ANA_CHECK( jetCalibrationTool.setProperty("IsData", false) );
116  ANA_CHECK( jetCalibrationTool.retrieve() );
117 
119  metSystTool.setTypeAndName("met::METSystematicsTool/metSystTool");
120  // ANA_CHECK( metSystTool.setProperty("UseDevArea" ,true )); // To get the configs from GROUPDATA/dev/METUtilities
121  ANA_CHECK( metSystTool.retrieve() );
122 
124  metMaker.setTypeAndName("met::METMaker/metMaker");
125  ANA_CHECK( metMaker.setProperty("DoMuonEloss", true) );
126  ANA_CHECK( metMaker.setProperty("DoRemoveMuonJets", true) );
127  ANA_CHECK( metMaker.setProperty("DoSetMuonJetEMScale", true) );
128  ANA_CHECK( metMaker.retrieve() );
129 
130  for(size_t ievent = 0; ievent < std::min(size_t(event->getEntries()), evtmax); ++ievent){
131  if(ievent % 10 == 0) std::cout << "event number: " << ievent << std::endl;
132  ANA_CHECK( event->getEntry(ievent) >= 0 );
133 
134  //retrieve the original containers
135 
136  //this contains all constituents not associated to a jet/misc term
137  const xAOD::MissingETContainer* coreMet = nullptr;
138  std::string coreMetKey = "MET_Core_" + jetType;
139  ANA_CHECK( event->retrieve(coreMet, coreMetKey) );
140  if(debug) std::cout << "Using core MET " << coreMet << std::endl;
141 
142  const xAOD::ElectronContainer* electrons = nullptr;
143  ANA_CHECK( event->retrieve(electrons, "Electrons") );
144 
145  const xAOD::MuonContainer* muons = nullptr;
146  ANA_CHECK( event->retrieve(muons, "Muons") );
147 
148  const xAOD::PhotonContainer* photons = nullptr;
149  ANA_CHECK( event->retrieve(photons, "Photons"));
150 
151  const xAOD::TauJetContainer* taus = nullptr;
152  ANA_CHECK( event->retrieve(taus, "TauJets"));
153 
154  //this should probably be a calibrated jet container. See the METUtilities twiki for more info
155  const xAOD::JetContainer* uncalibJets = nullptr;
156  ANA_CHECK( event->retrieve(uncalibJets, jetType+"Jets"));//this retrieves and applies the correction
157  std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > calibJetsPair = xAOD::shallowCopyContainer( *uncalibJets );//make a shallow copy to calibrate
158  xAOD::JetContainer *& calibJets = calibJetsPair.first;//create a reference to the first element of the pair (i.e. the JetContainer)
159  met::addGhostMuonsToJets(*muons, *calibJets);
160  if(calibjets) {
161  //Shallow copy is needed (see links below)
162  if(jetCalibrationTool->applyCalibration(*calibJets).isFailure())//apply the calibration
163  return 1;
164  }
165  if(!xAOD::setOriginalObjectLink(*uncalibJets, *calibJets)){//tell calib container what old container it matches
166  if(debug) std::cout << "Failed to set the original object links" << std::endl;
167  return 1;
168  }
169  ANA_CHECK( store->record(calibJets, "CalibJets") );
170 
171  //retrieve the MET association map
172  const xAOD::MissingETAssociationMap* metMap = nullptr;
173  std::string metAssocKey = "METAssoc_" + jetType;
174  ANA_CHECK( event->retrieve(metMap, metAssocKey) );
175 
176  //get the set of recommended systematics
178  const CP::SystematicSet& recSysList = registry.recommendedSystematics();
179 
180  //start the loop over systematics
181  //For each systematic, we create an output MissingET container
182  for(CP::SystematicSet::const_iterator isys = recSysList.begin();
183  isys != recSysList.end();
184  ++isys) { // print the systematics on the first event
185  // When only using the METSystematicsTool, this will be the list of recommended systematics for that tool
186  if(ievent == 0)
187  if(debug) std::cout << "Doing systematic : " << (*isys).name() << std::endl;
188 
189  // Create a MissingETContainer with its aux store for each systematic
190  xAOD::MissingETContainer* newMetContainer = new xAOD::MissingETContainer();
191  xAOD::MissingETAuxContainer* newMetAuxContainer = new xAOD::MissingETAuxContainer();
192  newMetContainer->setStore(newMetAuxContainer);
193 
194  // A MET Association Helper is needed to keep track of selected objects
195  xAOD::MissingETAssociationHelper metHelper(metMap);
196 
197  //here we apply some basic cuts and rebuild the met at each step
198  //Electrons
200  for(const auto& el : *electrons) {
201  if(el->pt()>20e3 && el->eta()<2.47) metElectrons.push_back(el);
202  }
203  ANA_CHECK( metMaker->rebuildMET("RefEle", //name of metElectrons in metContainer
204  xAOD::Type::Electron, //telling the rebuilder that this is electron met
205  newMetContainer, //filling this met container
206  metElectrons.asDataVector(),//using these metElectrons that accepted our cuts
207  metHelper) //and this association map
208  );
209 
210  //Photons
212  for(const auto& ph : *photons) {
213  if(ph->pt()>20e3 && ph->eta()<2.47) metPhotons.push_back(ph);
214  }
215  ANA_CHECK( metMaker->rebuildMET("RefPhoton",
217  newMetContainer,
218  metPhotons.asDataVector(),
219  metHelper)
220  );
221 
222  //Taus
224  for(const auto& tau : *taus) {
225  if(tau->pt()>20e3 && tau->eta()<2.5) metTaus.push_back(tau);
226  }
227  ANA_CHECK( metMaker->rebuildMET("RefTau",
229  newMetContainer,
230  metTaus.asDataVector(),
231  metHelper)
232  );
233 
234  //Muons
236  for(const auto& mu : *muons) {
237  if(mu->pt()>20e3 && mu->eta()<2.4) metMuons.push_back(mu);
238  }
239  ANA_CHECK( metMaker->rebuildMET("Muons",
241  newMetContainer,
242  metMuons.asDataVector(),
243  metHelper)
244  );
245 
246  //Now time to rebuild jetMet and get the soft term
247  //This adds the necessary soft term for both CST and TST
248  //these functions create an xAODMissingET object with the given names inside the container
249  ANA_CHECK( metMaker->rebuildJetMET("RefJet", //name of jet met
250  "SoftClus", //name of soft cluster term met
251  "PVSoftTrk", //name of soft track term met
252  newMetContainer, //adding to this new met container
253  calibJets, //using this jet collection to calculate jet met
254  coreMet, //core met container
255  metHelper, //with this association map
256  false //don't apply jet jvt cut
257  )
258  );
259 
260  //this is kind of annoying, but applySystematicVariation only takes a SystematicSet, but *isys is a SystematicVariation.
261  //We use the SystematicSet constructor which just takes a SystematicVariation
262  CP::SystematicSet iSysSet( (*isys).name());
263  //tell the tool that we are using this SystematicSet (of one SystematicVariation for now)
264  //after this call, when we use applyCorrection, the given met term will be adjusted with this systematic applied
265  ANA_CHECK( metSystTool->applySystematicVariation(iSysSet) );
266 
267  //get the soft cluster term, and applyCorrection
268  xAOD::MissingET * softClusMet = (*newMetContainer)["SoftClus"];
269  if(debug) std::cout << "Soft cluster met term met " << softClusMet->met() << std::endl;
270  ANA_CHECK( softClusMet != nullptr); //check we retrieved the clust term
271  ANA_CHECK( metSystTool->applyCorrection(*softClusMet, metHelper) );
272 
273  xAOD::MissingET * softTrkMet = (*newMetContainer)["PVSoftTrk"];
274  if(debug) std::cout << "Soft track met term met " << softTrkMet->met() << std::endl;
275  ANA_CHECK( softTrkMet != nullptr); //check we retrieved the soft trk
276  ANA_CHECK( metSystTool->applyCorrection(*softTrkMet, metHelper) );
277 
278  //this builds the final track or cluster met sums, using systematic varied container
279  //In the future, you will be able to run both of these on the same container to easily output CST and TST
280  ANA_CHECK( met::buildMETSum("FinalTrk" , newMetContainer, MissingETBase::Source::Track ) );
281  //ANA_CHECK( met::buildMETSum("FinalClus", newMetContainer, MissingETBase::Source::LCTopo) );
282 
283  //we record the container to the store, with a systematic indicated name
284  ANA_CHECK( store->record( newMetContainer, "FinalMETContainer_" + iSysSet.name() ));
285  ANA_CHECK( store->record( newMetAuxContainer, "FinalMETContainer_" + iSysSet.name() + "Aux."));
286 
287  if(debug) {
288  xAOD::MissingET * jetMet = (*newMetContainer)["RefJet"];
289  const std::vector<float>& jetweights = jetMet->auxdataConst<std::vector<float> >("ConstitObjectWeights");
290  const std::vector<ElementLink<xAOD::IParticleContainer> >& constitjets = jetMet->auxdataConst<std::vector<ElementLink<xAOD::IParticleContainer> > >("ConstitObjectLinks");
291  for(size_t iconstit=0; iconstit < jetweights.size(); ++iconstit) {
292  const xAOD::Jet* constjet = static_cast<const xAOD::Jet*>(*constitjets[iconstit]);
293  const float jetweight = jetweights[iconstit];
294  std::cout << "RefJet jet " << constjet->index() << ", weight " << jetweight << ", pt: " << constjet->pt() << std::endl;
295  }
296  }
297  }
298 
299 #ifdef XAOD_STANDALONE
300  //fill the containers stored in the event
301  //to the output file and clear the transient store
302  assert( event->fill());
303  store->clear();
304 #endif
305  }
306 
307 #ifndef XAOD_STANDALONE
308  ANA_CHECK(app->finalize());
309 #endif
310 
312 
313  return 0;
314 }
315 
316 #endif
ShallowCopy.h
python.Dso.registry
registry
Definition: Control/AthenaServices/python/Dso.py:159
SGTest::store
TestStore store
Definition: TestStore.cxx:23
xAOD::Electron
Electron_v1 Electron
Definition of the current "egamma version".
Definition: Event/xAOD/xAODEgamma/xAODEgamma/Electron.h:17
xAOD::MissingETAuxContainer
MissingETAuxContainer_v1 MissingETAuxContainer
Definition: MissingETAuxContainer.h:16
xAOD::IOStats::stats
ReadStats & stats()
Access the object belonging to the current thread.
Definition: IOStats.cxx:17
IMETMaker::rebuildJetMET
virtual StatusCode rebuildJetMET(const std::string &metJetKey, const std::string &metSoftKey, xAOD::MissingETContainer *metCont, const xAOD::JetContainer *jets, const xAOD::MissingETContainer *metCoreCont, xAOD::MissingETAssociationHelper &helper, bool doJetJVT)=0
SG::VIEW_ELEMENTS
@ VIEW_ELEMENTS
this data object is a view, it does not own its elmts
Definition: OwnershipPolicy.h:18
CP::CorrectionCode::enableFailure
static void enableFailure() noexcept
Definition: CorrectionCode.h:64
IMETSystematicsTool::applyCorrection
virtual CP::CorrectionCode applyCorrection(xAOD::MissingET &met, const xAOD::MissingETAssociationHelper &helper) const =0
min
constexpr double min()
Definition: ap_fixedTest.cxx:26
CP::SystematicSet::const_iterator
std::set< SystematicVariation >::const_iterator const_iterator
Definition: SystematicSet.h:52
CP::SystematicSet
Class to wrap a set of SystematicVariations.
Definition: SystematicSet.h:31
IMETMaker.h
ANA_CHECK
#define ANA_CHECK(EXP)
check whether the given expression was successful
Definition: Control/AthToolSupport/AsgMessaging/AsgMessaging/MessageCheck.h:324
xAOD::MissingETContainer
MissingETContainer_v1 MissingETContainer
Definition: Event/xAOD/xAODMissingET/xAODMissingET/MissingETContainer.h:16
IMETSystematicsTool.h
main
int main()
Definition: example_METMaker_METSystematicsTool.cxx:10
IOStats.h
ShallowAuxContainer.h
xAOD::TEvent::kClassAccess
@ kClassAccess
Access auxiliary data using the aux containers.
Definition: Control/xAODRootAccess/xAODRootAccess/TEvent.h:100
ASG_MAKE_ANA_TOOL
#define ASG_MAKE_ANA_TOOL(handle, type)
create the tool in the given tool handle
Definition: AnaToolHandle.h:690
IMETMaker::rebuildMET
virtual StatusCode rebuildMET(const std::string &metKey, xAOD::Type::ObjectType metType, xAOD::MissingETContainer *metCont, const xAOD::IParticleContainer *collection, xAOD::MissingETAssociationHelper &helper, MissingETBase::UsageHandler::Policy objScale=MissingETBase::UsageHandler::PhysicsObject)=0
xAOD::MissingETAssociationMap_v1
Definition: MissingETAssociationMap_v1.h:29
POOL::Init
IAppMgrUI * Init(const char *options="POOLRootAccess/basic.opts")
Bootstraps (creates and configures) the Gaudi Application with the provided options file.
Definition: PhysicsAnalysis/POOLRootAccess/src/TEvent.cxx:29
POOL::TEvent::kClassAccess
@ kClassAccess
Definition: PhysicsAnalysis/POOLRootAccess/POOLRootAccess/TEvent.h:46
met::buildMETSum
StatusCode buildMETSum(const std::string &totalName, xAOD::MissingETContainer *metCont)
Definition: METHelpers.cxx:64
METHelpers.h
met::addGhostMuonsToJets
void addGhostMuonsToJets(const xAOD::MuonContainer &muons, xAOD::JetContainer &jets)
Definition: METHelpers.cxx:34
POOL::TEvent::readFrom
StatusCode readFrom(TFile *file)
Definition: PhysicsAnalysis/POOLRootAccess/src/TEvent.cxx:133
FortranAlgorithmOptions.fileName
fileName
Definition: FortranAlgorithmOptions.py:13
JetCalibrationTool.h
ReadStats.h
CheckAppliedSFs.e3
e3
Definition: CheckAppliedSFs.py:264
event
POOL::TEvent event(POOL::TEvent::kClassAccess)
ElectronContainer.h
POOL::TEvent::getEntry
int getEntry(long entry)
Definition: PhysicsAnalysis/POOLRootAccess/src/TEvent.cxx:185
asg::StandaloneToolHandle::setProperty
StatusCode setProperty(const std::string &name, T2 &&value)
Definition: StandaloneToolHandle.h:105
lumiFormat.i
int i
Definition: lumiFormat.py:85
SystematicRegistry.h
POOL::TEvent::getEntries
long getEntries()
Definition: PhysicsAnalysis/POOLRootAccess/src/TEvent.cxx:124
asg::StandaloneToolHandle
an "initializing" ToolHandle for stand-alone applications
Definition: StandaloneToolHandle.h:44
LArCellNtuple.argv
argv
Definition: LArCellNtuple.py:152
MissingETAuxContainer.h
MessageCheck.h
macros for messaging and checking status codes
JetCalibrationTool
Definition: JetCalibrationTool.h:34
TEvent.h
xAOD::MissingET_v1
Principal data object for Missing ET.
Definition: MissingET_v1.h:25
plotIsoValidation.el
el
Definition: plotIsoValidation.py:197
CP::SystematicSet::end
const_iterator end() const
description: const iterator to the end of the set
Definition: SystematicSet.h:59
xAOD::MissingETAuxContainer_v1
Auxiliary data store for xAOD::MissingETContainer.
Definition: MissingETAuxContainer_v1.h:20
Init.h
DQHistogramMergeRegExp.argc
argc
Definition: DQHistogramMergeRegExp.py:20
TauJetContainer.h
SG::AuxElement::index
size_t index() const
Return the index of this element within its container.
xAOD::IOStats::instance
static IOStats & instance()
Singleton object accessor.
Definition: IOStats.cxx:11
DataVector
Derived DataVector<T>.
Definition: DataVector.h:794
asg::StandaloneToolHandle::retrieve
StatusCode retrieve()
initialize the tool, will succeed if the tool was already initialized
Definition: StandaloneToolHandle.h:147
xAOD::ReadStats::printSmartSlimmingBranchList
void printSmartSlimmingBranchList(bool autoIncludeLinks=false) const
Print the accessed variables, formatted for smart slimming.
xAOD::MissingETContainer_v1
Container for xAOD::MissingET_v1 objects.
Definition: MissingETContainer_v1.h:21
POOL::TEvent
Definition: PhysicsAnalysis/POOLRootAccess/POOLRootAccess/TEvent.h:40
TEvent.h
debug
const bool debug
Definition: MakeUncertaintyPlots.cxx:53
SGTest::TestStore::record
void record(const T *p, const std::string &key)
Definition: TestStore.h:81
xAOD::MissingETAssociationHelper
Definition: MissingETAssociationHelper.h:26
xAOD::shallowCopyContainer
std::pair< std::unique_ptr< T >, std::unique_ptr< ShallowAuxContainer > > shallowCopyContainer(const T &cont, [[maybe_unused]] const EventContext &ctx)
Function making a shallow copy of a constant container.
Definition: ShallowCopy.h:110
MuonContainer.h
xAOD::Photon
Photon_v1 Photon
Definition of the current "egamma version".
Definition: Event/xAOD/xAODEgamma/xAODEgamma/Photon.h:17
Muon
struct TBPatternUnitContext Muon
asg::StandaloneToolHandle::setTypeAndName
void setTypeAndName(const std::string &typeAndName)
Definition: StandaloneToolHandle.h:101
xAOD::Jet_v1
Class describing a jet.
Definition: Jet_v1.h:57
ConvertOldUJHistosToNewHistos.jetType
string jetType
Definition: ConvertOldUJHistosToNewHistos.py:121
xAOD::TStore
A relatively simple transient store for objects created in analysis.
Definition: TStore.h:44
JetContainer.h
CP::SystematicRegistry
This module implements the central registry for handling systematic uncertainties with CP tools.
Definition: SystematicRegistry.h:25
ConstDataVector
DataVector adapter that acts like it holds const pointers.
Definition: ConstDataVector.h:76
POOL::TEvent::retrieve
StatusCode retrieve(const T *&obj)
Definition: PhysicsAnalysis/POOLRootAccess/POOLRootAccess/TEvent.h:74
xAOD::setOriginalObjectLink
bool setOriginalObjectLink(const IParticle &original, IParticle &copy)
This function should be used by CP tools when they make a deep copy of an object in their correctedCo...
Definition: IParticleHelpers.cxx:30
CP::SystematicSet::begin
const_iterator begin() const
description: const iterator to the beginning of the set
Definition: SystematicSet.h:55
IJetCalibrationTool::applyCalibration
virtual StatusCode applyCalibration(xAOD::JetContainer &jets) const =0
Apply calibration to a jet container.
SG::AuxElement::auxdataConst
XAOD_AUXDATA_DEPRECATED Accessor< T, ALLOC >::const_reference_type auxdataConst(const std::string &name) const
Fetch an aux data variable, as a const reference.
xAODType::Tau
@ Tau
The object is a tau (jet)
Definition: ObjectType.h:49
CxxUtils::atoi
int atoi(std::string_view str)
Helper functions to unpack numbers decoded in string into integers and doubles The strings are requir...
Definition: Control/CxxUtils/Root/StringUtils.cxx:85
IParticleHelpers.h
MissingETAssociationMap.h
LArCellNtuple.ifile
string ifile
Definition: LArCellNtuple.py:133
StandaloneToolHandle.h
CaloNoise_fillDB.mu
mu
Definition: CaloNoise_fillDB.py:53
xAOD::Jet_v1::pt
virtual double pt() const
The transverse momentum ( ) of the particle.
Definition: Jet_v1.cxx:44
CP::ISystematicsTool::applySystematicVariation
virtual StatusCode applySystematicVariation(const SystematicSet &systConfig)=0
effects: configure this tool for the given list of systematic variations.
MissingETAssociationHelper.h
StoreGateSvc.h
PhotonContainer.h
MissingETContainer.h
TStore.h
InDetDD::electrons
@ electrons
Definition: InDetDD_Defs.h:17
xAOD::TEvent
Tool for accessing xAOD files outside of Athena.
Definition: Control/xAODRootAccess/xAODRootAccess/TEvent.h:84
xAOD::MissingET_v1::met
float met() const
Returns .
CP::SystematicRegistry::getInstance
static SystematicRegistry & getInstance()
Get the singleton instance of the registry for the curren thread.
Definition: SystematicRegistry.cxx:25
xAOD::Init
StatusCode Init(const char *appname)
Function initialising ROOT/PyROOT for using the ATLAS EDM.
Definition: Init.cxx:31
ServiceHandle< StoreGateSvc >