CMS 3D CMS Logo

PhotonMVANtuplizer.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: RecoEgamma/PhotonIdentification
4 // Class: PhotonMVANtuplizer
5 //
13 //
14 // Original Author: Jonas REMBSER
15 // Created: Thu, 22 Mar 2018 14:54:24 GMT
16 //
17 //
18 
35 
36 #include <TTree.h>
37 #include <TFile.h>
38 #include <Math/VectorUtil.h>
39 
40 //
41 // class declaration
42 //
43 
44 class PhotonMVANtuplizer : public edm::one::EDAnalyzer<edm::one::SharedResources> {
45 public:
46  explicit PhotonMVANtuplizer(const edm::ParameterSet&);
47 
48  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
49 
50 private:
51  void analyze(const edm::Event&, const edm::EventSetup&) override;
52 
53  // ----------member data ---------------------------
54 
55  // other
56  TTree* tree_;
57 
58  // global variables
60  int genNpu_;
61  int vtxN_;
62 
63  // photon variables
64  double pT_, eta_;
65  std::vector<float> energyMatrix_;
66 
67  // photon genMatch variable
70 
71  // ID decisions objects
72  const std::vector<std::string> phoMapTags_;
73  std::vector<edm::EDGetTokenT<edm::ValueMap<bool>>> phoMapTokens_;
74  const std::vector<std::string> phoMapBranchNames_;
75  const size_t nPhoMaps_;
76 
77  // MVA values and categories (optional)
78  const std::vector<std::string> valMapTags_;
79  std::vector<edm::EDGetTokenT<edm::ValueMap<float>>> valMapTokens_;
80  const std::vector<std::string> valMapBranchNames_;
81  const size_t nValMaps_;
82 
83  const std::vector<std::string> mvaCatTags_;
84  std::vector<edm::EDGetTokenT<edm::ValueMap<int>>> mvaCatTokens_;
85  const std::vector<std::string> mvaCatBranchNames_;
86  const size_t nCats_;
87 
88  // config
89  const bool isMC_;
90  const double ptThreshold_;
91  const double deltaR_;
92 
93  // Tokens
100 
101  // to hold ID decisions and categories
102  std::vector<int> mvaPasses_;
103  std::vector<float> mvaValues_;
104  std::vector<int> mvaCats_;
105 
106  // To get the auxiliary MVA variables
108 
109  // To manage the variables which are parsed from the text file
111 
112  const int nVars_;
113  std::vector<float> vars_;
114 
115  const bool doEnergyMatrix_;
116  const int energyMatrixSize_;
117 };
118 
123 };
124 
125 namespace {
126 
127  int matchToTruth(const reco::Photon& ph, const edm::View<reco::GenParticle>& genParticles, double deltaR) {
128  // Find the closest status 1 gen photon to the reco photon
129  double dR = 999;
130  reco::GenParticle const* closestPhoton = &genParticles[0];
131  for (auto& particle : genParticles) {
132  // Drop everything that is not photon or not status 1
133  if (abs(particle.pdgId()) != 22 || particle.status() != 1)
134  continue;
135 
136  double dRtmp = ROOT::Math::VectorUtil::DeltaR(ph.p4(), particle.p4());
137  if (dRtmp < dR) {
138  dR = dRtmp;
139  closestPhoton = &particle;
140  }
141  }
142  // See if the closest photon (if it exists) is close enough.
143  // If not, no match found.
144  if (dR < deltaR) {
145  if (closestPhoton->isPromptFinalState())
146  return TRUE_PROMPT_PHOTON;
147  else
148  return TRUE_NON_PROMPT_PHOTON;
149  }
150  return FAKE_PHOTON;
151  }
152 
153 }; // namespace
154 
155 // constructor
157  : phoMapTags_(iConfig.getParameter<std::vector<std::string>>("phoMVAs")),
158  phoMapBranchNames_(iConfig.getParameter<std::vector<std::string>>("phoMVALabels")),
160  valMapTags_(iConfig.getParameter<std::vector<std::string>>("phoMVAValMaps")),
161  valMapBranchNames_(iConfig.getParameter<std::vector<std::string>>("phoMVAValMapLabels")),
163  mvaCatTags_(iConfig.getParameter<std::vector<std::string>>("phoMVACats")),
164  mvaCatBranchNames_(iConfig.getParameter<std::vector<std::string>>("phoMVACatLabels")),
166  isMC_(iConfig.getParameter<bool>("isMC")),
167  ptThreshold_(iConfig.getParameter<double>("ptThreshold")),
168  deltaR_(iConfig.getParameter<double>("deltaR")),
169  src_(consumes<edm::View<reco::Photon>>(iConfig.getParameter<edm::InputTag>("src"))),
170  vertices_(consumes<std::vector<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("vertices"))),
171  pileup_(consumes<std::vector<PileupSummaryInfo>>(iConfig.getParameter<edm::InputTag>("pileup"))),
172  genParticles_(consumes<edm::View<reco::GenParticle>>(iConfig.getParameter<edm::InputTag>("genParticles"))),
173  ebRecHits_(consumes<EcalRecHitCollection>(iConfig.getParameter<edm::InputTag>("ebReducedRecHitCollection"))),
174  eeRecHits_(consumes<EcalRecHitCollection>(iConfig.getParameter<edm::InputTag>("eeReducedRecHitCollection"))),
177  mvaCats_(nCats_),
179  mvaVarMngr_(iConfig.getParameter<std::string>("variableDefinition")),
180  nVars_(mvaVarMngr_.getNVars()),
181  vars_(nVars_),
182  doEnergyMatrix_(iConfig.getParameter<bool>("doEnergyMatrix")),
183  energyMatrixSize_(iConfig.getParameter<int>("energyMatrixSize")) {
184  // phoMaps
185  for (auto const& tag : phoMapTags_) {
187  }
188  // valMaps
189  for (auto const& tag : valMapTags_) {
191  }
192  // categories
193  for (auto const& tag : mvaCatTags_) {
195  }
196 
197  // Book tree
198  usesResource(TFileService::kSharedResource);
200  tree_ = fs->make<TTree>("tree", "tree");
201 
202  tree_->Branch("nEvent", &nEvent_);
203  tree_->Branch("nRun", &nRun_);
204  tree_->Branch("nLumi", &nLumi_);
205  if (isMC_) {
206  tree_->Branch("genNpu", &genNpu_);
207  tree_->Branch("matchedToGenPh", &matchedToGenPh_);
208  }
209  tree_->Branch("vtxN", &vtxN_);
210  tree_->Branch("pT", &pT_);
211  tree_->Branch("eta", &eta_);
212 
213  if (doEnergyMatrix_)
214  tree_->Branch("energyMatrix", &energyMatrix_);
215 
216  for (int i = 0; i < nVars_; ++i) {
217  tree_->Branch(mvaVarMngr_.getName(i).c_str(), &vars_[i]);
218  }
219 
220  // IDs
221  for (size_t k = 0; k < nValMaps_; ++k) {
222  tree_->Branch(valMapBranchNames_[k].c_str(), &mvaValues_[k]);
223  }
224 
225  for (size_t k = 0; k < nPhoMaps_; ++k) {
226  tree_->Branch(phoMapBranchNames_[k].c_str(), &mvaPasses_[k]);
227  }
228 
229  for (size_t k = 0; k < nCats_; ++k) {
230  tree_->Branch(mvaCatBranchNames_[k].c_str(), &mvaCats_[k]);
231  }
232 }
233 
234 // ------------ method called for each event ------------
236  // Fill global event info
237  nEvent_ = iEvent.id().event();
238  nRun_ = iEvent.id().run();
239  nLumi_ = iEvent.luminosityBlock();
240 
241  // Get Handles
242  auto src = iEvent.getHandle(src_);
243  auto vertices = iEvent.getHandle(vertices_);
244  auto pileup = iEvent.getHandle(pileup_);
245  auto genParticles = iEvent.getHandle(genParticles_);
246 
247  vtxN_ = vertices->size();
248 
249  // initialize cluster tools
250  std::unique_ptr<noZS::EcalClusterLazyTools> lazyTools;
251  if (doEnergyMatrix_) {
252  // Configure Lazy Tools, which will compute 5x5 quantities
253  lazyTools = std::make_unique<noZS::EcalClusterLazyTools>(iEvent, iSetup, ebRecHits_, eeRecHits_);
254  }
255 
256  // Fill with true number of pileup
257  if (isMC_) {
258  for (const auto& pu : *pileup) {
259  int bx = pu.getBunchCrossing();
260  if (bx == 0) {
261  genNpu_ = pu.getPU_NumInteractions();
262  break;
263  }
264  }
265  }
266 
267  // Get MVA decisions
269  for (size_t k = 0; k < nPhoMaps_; ++k) {
270  iEvent.getByToken(phoMapTokens_[k], decisions[k]);
271  }
272 
273  // Get MVA values
275  for (size_t k = 0; k < nValMaps_; ++k) {
276  iEvent.getByToken(valMapTokens_[k], values[k]);
277  }
278 
279  // Get MVA categories
281  for (size_t k = 0; k < nCats_; ++k) {
282  iEvent.getByToken(mvaCatTokens_[k], mvaCats[k]);
283  }
284 
285  std::vector<float> extraVariables = variableHelper_.getAuxVariables(iEvent);
286 
287  for (auto const& pho : src->ptrs()) {
288  if (pho->pt() < ptThreshold_)
289  continue;
290 
291  pT_ = pho->pt();
292  eta_ = pho->eta();
293 
294  // Fill the energy matrix around the seed
295  if (doEnergyMatrix_) {
296  const auto& seed = *(pho->superCluster()->seed());
297  energyMatrix_ = lazyTools->energyMatrix(seed, energyMatrixSize_);
298  }
299 
300  // variables from the text file
301  for (int iVar = 0; iVar < nVars_; ++iVar) {
302  vars_[iVar] = mvaVarMngr_.getValue(iVar, *pho, extraVariables);
303  }
304 
305  if (isMC_)
306  matchedToGenPh_ = matchToTruth(*pho, *genParticles, deltaR_);
307 
308  //
309  // Look up and save the ID decisions
310  //
311  for (size_t k = 0; k < nPhoMaps_; ++k)
312  mvaPasses_[k] = static_cast<int>((*decisions[k])[pho]);
313  for (size_t k = 0; k < nValMaps_; ++k)
314  mvaValues_[k] = (*values[k])[pho];
315  for (size_t k = 0; k < nCats_; ++k)
316  mvaCats_[k] = (*mvaCats[k])[pho];
317 
318  tree_->Fill();
319  }
320 }
321 
322 // ------------ method fills 'descriptions' with the allowed parameters for the module ------------
325  desc.add<edm::InputTag>("src", edm::InputTag("slimmedPhotons"));
326  desc.add<edm::InputTag>("vertices", edm::InputTag("offlineSlimmedPrimaryVertices"));
327  desc.add<edm::InputTag>("pileup", edm::InputTag("slimmedAddPileupInfo"));
328  desc.add<edm::InputTag>("genParticles", edm::InputTag("prunedGenParticles"));
329  desc.add<edm::InputTag>("ebReducedRecHitCollection", edm::InputTag("reducedEgamma", "reducedEBRecHits"));
330  desc.add<edm::InputTag>("eeReducedRecHitCollection", edm::InputTag("reducedEgamma", "reducedEERecHits"));
331  desc.add<std::vector<std::string>>("phoMVAs", {});
332  desc.add<std::vector<std::string>>("phoMVALabels", {});
333  desc.add<std::vector<std::string>>("phoMVAValMaps", {});
334  desc.add<std::vector<std::string>>("phoMVAValMapLabels", {});
335  desc.add<std::vector<std::string>>("phoMVACats", {});
336  desc.add<std::vector<std::string>>("phoMVACatLabels", {});
337  desc.add<bool>("doEnergyMatrix", false);
338  desc.add<int>("energyMatrixSize", 2)->setComment("extension of crystals in each direction away from the seed");
339  desc.add<bool>("isMC", true);
340  desc.add<double>("ptThreshold", 15.0);
341  desc.add<double>("deltaR", 0.1);
342  desc.add<std::string>("variableDefinition");
343  descriptions.addDefault(desc);
344 }
345 
346 //define this as a plug-in
RunNumber_t run() const
Definition: EventID.h:38
size
Write out results.
static const std::string kSharedResource
Definition: TFileService.h:76
EventNumber_t event() const
Definition: EventID.h:40
bool isPromptFinalState() const
Definition: GenParticle.h:51
const std::string & getName(int index) const
Definition: Photon.py:1
const edm::EDGetTokenT< EcalRecHitCollection > eeRecHits_
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:525
MVAVariableManager< reco::Photon > mvaVarMngr_
edm::LuminosityBlockNumber_t luminosityBlock() const
Definition: EventBase.h:61
const std::vector< std::string > mvaCatBranchNames_
const edm::EDGetTokenT< std::vector< PileupSummaryInfo > > pileup_
T * make(const Args &...args) const
make new ROOT object
Definition: TFileService.h:64
float getValue(int index, const ParticleType &particle, const std::vector< float > &auxVariables) const
const std::vector< std::string > valMapTags_
std::vector< int > mvaCats_
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
std::vector< edm::EDGetTokenT< edm::ValueMap< int > > > mvaCatTokens_
Handle< PROD > getHandle(EDGetTokenT< PROD > token) const
Definition: Event.h:547
std::vector< int > mvaPasses_
int iEvent
Definition: GenABIO.cc:224
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void addDefault(ParameterSetDescription const &psetDescription)
std::vector< float > mvaValues_
ConsumesCollector consumesCollector()
Use a ConsumesCollector to gather consumes information from helper functions.
const std::vector< std::string > mvaCatTags_
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
ParameterDescriptionBase * add(U const &iLabel, T const &value)
std::vector< edm::EDGetTokenT< edm::ValueMap< bool > > > phoMapTokens_
const std::vector< std::string > valMapBranchNames_
const edm::EDGetTokenT< EcalRecHitCollection > ebRecHits_
const std::vector< std::string > phoMapBranchNames_
const edm::EDGetTokenT< edm::View< reco::Photon > > src_
const edm::EDGetTokenT< std::vector< reco::Vertex > > vertices_
const LorentzVector & p4(P4type type) const
edm::EventID id() const
Definition: EventBase.h:59
fixed size matrix
PhotonMatchType
HLT enums.
const edm::EDGetTokenT< edm::View< reco::GenParticle > > genParticles_
const MVAVariableHelper variableHelper_
const std::vector< float > getAuxVariables(const edm::Event &iEvent) const
const std::vector< std::string > phoMapTags_
void analyze(const edm::Event &, const edm::EventSetup &) override
std::vector< float > energyMatrix_
std::vector< float > vars_
PhotonMVANtuplizer(const edm::ParameterSet &)
std::vector< edm::EDGetTokenT< edm::ValueMap< float > > > valMapTokens_