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 
19 
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 
47  public:
48  explicit PhotonMVANtuplizer(const edm::ParameterSet&);
49 
50  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
51 
52 
53  private:
54  void analyze(const edm::Event&, const edm::EventSetup&) override;
55 
56  // ----------member data ---------------------------
57 
58  // other
59  TTree* tree_;
60 
61  // global variables
63  int genNpu_;
64  int vtxN_;
65 
66  // photon variables
67  double pT_, eta_;
68  std::vector<float> energyMatrix_;
69 
70  // photon genMatch variable
73 
74  // ID decisions objects
75  const std::vector< std::string > phoMapTags_;
76  std::vector< edm::EDGetTokenT< edm::ValueMap<bool> > > phoMapTokens_;
77  const std::vector< std::string > phoMapBranchNames_;
78  const size_t nPhoMaps_;
79 
80  // MVA values and categories (optional)
81  const std::vector< std::string > valMapTags_;
82  std::vector< edm::EDGetTokenT<edm::ValueMap<float> > > valMapTokens_;
83  const std::vector< std::string > valMapBranchNames_;
84  const size_t nValMaps_;
85 
86  const std::vector< std::string > mvaCatTags_;
87  std::vector< edm::EDGetTokenT<edm::ValueMap<int> > > mvaCatTokens_;
88  const std::vector< std::string > mvaCatBranchNames_;
89  const size_t nCats_;
90 
91  // config
92  const bool isMC_;
93  const double ptThreshold_;
94  const double deltaR_;
95 
96  // for AOD or MiniAOD case
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,
132  double deltaR)
133  {
134  // Find the closest status 1 gen photon to the reco photon
135  double dR = 999;
136  reco::GenParticle const * closestPhoton = &genParticles[0];
137  for (auto & particle : genParticles) {
138  // Drop everything that is not photon or not status 1
139  if( abs(particle.pdgId()) != 22 || particle.status() != 1 ) continue;
140 
141  double dRtmp = ROOT::Math::VectorUtil::DeltaR( ph.p4(), particle.p4() );
142  if( dRtmp < dR ) {
143  dR = dRtmp;
144  closestPhoton = &particle;
145  }
146  }
147  // See if the closest photon (if it exists) is close enough.
148  // If not, no match found.
149  if(dR < deltaR) {
150  if( closestPhoton->isPromptFinalState() ) return TRUE_PROMPT_PHOTON;
151  else return TRUE_NON_PROMPT_PHOTON;
152  }
153  return FAKE_PHOTON;
154  }
155 
156 };
157 
158 // constructor
160  : phoMapTags_ (iConfig.getParameter<std::vector<std::string>>("phoMVAs"))
161  , phoMapBranchNames_ (iConfig.getParameter<std::vector<std::string>>("phoMVALabels"))
163  , valMapTags_ (iConfig.getParameter<std::vector<std::string>>("phoMVAValMaps"))
164  , valMapBranchNames_ (iConfig.getParameter<std::vector<std::string>>("phoMVAValMapLabels"))
166  , mvaCatTags_ (iConfig.getParameter<std::vector<std::string>>("phoMVACats"))
167  , mvaCatBranchNames_ (iConfig.getParameter<std::vector<std::string>>("phoMVACatLabels"))
169  , isMC_ (iConfig.getParameter<bool>("isMC"))
170  , ptThreshold_ (iConfig.getParameter<double>("ptThreshold"))
171  , deltaR_ (iConfig.getParameter<double>("deltaR"))
172  , src_ (consumesCollector(), iConfig, "src" , "srcMiniAOD")
173  , vertices_ (src_, consumesCollector(), iConfig, "vertices", "verticesMiniAOD")
174  , pileup_ (src_, consumesCollector(), iConfig, "pileup" , "pileupMiniAOD")
175  , genParticles_ (src_, consumesCollector(), iConfig, "genParticles", "genParticlesMiniAOD")
176  , ebRecHits_ (src_, consumesCollector(), iConfig, "ebReducedRecHitCollection", "ebReducedRecHitCollectionMiniAOD")
177  , eeRecHits_ (src_, consumesCollector(), iConfig, "eeReducedRecHitCollection", "eeReducedRecHitCollectionMiniAOD")
180  , mvaCats_ (nCats_)
182  , mvaVarMngr_ (iConfig.getParameter<std::string>("variableDefinition"))
183  , nVars_ (mvaVarMngr_.getNVars())
184  , vars_ (nVars_)
185  , doEnergyMatrix_ (iConfig.getParameter<bool>("doEnergyMatrix"))
186  , energyMatrixSize_ (iConfig.getParameter<int>("energyMatrixSize"))
187 {
188  // phoMaps
189  for (auto const& tag : phoMapTags_) {
191  }
192  // valMaps
193  for (auto const& tag : valMapTags_) {
195  }
196  // categories
197  for (auto const& tag : mvaCatTags_) {
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_) tree_->Branch("energyMatrix",&energyMatrix_);
218 
219  for (int i = 0; i < nVars_; ++i) {
220  tree_->Branch(mvaVarMngr_.getName(i).c_str(), &vars_[i]);
221  }
222 
223  // IDs
224  for (size_t k = 0; k < nValMaps_; ++k) {
225  tree_->Branch(valMapBranchNames_[k].c_str() , &mvaValues_[k]);
226  }
227 
228  for (size_t k = 0; k < nPhoMaps_; ++k) {
229  tree_->Branch(phoMapBranchNames_[k].c_str() , &mvaPasses_[k]);
230  }
231 
232  for (size_t k = 0; k < nCats_; ++k) {
233  tree_->Branch(mvaCatBranchNames_[k].c_str() , &mvaCats_[k]);
234  }
235 }
236 
237 // ------------ method called for each event ------------
238 void
240 {
241  // Fill global event info
242  nEvent_ = iEvent.id().event();
243  nRun_ = iEvent.id().run();
244  nLumi_ = iEvent.luminosityBlock();
245 
246  // Get Handles
247  auto src = src_.getValidHandle(iEvent);
248  auto vertices = vertices_.getValidHandle(iEvent);
249  auto pileup = pileup_.getValidHandle(iEvent);
251 
252  vtxN_ = vertices->size();
253 
254  // initialize cluster tools
255  std::unique_ptr<noZS::EcalClusterLazyTools> lazyTools;
256  if(doEnergyMatrix_) {
257  // Configure Lazy Tools, which will compute 5x5 quantities
258  lazyTools = std::make_unique<noZS::EcalClusterLazyTools>(
259  iEvent, iSetup, ebRecHits_.get(iEvent), eeRecHits_.get(iEvent));
260  }
261 
262  // Fill with true number of pileup
263  if(isMC_) {
264  for(const auto& pu : *pileup)
265  {
266  int bx = pu.getBunchCrossing();
267  if(bx == 0)
268  {
269  genNpu_ = pu.getPU_NumInteractions();
270  break;
271  }
272  }
273  }
274 
275  // Get MVA decisions
277  for (size_t k = 0; k < nPhoMaps_; ++k) {
278  iEvent.getByToken(phoMapTokens_[k],decisions[k]);
279  }
280 
281  // Get MVA values
283  for (size_t k = 0; k < nValMaps_; ++k) {
284  iEvent.getByToken(valMapTokens_[k],values[k]);
285  }
286 
287  // Get MVA categories
289  for (size_t k = 0; k < nCats_; ++k) {
290  iEvent.getByToken(mvaCatTokens_[k],mvaCats[k]);
291  }
292 
293  for(auto const& pho : src->ptrs())
294  {
295  if (pho->pt() < ptThreshold_) continue;
296 
297  pT_ = pho->pt();
298  eta_ = pho->eta();
299 
300  // Fill the energy matrix around the seed
301  if(doEnergyMatrix_) {
302  const auto& seed = *(pho->superCluster()->seed());
303  energyMatrix_ = lazyTools->energyMatrix(seed, energyMatrixSize_);
304  }
305 
306  // variables from the text file
307  for (int iVar = 0; iVar < nVars_; ++iVar) {
308  std::vector<float> extraVariables = variableHelper_.getAuxVariables(pho, iEvent);
309  vars_[iVar] = mvaVarMngr_.getValue(iVar, *pho, extraVariables);
310  }
311 
312  if (isMC_) matchedToGenPh_ = matchToTruth( *pho, *genParticles, deltaR_);
313 
314  //
315  // Look up and save the ID decisions
316  //
317  for (size_t k = 0; k < nPhoMaps_; ++k) mvaPasses_[k] = static_cast<int>((*decisions[k])[pho]);
318  for (size_t k = 0; k < nValMaps_; ++k) mvaValues_[k] = (*values[k])[pho];
319  for (size_t k = 0; k < nCats_ ; ++k) mvaCats_[k] = (*mvaCats[k])[pho];
320 
321  tree_->Fill();
322  }
323 
324 }
325 
326 // ------------ method fills 'descriptions' with the allowed parameters for the module ------------
327 void
329 {
331  desc.add<edm::InputTag>("src", edm::InputTag("gedPhotons"));
332  desc.add<edm::InputTag>("vertices", edm::InputTag("offlinePrimaryVertices"));
333  desc.add<edm::InputTag>("pileup", edm::InputTag("addPileupInfo"));
334  desc.add<edm::InputTag>("genParticles", edm::InputTag("genParticles"));
335  desc.add<edm::InputTag>("srcMiniAOD", edm::InputTag("slimmedPhotons"));
336  desc.add<edm::InputTag>("verticesMiniAOD", edm::InputTag("offlineSlimmedPrimaryVertices"));
337  desc.add<edm::InputTag>("pileupMiniAOD", edm::InputTag("slimmedAddPileupInfo"));
338  desc.add<edm::InputTag>("genParticlesMiniAOD", edm::InputTag("prunedGenParticles"));
339  desc.add<edm::InputTag>("ebReducedRecHitCollection", edm::InputTag("reducedEcalRecHitsEB"));
340  desc.add<edm::InputTag>("eeReducedRecHitCollection", edm::InputTag("reducedEcalRecHitsEE"));
341  desc.add<edm::InputTag>("ebReducedRecHitCollectionMiniAOD", edm::InputTag("reducedEgamma","reducedEBRecHits"));
342  desc.add<edm::InputTag>("eeReducedRecHitCollectionMiniAOD", edm::InputTag("reducedEgamma","reducedEERecHits"));
343  desc.add<std::vector<std::string>>("phoMVAs", {});
344  desc.add<std::vector<std::string>>("phoMVALabels", {});
345  desc.add<std::vector<std::string>>("phoMVAValMaps", {});
346  desc.add<std::vector<std::string>>("phoMVAValMapLabels", {});
347  desc.add<std::vector<std::string>>("phoMVACats", {});
348  desc.add<std::vector<std::string>>("phoMVACatLabels", {});
349  desc.add<bool>("doEnergyMatrix", false);
350  desc.add<int>("energyMatrixSize", 2)->setComment("extension of crystals in each direction away from the seed");
351  desc.add<bool>("isMC", true);
352  desc.add<double>("ptThreshold", 15.0);
353  desc.add<double>("deltaR", 0.1);
354  desc.add<std::string>("variableDefinition");
355  descriptions.addDefault(desc);
356 }
357 
358 //define this as a plug-in
RunNumber_t run() const
Definition: EventID.h:39
size
Write out results.
static const std::string kSharedResource
Definition: TFileService.h:76
EventNumber_t event() const
Definition: EventID.h:41
bool isPromptFinalState() const
Definition: GenParticle.h:54
const std::string & getName(int index) const
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
const MVAVariableHelper< reco::Photon > variableHelper_
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:517
MVAVariableManager< reco::Photon > mvaVarMngr_
edm::LuminosityBlockNumber_t luminosityBlock() const
Definition: EventBase.h:61
const MultiTokenT< edm::View< reco::Photon > > src_
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 MultiTokenT< EcalRecHitCollection > ebRecHits_
const std::vector< std::string > valMapBranchNames_
std::vector< int > mvaCats_
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
const std::vector< std::string > phoMapTags_
std::vector< int > mvaPasses_
int iEvent
Definition: GenABIO.cc:224
const std::vector< std::string > valMapTags_
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void addDefault(ParameterSetDescription const &psetDescription)
std::vector< float > mvaValues_
const MultiTokenT< EcalRecHitCollection > eeRecHits_
const MultiTokenT< std::vector< reco::Vertex > > vertices_
ConsumesCollector consumesCollector()
Use a ConsumesCollector to gather consumes information from helper functions.
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
edm::Handle< T > getValidHandle(const edm::Event &iEvent) const
Definition: MultiToken.h:95
std::vector< edm::EDGetTokenT< edm::ValueMap< int > > > mvaCatTokens_
ParameterDescriptionBase * add(U const &iLabel, T const &value)
int k[5][pyjets_maxn]
const std::vector< float > getAuxVariables(edm::Ptr< ParticleType > const &particlePtr, const edm::Event &iEvent) const
const LorentzVector & p4(P4type type) const
std::vector< edm::EDGetTokenT< edm::ValueMap< bool > > > phoMapTokens_
const MultiTokenT< edm::View< reco::GenParticle > > genParticles_
const std::vector< std::string > mvaCatBranchNames_
edm::EventID id() const
Definition: EventBase.h:59
PhotonMatchType
std::vector< edm::EDGetTokenT< edm::ValueMap< float > > > valMapTokens_
const MultiTokenT< std::vector< PileupSummaryInfo > > pileup_
const std::vector< std::string > phoMapBranchNames_
void analyze(const edm::Event &, const edm::EventSetup &) override
std::vector< float > energyMatrix_
std::vector< float > vars_
PhotonMVANtuplizer(const edm::ParameterSet &)
const std::vector< std::string > mvaCatTags_