CMS 3D CMS Logo

SmearedJetProducerT.h
Go to the documentation of this file.
1 #ifndef PAT_SMEAREDJETPRODUCERT_H
2 #define PAT_SMEAREDJETPRODUCERT_H
3 
16 
25 
29 
31 
32 #include <TFile.h>
33 #include <TH1.h>
34 #include <TH1F.h>
35 
36 #include <memory>
37 #include <random>
38 
39 namespace pat {
40  class GenJetMatcher {
41  public:
43  m_genJetsToken(collector.consumes<reco::GenJetCollection>(cfg.getParameter<edm::InputTag>("genJets"))),
44  m_dR_max(cfg.getParameter<double>("dRMax")),
45  m_dPt_max_factor(cfg.getParameter<double>("dPtMaxFactor")) {
46  // Empty
47  }
48 
50  desc.add<edm::InputTag>("genJets");
51  desc.add<double>("dRMax");
52  desc.add<double>("dPtMaxFactor");
53  }
54 
55  void getTokens(const edm::Event& event) {
56  event.getByToken(m_genJetsToken, m_genJets);
57  }
58 
59  template<class T>
60  const reco::GenJet* match(const T& jet, double resolution) {
62 
63  // Try to find a gen jet matching
64  // dR < m_dR_max
65  // dPt < m_dPt_max_factor * resolution
66 
67  double min_dR = std::numeric_limits<double>::infinity();
68  const reco::GenJet* matched_genJet = nullptr;
69 
70  for (const auto& genJet: genJets) {
71  double dR = deltaR(genJet, jet);
72 
73  if (dR > min_dR)
74  continue;
75 
76  if (dR < m_dR_max) {
77  double dPt = std::abs(genJet.pt() - jet.pt());
78  if (dPt > m_dPt_max_factor * resolution)
79  continue;
80 
81  min_dR = dR;
82  matched_genJet = &genJet;
83  }
84  }
85 
86  return matched_genJet;
87  }
88 
89  private:
92 
93  double m_dR_max;
95  };
96 };
97 
98 template <typename T>
100 
101  using JetCollection = std::vector<T>;
102 
103  public:
105  m_enabled(cfg.getParameter<bool>("enabled")),
106  m_useDeterministicSeed(cfg.getParameter<bool>("useDeterministicSeed")),
107  m_debug(cfg.getUntrackedParameter<bool>("debug", false)) {
108 
109  m_jets_token = consumes<JetCollection>(cfg.getParameter<edm::InputTag>("src"));
110 
111  if (m_enabled) {
112  m_rho_token = consumes<double>(cfg.getParameter<edm::InputTag>("rho"));
113 
114  m_use_txt_files = cfg.exists("resolutionFile") && cfg.exists("scaleFactorFile");
115 
116  if (m_use_txt_files) {
117  std::string resolutionFile = cfg.getParameter<edm::FileInPath>("resolutionFile").fullPath();
118  std::string scaleFactorFile = cfg.getParameter<edm::FileInPath>("scaleFactorFile").fullPath();
119 
120  m_resolution_from_file.reset(new JME::JetResolution(resolutionFile));
121  m_scale_factor_from_file.reset(new JME::JetResolutionScaleFactor(scaleFactorFile));
122  } else {
123  m_jets_algo = cfg.getParameter<std::string>("algo");
124  m_jets_algo_pt = cfg.getParameter<std::string>("algopt");
125  }
126 
127  std::uint32_t seed = cfg.getParameter<std::uint32_t>("seed");
128  m_random_generator = std::mt19937(seed);
129 
130  bool skipGenMatching = cfg.getParameter<bool>("skipGenMatching");
131  if (! skipGenMatching)
132  m_genJetMatcher = std::make_shared<pat::GenJetMatcher>(cfg, consumesCollector());
133 
134  std::int32_t variation = cfg.getParameter<std::int32_t>("variation");
135  m_nomVar=1;
136  if (variation == 0)
137  m_systematic_variation = Variation::NOMINAL;
138  else if (variation == 1)
139  m_systematic_variation = Variation::UP;
140  else if (variation == -1)
141  m_systematic_variation = Variation::DOWN;
142  else if (variation == 101) {
143  m_systematic_variation = Variation::NOMINAL;
144  m_nomVar=1;
145  }
146  else if (variation == -101) {
147  m_systematic_variation = Variation::NOMINAL;
148  m_nomVar=-1;
149  }
150  else
151  throw edm::Exception(edm::errors::ConfigFileReadError, "Invalid value for 'variation' parameter. Only -1, 0, 1 or 101, -101 are supported.");
152  }
153 
154  produces<JetCollection>();
155  }
156 
159 
160  desc.add<edm::InputTag>("src");
161  desc.add<bool>("enabled");
162  desc.add<edm::InputTag>("rho");
163  desc.add<std::int32_t>("variation", 0);
164  desc.add<std::uint32_t>("seed", 37428479);
165  desc.add<bool>("skipGenMatching", false);
166  desc.add<bool>("useDeterministicSeed", true);
167  desc.addUntracked<bool>("debug", false);
168 
169  auto source =
171  (edm::ParameterDescription<edm::FileInPath>("resolutionFile", true) and edm::ParameterDescription<edm::FileInPath>("scaleFactorFile", true));
172  desc.addNode(std::move(source));
173 
175 
176  descriptions.addDefault(desc);
177  }
178 
179  virtual void produce(edm::Event& event, const edm::EventSetup& setup) override {
180 
181  edm::Handle<JetCollection> jets_collection;
182  event.getByToken(m_jets_token, jets_collection);
183 
184  // Disable the module when running on real data
185  if (m_enabled && event.isRealData()) {
186  m_enabled = false;
187  m_genJetMatcher.reset();
188  }
189 
191  if (m_enabled)
192  event.getByToken(m_rho_token, rho);
193 
195  JME::JetResolutionScaleFactor resolution_sf;
196 
197  const JetCollection& jets = *jets_collection;
198 
199  if (m_enabled) {
200  if (m_use_txt_files) {
201  resolution = *m_resolution_from_file;
202  resolution_sf = *m_scale_factor_from_file;
203  } else {
204  resolution = JME::JetResolution::get(setup, m_jets_algo_pt);
205  resolution_sf = JME::JetResolutionScaleFactor::get(setup, m_jets_algo);
206  }
207 
208  if(m_useDeterministicSeed) {
209  unsigned int runNum_uint = static_cast <unsigned int> (event.id().run());
210  unsigned int lumiNum_uint = static_cast <unsigned int> (event.id().luminosityBlock());
211  unsigned int evNum_uint = static_cast <unsigned int> (event.id().event());
212  unsigned int jet0eta = uint32_t(jets.empty() ? 0 : jets[0].eta()/0.01);
213  std::uint32_t seed = jet0eta + m_nomVar + (lumiNum_uint<<10) + (runNum_uint<<20) + evNum_uint;
214  m_random_generator.seed(seed);
215  }
216  }
217 
218  if (m_genJetMatcher)
219  m_genJetMatcher->getTokens(event);
220 
221  auto smearedJets = std::make_unique<JetCollection>();
222 
223  for (const auto& jet: jets) {
224 
225  if ((! m_enabled) || (jet.pt() == 0)) {
226  // Module disabled or invalid p4. Simply copy the input jet.
227  smearedJets->push_back(jet);
228 
229  continue;
230  }
231 
232  double jet_resolution = resolution.getResolution({{JME::Binning::JetPt, jet.pt()}, {JME::Binning::JetEta, jet.eta()}, {JME::Binning::Rho, *rho}});
233  double jer_sf = resolution_sf.getScaleFactor({{JME::Binning::JetEta, jet.eta()}}, m_systematic_variation);
234 
235  if (m_debug) {
236  std::cout << "jet: pt: " << jet.pt() << " eta: " << jet.eta() << " phi: " << jet.phi() << " e: " << jet.energy() << std::endl;
237  std::cout << "resolution: " << jet_resolution << std::endl;
238  std::cout << "resolution scale factor: " << jer_sf << std::endl;
239  }
240 
241  const reco::GenJet* genJet = nullptr;
242  if (m_genJetMatcher)
243  genJet = m_genJetMatcher->match(jet, jet.pt() * jet_resolution);
244 
245  double smearFactor = 1.;
246 
247  if (genJet) {
248  /*
249  * Case 1: we have a "good" gen jet matched to the reco jet
250  */
251 
252  if (m_debug) {
253  std::cout << "gen jet: pt: " << genJet->pt() << " eta: " << genJet->eta() << " phi: " << genJet->phi() << " e: " << genJet->energy() << std::endl;
254  }
255 
256  double dPt = jet.pt() - genJet->pt();
257  smearFactor = 1 + m_nomVar*(jer_sf - 1.) * dPt / jet.pt();
258 
259  } else if (jer_sf > 1) {
260  /*
261  * Case 2: we don't have a gen jet. Smear jet pt using a random gaussian variation
262  */
263 
264  double sigma = jet_resolution * std::sqrt(jer_sf * jer_sf - 1);
265  if (m_debug) {
266  std::cout << "gaussian width: " << sigma << std::endl;
267  }
268 
269  std::normal_distribution<> d(0, sigma);
270  smearFactor = 1. + m_nomVar*d(m_random_generator);
271  } else if (m_debug) {
272  std::cout << "Impossible to smear this jet" << std::endl;
273  }
274 
275  if (jet.energy() * smearFactor < MIN_JET_ENERGY) {
276  // Negative or too small smearFactor. We would change direction of the jet
277  // and this is not what we want.
278  // Recompute the smearing factor in order to have jet.energy() == MIN_JET_ENERGY
279  double newSmearFactor = MIN_JET_ENERGY / jet.energy();
280  if (m_debug) {
281  std::cout << "The smearing factor (" << smearFactor << ") is either negative or too small. Fixing it to " << newSmearFactor << " to avoid change of direction." << std::endl;
282  }
283  smearFactor = newSmearFactor;
284  }
285 
286  T smearedJet = jet;
287  smearedJet.scaleEnergy(smearFactor);
288 
289  if (m_debug) {
290  std::cout << "smeared jet (" << smearFactor << "): pt: " << smearedJet.pt() << " eta: " << smearedJet.eta() << " phi: " << smearedJet.phi() << " e: " << smearedJet.energy() << std::endl;
291  }
292 
293  smearedJets->push_back(smearedJet);
294  }
295 
296  // Sort jets by pt
297  std::sort(smearedJets->begin(), smearedJets->end(), jetPtComparator);
298 
299  event.put(std::move(smearedJets));
300  }
301 
302  private:
303  static constexpr const double MIN_JET_ENERGY = 1e-2;
304 
307  bool m_enabled;
312  bool m_debug;
313  std::shared_ptr<pat::GenJetMatcher> m_genJetMatcher;
314 
316  std::unique_ptr<JME::JetResolution> m_resolution_from_file;
317  std::unique_ptr<JME::JetResolutionScaleFactor> m_scale_factor_from_file;
318 
319  std::mt19937 m_random_generator;
320 
322 
323  int m_nomVar;
324 };
325 #endif
edm::EDGetTokenT< JetCollection > m_jets_token
T getParameter(std::string const &) const
virtual double pt() const final
transverse momentum
float getResolution(const JetParameters &parameters) const
void getTokens(const edm::Event &event)
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
static const JetResolution get(const edm::EventSetup &, const std::string &)
virtual double eta() const final
momentum pseudorapidity
edm::Handle< reco::GenJetCollection > m_genJets
std::vector< GenJet > GenJetCollection
collection of GenJet objects
virtual void produce(edm::Event &event, const edm::EventSetup &setup) override
GenJetMatcher(const edm::ParameterSet &cfg, edm::ConsumesCollector &&collector)
bool exists(std::string const &parameterName) const
checks if a parameter exists
SmearedJetProducerT(const edm::ParameterSet &cfg)
ParameterDescriptionNode * addNode(ParameterDescriptionNode const &node)
def setup(process, global_tag, zero_tesla=False)
Definition: GeneralSetup.py:1
bool isRealData() const
Definition: EventBase.h:64
#define constexpr
Definition: HeavyIon.h:7
GreaterByPt< T > jetPtComparator
const reco::GenJet * match(const T &jet, double resolution)
virtual double phi() const final
momentum azimuthal angle
std::unique_ptr< JME::JetResolution > m_resolution_from_file
static void fillDescriptions(edm::ParameterSetDescription &desc)
void addDefault(ParameterSetDescription const &psetDescription)
std::vector< T > JetCollection
T sqrt(T t)
Definition: SSEVec.h:18
vector< PseudoJet > jets
virtual double energy() const final
energy
const double infinity
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
Jets made from MC generator particles.
Definition: GenJet.h:24
ParameterDescriptionBase * add(U const &iLabel, T const &value)
edm::EDGetTokenT< double > m_rho_token
double deltaR(double eta1, double eta2, double phi1, double phi2)
Definition: TreeUtility.cc:17
std::mt19937 m_random_generator
float getScaleFactor(const JetParameters &parameters, Variation variation=Variation::NOMINAL) const
static const JetResolutionScaleFactor get(const edm::EventSetup &, const std::string &)
std::shared_ptr< pat::GenJetMatcher > m_genJetMatcher
fixed size matrix
HLT enums.
std::unique_ptr< JME::JetResolutionScaleFactor > m_scale_factor_from_file
edm::EDGetTokenT< reco::GenJetCollection > m_genJetsToken
long double T
static std::string const source
Definition: EdmProvDump.cc:43
def move(src, dest)
Definition: eostools.py:510
Definition: event.py:1