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