CMS 3D CMS Logo

GenWeightsTableProducer.cc
Go to the documentation of this file.
14 #include "boost/algorithm/string.hpp"
15 
16 #include <vector>
17 #include <unordered_map>
18 #include <iostream>
19 #include <regex>
20 
21 namespace {
23  struct Counter {
24  Counter() :
25  num(0), sumw(0), sumw2(0), sumPDF(), sumScale(), sumRwgt(), sumNamed(), sumPS() {}
26 
27  // the counters
28  long long num;
29  long double sumw;
30  long double sumw2;
31  std::vector<long double> sumPDF, sumScale, sumRwgt, sumNamed, sumPS;
32 
33  void clear() {
34  num = 0; sumw = 0; sumw2 = 0;
35  sumPDF.clear(); sumScale.clear(); sumRwgt.clear(); sumNamed.clear(), sumPS.clear();
36  }
37 
38  // inc the counters
39  void incGenOnly(double w) {
40  num++; sumw += w; sumw2 += (w*w);
41  }
42 
43  void incPSOnly(double w0, const std::vector<double> & wPS) {
44  if (!wPS.empty()) {
45  if (sumPS.empty()) sumPS.resize(wPS.size(), 0);
46  for (unsigned int i = 0, n = wPS.size(); i < n; ++i) sumPS[i] += (w0 * wPS[i]);
47  }
48  }
49 
50  void incLHE(double w0, const std::vector<double> & wScale, const std::vector<double> & wPDF, const std::vector<double> & wRwgt, const std::vector<double> & wNamed, const std::vector<double> & wPS) {
51  // add up weights
52  incGenOnly(w0);
53  // then add up variations
54  if (!wScale.empty()) {
55  if (sumScale.empty()) sumScale.resize(wScale.size(), 0);
56  for (unsigned int i = 0, n = wScale.size(); i < n; ++i) sumScale[i] += (w0 * wScale[i]);
57  }
58  if (!wPDF.empty()) {
59  if (sumPDF.empty()) sumPDF.resize(wPDF.size(), 0);
60  for (unsigned int i = 0, n = wPDF.size(); i < n; ++i) sumPDF[i] += (w0 * wPDF[i]);
61  }
62  if (!wRwgt.empty()) {
63  if (sumRwgt.empty()) sumRwgt.resize(wRwgt.size(), 0);
64  for (unsigned int i = 0, n = wRwgt.size(); i < n; ++i) sumRwgt[i] += (w0 * wRwgt[i]);
65  }
66  if (!wNamed.empty()) {
67  if (sumNamed.empty()) sumNamed.resize(wNamed.size(), 0);
68  for (unsigned int i = 0, n = wNamed.size(); i < n; ++i) sumNamed[i] += (w0 * wNamed[i]);
69  }
70  incPSOnly(w0, wPS);
71  }
72 
73  void merge(const Counter & other) {
74  num += other.num; sumw += other.sumw; sumw2 += other.sumw2;
75  if (sumScale.empty() && !other.sumScale.empty()) sumScale.resize(other.sumScale.size(),0);
76  if (sumPDF.empty() && !other.sumPDF.empty()) sumPDF.resize(other.sumPDF.size(),0);
77  if (sumRwgt.empty() && !other.sumRwgt.empty()) sumRwgt.resize(other.sumRwgt.size(),0);
78  if (sumNamed.empty() && !other.sumNamed.empty()) sumNamed.resize(other.sumNamed.size(),0);
79  if (sumPS.empty() && !other.sumPS.empty()) sumPS.resize(other.sumPS.size(),0);
80  if (!other.sumScale.empty()) for (unsigned int i = 0, n = sumScale.size(); i < n; ++i) sumScale[i] += other.sumScale[i];
81  if (!other.sumPDF.empty()) for (unsigned int i = 0, n = sumPDF.size(); i < n; ++i) sumPDF[i] += other.sumPDF[i];
82  if (!other.sumRwgt.empty()) for (unsigned int i = 0, n = sumRwgt.size(); i < n; ++i) sumRwgt[i] += other.sumRwgt[i];
83  if (!other.sumNamed.empty()) for (unsigned int i = 0, n = sumNamed.size(); i < n; ++i) sumNamed[i] += other.sumNamed[i];
84  if (!other.sumPS.empty()) for (unsigned int i = 0, n = sumPS.size(); i < n; ++i) sumPS[i] += other.sumPS[i];
85  }
86  };
87 
89  struct DynamicWeightChoice {
90  // choice of LHE weights
91  // ---- scale ----
92  std::vector<std::string> scaleWeightIDs;
93  std::string scaleWeightsDoc;
94  // ---- pdf ----
95  std::vector<std::string> pdfWeightIDs;
96  std::string pdfWeightsDoc;
97  // ---- rwgt ----
98  std::vector<std::string> rwgtIDs;
99  std::string rwgtWeightDoc;
100  };
101 
102  float stof_fortrancomp(const std::string &str) {
103  std::string::size_type match = str.find("d");
104  if (match != std::string::npos) {
105  std::string pre = str.substr(0,match);
106  std::string post = str.substr(match+1);
107  return std::stof(pre) * std::pow(10.0f, std::stof(post));
108  } else {
109  return std::stof(str);
110  }
111  }
113  struct ScaleVarWeight {
114  std::string wid, label;
115  std::pair<float,float> scales;
116  ScaleVarWeight(const std::string & id, const std::string & text, const std::string & muR, const std::string & muF) :
117  wid(id), label(text), scales(stof_fortrancomp(muR), stof_fortrancomp(muF)) {}
118  bool operator<(const ScaleVarWeight & other) { return (scales == other.scales ? wid < other.wid : scales < other.scales); }
119  };
120  struct PDFSetWeights {
121  std::vector<std::string> wids;
122  std::pair<unsigned int,unsigned int> lhaIDs;
123  PDFSetWeights(const std::string & wid, unsigned int lhaID) : wids(1,wid), lhaIDs(lhaID,lhaID) {}
124  bool operator<(const PDFSetWeights & other) const { return lhaIDs < other.lhaIDs; }
125  void add(const std::string & wid, unsigned int lhaID) {
126  wids.push_back(wid);
127  lhaIDs.second = lhaID;
128  }
129  bool maybe_add(const std::string & wid, unsigned int lhaID) {
130  if (lhaID == lhaIDs.second+1) {
131  lhaIDs.second++;
132  wids.push_back(wid);
133  return true;
134  } else {
135  return false;
136  }
137  }
138  };
139 }
140 
141 class GenWeightsTableProducer : public edm::global::EDProducer<edm::StreamCache<Counter>, edm::RunCache<DynamicWeightChoice>, edm::RunSummaryCache<Counter>, edm::EndRunProducer> {
142  public:
144  genTag_(consumes<GenEventInfoProduct>(params.getParameter<edm::InputTag>("genEvent"))),
145  lheLabel_(params.getParameter<std::vector<edm::InputTag>>("lheInfo")),
146  lheTag_(edm::vector_transform(lheLabel_, [this](const edm::InputTag & tag) { return mayConsume<LHEEventProduct>(tag); })),
147  lheRunTag_(edm::vector_transform(lheLabel_, [this](const edm::InputTag & tag) { return mayConsume<LHERunInfoProduct, edm::InRun>(tag); })),
148  namedWeightIDs_(params.getParameter<std::vector<std::string>>("namedWeightIDs")),
149  namedWeightLabels_(params.getParameter<std::vector<std::string>>("namedWeightLabels")),
150  lheWeightPrecision_(params.getParameter<int32_t>("lheWeightPrecision")),
151  maxPdfWeights_(params.getParameter<uint32_t>("maxPdfWeights")),
152  debug_(params.getUntrackedParameter<bool>("debug",false)), debugRun_(debug_.load()),
153  hasIssuedWarning_(false)
154  {
155  produces<nanoaod::FlatTable>();
156  produces<nanoaod::FlatTable>("LHEScale");
157  produces<nanoaod::FlatTable>("LHEPdf");
158  produces<nanoaod::FlatTable>("LHEReweighting");
159  produces<nanoaod::FlatTable>("LHENamed");
160  produces<nanoaod::FlatTable>("PS");
161  produces<nanoaod::MergeableCounterTable,edm::Transition::EndRun>();
162  if (namedWeightIDs_.size() != namedWeightLabels_.size()) {
163  throw cms::Exception("Configuration", "Size mismatch between namedWeightIDs & namedWeightLabels");
164  }
165  for (const edm::ParameterSet & pdfps : params.getParameter<std::vector<edm::ParameterSet>>("preferredPDFs")) {
166  const std::string & name = pdfps.getParameter<std::string>("name");
167  uint32_t lhaid = pdfps.getParameter<uint32_t>("lhaid");
168  preferredPDFLHAIDs_.push_back(lhaid);
169  lhaNameToID_[name] = lhaid;
170  lhaNameToID_[name+".LHgrid"] = lhaid;
171  }
172  }
173 
175 
176  void produce(edm::StreamID id, edm::Event& iEvent, const edm::EventSetup& iSetup) const override {
177  // get my counter for weights
178  Counter * counter = streamCache(id);
179 
180  // generator information (always available)
182  iEvent.getByToken(genTag_, genInfo);
183  double weight = genInfo->weight();
184 
185  // table for gen info, always available
186  auto out = std::make_unique<nanoaod::FlatTable>(1, "genWeight", true);
187  out->setDoc("generator weight");
188  out->addColumnValue<float>("", weight, "generator weight", nanoaod::FlatTable::FloatColumn);
189  iEvent.put(std::move(out));
190 
191  // tables for LHE weights, may not be filled
192  std::unique_ptr<nanoaod::FlatTable> lheScaleTab, lhePdfTab, lheRwgtTab, lheNamedTab;
193  std::unique_ptr<nanoaod::FlatTable> genPSTab;
194 
196  for (const auto & lheTag: lheTag_) {
197  iEvent.getByToken(lheTag, lheInfo);
198  if (lheInfo.isValid()) {
199  break;
200  }
201  }
202  if (lheInfo.isValid()) {
203  // get the dynamic choice of weights
204  const DynamicWeightChoice * weightChoice = runCache(iEvent.getRun().index());
205  // go fill tables
206  fillLHEWeightTables(counter, weightChoice, weight, *lheInfo, *genInfo, lheScaleTab, lhePdfTab, lheRwgtTab, lheNamedTab, genPSTab);
207  } else {
208  // Still try to add the PS weights
209  fillOnlyPSWeightTable(counter, weight, *genInfo, genPSTab);
210  // make dummy values
211  lheScaleTab.reset(new nanoaod::FlatTable(1, "LHEScaleWeights", true));
212  lhePdfTab.reset(new nanoaod::FlatTable(1, "LHEPdfWeights", true));
213  lheRwgtTab.reset(new nanoaod::FlatTable(1, "LHEReweightingWeights", true));
214  lheNamedTab.reset(new nanoaod::FlatTable(1, "LHENamedWeights", true));
215  if (!hasIssuedWarning_.exchange(true)) {
216  edm::LogWarning("LHETablesProducer") << "No LHEEventProduct, so there will be no LHE Tables\n";
217  }
218  }
219 
220  iEvent.put(std::move(lheScaleTab), "LHEScale");
221  iEvent.put(std::move(lhePdfTab), "LHEPdf");
222  iEvent.put(std::move(lheRwgtTab), "LHEReweighting");
223  iEvent.put(std::move(lheNamedTab), "LHENamed");
224  iEvent.put(std::move(genPSTab), "PS");
225  }
226 
228  Counter * counter,
229  const DynamicWeightChoice * weightChoice,
230  double genWeight,
231  const LHEEventProduct & lheProd,
232  const GenEventInfoProduct & genProd,
233  std::unique_ptr<nanoaod::FlatTable> & outScale,
234  std::unique_ptr<nanoaod::FlatTable> & outPdf,
235  std::unique_ptr<nanoaod::FlatTable> & outRwgt,
236  std::unique_ptr<nanoaod::FlatTable> & outNamed,
237  std::unique_ptr<nanoaod::FlatTable> & outPS ) const
238  {
239  bool lheDebug = debug_.exchange(false); // make sure only the first thread dumps out this (even if may still be mixed up with other output, but nevermind)
240 
241  const std::vector<std::string> & scaleWeightIDs = weightChoice->scaleWeightIDs;
242  const std::vector<std::string> & pdfWeightIDs = weightChoice->pdfWeightIDs;
243  const std::vector<std::string> & rwgtWeightIDs = weightChoice->rwgtIDs;
244 
245  double w0 = lheProd.originalXWGTUP();
246 
247  std::vector<double> wScale(scaleWeightIDs.size(), 1), wPDF(pdfWeightIDs.size(), 1), wRwgt(rwgtWeightIDs.size(), 1), wNamed(namedWeightIDs_.size(), 1);
248  for (auto & weight : lheProd.weights()) {
249  if (lheDebug) printf("Weight %+9.5f rel %+9.5f for id %s\n", weight.wgt, weight.wgt/w0, weight.id.c_str());
250  // now we do it slowly, can be optimized
251  auto mScale = std::find(scaleWeightIDs.begin(), scaleWeightIDs.end(), weight.id);
252  if (mScale != scaleWeightIDs.end()) wScale[mScale-scaleWeightIDs.begin()] = weight.wgt/w0;
253 
254  auto mPDF = std::find(pdfWeightIDs.begin(), pdfWeightIDs.end(), weight.id);
255  if (mPDF != pdfWeightIDs.end()) wPDF[mPDF-pdfWeightIDs.begin()] = weight.wgt/w0;
256 
257  auto mRwgt = std::find(rwgtWeightIDs.begin(), rwgtWeightIDs.end(), weight.id);
258  if (mRwgt != rwgtWeightIDs.end()) wRwgt[mRwgt-rwgtWeightIDs.begin()] = weight.wgt/w0;
259 
260  auto mNamed = std::find(namedWeightIDs_.begin(), namedWeightIDs_.end(), weight.id);
261  if (mNamed != namedWeightIDs_.end()) wNamed[mNamed-namedWeightIDs_.begin()] = weight.wgt/w0;
262  }
263 
264  int vectorSize = (genProd.weights().size() == 14 || genProd.weights().size() == 46) ? 4 : 1;
265  std::vector<double> wPS(vectorSize, 1);
266  if (vectorSize > 1 ) {
267  for (unsigned int i=6; i<10; i++){
268  wPS[i-6] = (genProd.weights()[i])/w0;
269  }
270  }
271  outPS.reset(new nanoaod::FlatTable(wPS.size(), "PSWeight", false));
272  outPS->addColumn<float>("", wPS, vectorSize > 1 ? "PS weights (w_var / w_nominal); [0] is ISR=0.5 FSR=1; [1] is ISR=1 FSR=0.5; [2] is ISR=2 FSR=1; [3] is ISR=1 FSR=2 " : "dummy PS weight (1.0) ", nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
273 
274  outScale.reset(new nanoaod::FlatTable(wScale.size(), "LHEScaleWeight", false));
275  outScale->addColumn<float>("", wScale, weightChoice->scaleWeightsDoc, nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
276 
277  outPdf.reset(new nanoaod::FlatTable(wPDF.size(), "LHEPdfWeight", false));
278  outPdf->addColumn<float>("", wPDF, weightChoice->pdfWeightsDoc, nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
279 
280  outRwgt.reset(new nanoaod::FlatTable(wRwgt.size(), "LHEReweightingWeight", false));
281  outRwgt->addColumn<float>("", wRwgt, weightChoice->rwgtWeightDoc, nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
282 
283  outNamed.reset(new nanoaod::FlatTable(1, "LHEWeight", true));
284  outNamed->addColumnValue<float>("originalXWGTUP", lheProd.originalXWGTUP(), "Nominal event weight in the LHE file", nanoaod::FlatTable::FloatColumn);
285  for (unsigned int i = 0, n = wNamed.size(); i < n; ++i) {
286  outNamed->addColumnValue<float>(namedWeightLabels_[i], wNamed[i], "LHE weight for id "+namedWeightIDs_[i]+", relative to nominal", nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
287  }
288 
289  counter->incLHE(genWeight, wScale, wPDF, wRwgt, wNamed, wPS);
290  }
291 
293  Counter * counter,
294  double genWeight,
295  const GenEventInfoProduct & genProd,
296  std::unique_ptr<nanoaod::FlatTable> & outPS ) const
297  {
298  int vectorSize = (genProd.weights().size() == 14 || genProd.weights().size() == 46) ? 4 : 1;
299 
300  std::vector<double> wPS(vectorSize, 1);
301  if (vectorSize > 1 ){
302  for (unsigned int i=6; i<10; i++){
303  wPS[i-6] = (genProd.weights()[i])/genWeight;
304  }
305  }
306 
307  outPS.reset(new nanoaod::FlatTable(wPS.size(), "PSWeight", false));
308  outPS->addColumn<float>("", wPS, vectorSize > 1 ? "PS weights (w_var / w_nominal); [0] is ISR=0.5 FSR=1; [1] is ISR=1 FSR=0.5; [2] is ISR=2 FSR=1; [3] is ISR=1 FSR=2 " : "dummy PS weight (1.0) " , nanoaod::FlatTable::FloatColumn, lheWeightPrecision_);
309 
310  counter->incGenOnly(genWeight);
311  counter->incPSOnly(genWeight,wPS);
312  }
313 
314 
315 
316  // create an empty counter
317  std::shared_ptr<DynamicWeightChoice> globalBeginRun(edm::Run const& iRun, edm::EventSetup const&) const override {
319 
320  bool lheDebug = debugRun_.exchange(false); // make sure only the first thread dumps out this (even if may still be mixed up with other output, but nevermind)
321  auto weightChoice = std::make_shared<DynamicWeightChoice>();
322 
323  // getByToken throws since we're not in the endRun (see https://github.com/cms-sw/cmssw/pull/18499)
324  //if (iRun.getByToken(lheRunTag_, lheInfo)) {
325  for (const auto & lheLabel: lheLabel_) {
326  iRun.getByLabel(lheLabel, lheInfo);
327  if (lheInfo.isValid()) {
328  break;
329  }
330  }
331  if (lheInfo.isValid()) {
332  std::vector<ScaleVarWeight> scaleVariationIDs;
333  std::vector<PDFSetWeights> pdfSetWeightIDs;
334  std::vector<std::string> lheReweighingIDs;
335 
336  std::regex weightgroupmg26x("<weightgroup\\s+(?:name|type)=\"(.*)\"\\s+combine=\"(.*)\"\\s*>");
337  std::regex weightgroup("<weightgroup\\s+combine=\"(.*)\"\\s+(?:name|type)=\"(.*)\"\\s*>");
338  std::regex weightgroupRwgt("<weightgroup\\s+(?:name|type)=\"(.*)\"\\s*>");
339  std::regex endweightgroup("</weightgroup>");
340  std::regex scalewmg26x("<weight\\s+(?:.*\\s+)?id=\"(\\d+)\"\\s*(?:lhapdf=\\d+|dyn=\\s*-?\\d+)?\\s*((?:[mM][uU][rR]|renscfact)=\"(\\S+)\"\\s+(?:[mM][uU][Ff]|facscfact)=\"(\\S+)\")(\\s+.*)?</weight>");
341  std::regex scalew("<weight\\s+(?:.*\\s+)?id=\"(\\d+)\">\\s*(?:lhapdf=\\d+|dyn=\\s*-?\\d+)?\\s*((?:mu[rR]|renscfact)=(\\S+)\\s+(?:mu[Ff]|facscfact)=(\\S+)(\\s+.*)?)</weight>");
342  std::regex pdfw("<weight\\s+id=\"(\\d+)\">\\s*(?:PDF set|lhapdf|PDF|pdfset)\\s*=\\s*(\\d+)\\s*(?:\\s.*)?</weight>");
343  std::regex pdfwOld("<weight\\s+(?:.*\\s+)?id=\"(\\d+)\">\\s*Member \\s*(\\d+)\\s*(?:.*)</weight>");
344  std::regex pdfwmg26x("<weight\\s+id=\"(\\d+)\"\\s*MUR=\"(?:\\S+)\"\\s*MUF=\"(?:\\S+)\"\\s*(?:PDF set|lhapdf|PDF|pdfset)\\s*=\\s*\"(\\d+)\"\\s*>\\s*(?:PDF=(\\d+)\\s*MemberID=(\\d+))?\\s*(?:\\s.*)?</weight>");
345  std::regex rwgt("<weight\\s+id=\"(.+)\">(.+)?(</weight>)?");
346  std::smatch groups;
347  for (auto iter=lheInfo->headers_begin(), end = lheInfo->headers_end(); iter != end; ++iter) {
348  if (iter->tag() != "initrwgt") {
349  if (lheDebug) std::cout << "Skipping LHE header with tag" << iter->tag() << std::endl;
350  continue;
351  }
352  if (lheDebug) std::cout << "Found LHE header with tag" << iter->tag() << std::endl;
353  std::vector<std::string> lines = iter->lines();
354  bool missed_weightgroup=false; //Needed because in some of the samples ( produced with MG26X ) a small part of the header info is ordered incorrectly
355  bool ismg26x=false;
356  for (unsigned int iLine = 0, nLines = lines.size(); iLine < nLines; ++iLine) { //First start looping through the lines to see which weightgroup pattern is matched
357  boost::replace_all(lines[iLine],"&lt;", "<");
358  boost::replace_all(lines[iLine],"&gt;", ">");
359  if(std::regex_search(lines[iLine],groups,weightgroupmg26x)){
360  ismg26x=true;
361  }
362  }
363  for (unsigned int iLine = 0, nLines = lines.size(); iLine < nLines; ++iLine) {
364  if (lheDebug) std::cout << lines[iLine];
365  if (std::regex_search(lines[iLine], groups, ismg26x ? weightgroupmg26x : weightgroup) ) {
366  std::string groupname = groups.str(2);
367  if (ismg26x) groupname = groups.str(1);
368  if (lheDebug) std::cout << ">>> Looks like the beginning of a weight group for '" << groupname << "'" << std::endl;
369  if (groupname.find("scale_variation") == 0 || groupname == "Central scale variation") {
370  if (lheDebug) std::cout << ">>> Looks like scale variation for theory uncertainties" << std::endl;
371  for ( ++iLine; iLine < nLines; ++iLine) {
372  if (lheDebug) std::cout << " " << lines[iLine];
373  if (std::regex_search(lines[iLine], groups, ismg26x ? scalewmg26x : scalew)) {
374  if (lheDebug) std::cout << " >>> Scale weight " << groups[1].str() << " for " << groups[3].str() << " , " << groups[4].str() << " , " << groups[5].str() << std::endl;
375  scaleVariationIDs.emplace_back(groups.str(1), groups.str(2), groups.str(3), groups.str(4));
376  } else if (std::regex_search(lines[iLine], endweightgroup)) {
377  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
378  if (!missed_weightgroup){
379  break;
380  } else missed_weightgroup=false;
381  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
382  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
383  if (ismg26x) missed_weightgroup=true;
384  --iLine; // rewind by one, and go back to the outer loop
385  break;
386  }
387  }
388  } else if (groupname == "PDF_variation" || groupname.find("PDF_variation ") == 0) {
389  if (lheDebug) std::cout << ">>> Looks like a new-style block of PDF weights for one or more pdfs" << std::endl;
390  for ( ++iLine; iLine < nLines; ++iLine) {
391  if (lheDebug) std::cout << " " << lines[iLine];
392  if (std::regex_search(lines[iLine], groups, pdfw)) {
393  unsigned int lhaID = std::stoi(groups.str(2));
394  if (lheDebug) std::cout << " >>> PDF weight " << groups.str(1) << " for " << groups.str(2) << " = " << lhaID << std::endl;
395  if (pdfSetWeightIDs.empty() || ! pdfSetWeightIDs.back().maybe_add(groups.str(1),lhaID)) {
396  pdfSetWeightIDs.emplace_back(groups.str(1),lhaID);
397  }
398  } else if (std::regex_search(lines[iLine], endweightgroup)) {
399  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
400  if (!missed_weightgroup){
401  break;
402  } else missed_weightgroup=false;
403  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
404  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
405  if (ismg26x) missed_weightgroup=true;
406  --iLine; // rewind by one, and go back to the outer loop
407  break;
408  }
409  }
410  } else if (groupname == "PDF_variation1" || groupname == "PDF_variation2") {
411  if (lheDebug) std::cout << ">>> Looks like a new-style block of PDF weights for multiple pdfs" << std::endl;
412  unsigned int lastid = 0;
413  for ( ++iLine; iLine < nLines; ++iLine) {
414  if (lheDebug) std::cout << " " << lines[iLine];
415  if (std::regex_search(lines[iLine], groups, pdfw)) {
416  unsigned int id = std::stoi(groups.str(1));
417  unsigned int lhaID = std::stoi(groups.str(2));
418  if (lheDebug) std::cout << " >>> PDF weight " << groups.str(1) << " for " << groups.str(2) << " = " << lhaID << std::endl;
419  if (id != (lastid+1) || pdfSetWeightIDs.empty()) {
420  pdfSetWeightIDs.emplace_back(groups.str(1),lhaID);
421  } else {
422  pdfSetWeightIDs.back().add(groups.str(1),lhaID);
423  }
424  lastid = id;
425  } else if (std::regex_search(lines[iLine], endweightgroup)) {
426  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
427  if(!missed_weightgroup) {
428  break;
429  } else missed_weightgroup=false;
430  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
431  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
432  if (ismg26x) missed_weightgroup=true;
433  --iLine; // rewind by one, and go back to the outer loop
434  break;
435  }
436  }
437  } else if (lhaNameToID_.find(groupname) != lhaNameToID_.end()) {
438  if (lheDebug) std::cout << ">>> Looks like an old-style PDF weight for an individual pdf" << std::endl;
439  unsigned int firstLhaID = lhaNameToID_.find(groupname)->second;
440  bool first = true;
441  for ( ++iLine; iLine < nLines; ++iLine) {
442  if (lheDebug) std::cout << " " << lines[iLine];
443  if (std::regex_search(lines[iLine], groups, ismg26x ? pdfwmg26x : pdfwOld)) {
444  unsigned int member = 0;
445  if (ismg26x==0){
446  member = std::stoi(groups.str(2));
447  } else {
448  if (!groups.str(4).empty()){
449  member = std::stoi(groups.str(4));
450  }
451  }
452  unsigned int lhaID = member+firstLhaID;
453  if (lheDebug) std::cout << " >>> PDF weight " << groups.str(1) << " for " << member << " = " << lhaID << std::endl;
454  //if (member == 0) continue; // let's keep also the central value for now
455  if (first) {
456  pdfSetWeightIDs.emplace_back(groups.str(1),lhaID);
457  first = false;
458  } else {
459  pdfSetWeightIDs.back().add(groups.str(1),lhaID);
460  }
461  } else if (std::regex_search(lines[iLine], endweightgroup)) {
462  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
463  if (!missed_weightgroup) {
464  break;
465  } else missed_weightgroup=false;
466  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
467  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
468  if (ismg26x) missed_weightgroup=true;
469  --iLine; // rewind by one, and go back to the outer loop
470  break;
471  }
472  }
473  } else {
474  for ( ++iLine; iLine < nLines; ++iLine) {
475  if (lheDebug) std::cout << " " << lines[iLine];
476  if (std::regex_search(lines[iLine], groups, endweightgroup)) {
477  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
478  if (!missed_weightgroup){
479  break;
480  } else missed_weightgroup=false;
481  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
482  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
483  if (ismg26x) missed_weightgroup=true;
484  --iLine; // rewind by one, and go back to the outer loop
485  break;
486  }
487  }
488  }
489  } else if(std::regex_search(lines[iLine], groups, weightgroupRwgt) ) {
490  std::string groupname = groups.str(1);
491  if (groupname == "mg_reweighting") {
492  if (lheDebug) std::cout << ">>> Looks like a LHE weights for reweighting" << std::endl;
493  for ( ++iLine; iLine < nLines; ++iLine) {
494  if (lheDebug) std::cout << " " << lines[iLine];
495  if (std::regex_search(lines[iLine], groups, rwgt)) {
496  std::string rwgtID = groups.str(1);
497  if (lheDebug) std::cout << " >>> LHE reweighting weight: " << rwgtID << std::endl;
498  if (std::find(lheReweighingIDs.begin(), lheReweighingIDs.end(), rwgtID) == lheReweighingIDs.end()) {
499  // we're only interested in the beggining of the block
500  lheReweighingIDs.emplace_back(rwgtID);
501  }
502  } else if (std::regex_search(lines[iLine], endweightgroup)) {
503  if (lheDebug) std::cout << ">>> Looks like the end of a weight group" << std::endl;
504  if (!missed_weightgroup){
505  break;
506  } else missed_weightgroup=false;
507  } else if (std::regex_search(lines[iLine], ismg26x ? weightgroupmg26x : weightgroup)) {
508  if (lheDebug) std::cout << ">>> Looks like the beginning of a new weight group, I will assume I missed the end of the group." << std::endl;
509  if (ismg26x) missed_weightgroup=true;
510  --iLine; // rewind by one, and go back to the outer loop
511  break;
512  }
513  }
514  }
515  }
516  }
517  //std::cout << "============= END [ " << iter->tag() << " ] ============ \n\n" << std::endl;
518 
519  // ----- SCALE VARIATIONS -----
520  std::sort(scaleVariationIDs.begin(), scaleVariationIDs.end());
521  if (lheDebug) std::cout << "Found " << scaleVariationIDs.size() << " scale variations: " << std::endl;
522  std::stringstream scaleDoc; scaleDoc << "LHE scale variation weights (w_var / w_nominal); ";
523  for (unsigned int isw = 0, nsw = scaleVariationIDs.size(); isw < nsw; ++isw) {
524  const auto & sw = scaleVariationIDs[isw];
525  if (isw) scaleDoc << "; ";
526  scaleDoc << "[" << isw << "] is " << sw.label;
527  weightChoice->scaleWeightIDs.push_back(sw.wid);
528  if (lheDebug) printf(" id %s: scales ren = % .2f fact = % .2f text = %s\n", sw.wid.c_str(), sw.scales.first, sw.scales.second, sw.label.c_str());
529  }
530  if (!scaleVariationIDs.empty()) weightChoice->scaleWeightsDoc = scaleDoc.str();
531 
532  // ------ PDF VARIATIONS (take the preferred one) -----
533  if (lheDebug) {
534  std::cout << "Found " << pdfSetWeightIDs.size() << " PDF set errors: " << std::endl;
535  for (const auto & pw : pdfSetWeightIDs) printf("lhaIDs %6d - %6d (%3lu weights: %s, ... )\n", pw.lhaIDs.first, pw.lhaIDs.second, pw.wids.size(), pw.wids.front().c_str());
536  }
537 
538  // ------ LHE REWEIGHTING -------
539  if (lheDebug) {
540  std::cout << "Found " << lheReweighingIDs.size() << " reweighting weights" << std::endl;
541  }
542  std::copy(lheReweighingIDs.begin(), lheReweighingIDs.end(), std::back_inserter(weightChoice->rwgtIDs));
543 
544  std::stringstream pdfDoc; pdfDoc << "LHE pdf variation weights (w_var / w_nominal) for LHA IDs ";
545  bool found = false;
546  for (uint32_t lhaid : preferredPDFLHAIDs_) {
547  for (const auto & pw : pdfSetWeightIDs) {
548  if (pw.lhaIDs.first != lhaid && pw.lhaIDs.first != (lhaid+1)) continue; // sometimes the first weight is not saved if that PDF is the nominal one for the sample
549  if (pw.wids.size() == 1) continue; // only consider error sets
550  pdfDoc << pw.lhaIDs.first << " - " << pw.lhaIDs.second;
551  weightChoice->pdfWeightIDs = pw.wids;
552  if (maxPdfWeights_ < pw.wids.size()) {
553  weightChoice->pdfWeightIDs.resize(maxPdfWeights_); // drop some replicas
554  pdfDoc << ", truncated to the first " << maxPdfWeights_ << " replicas";
555  }
556  weightChoice->pdfWeightsDoc = pdfDoc.str();
557  found = true; break;
558  }
559  if (found) break;
560  }
561  }
562  }
563  return weightChoice;
564  }
565 
566 
567  // create an empty counter
568  std::unique_ptr<Counter> beginStream(edm::StreamID) const override {
569  return std::make_unique<Counter>();
570  }
571  // inizialize to zero at begin run
572  void streamBeginRun(edm::StreamID id, edm::Run const&, edm::EventSetup const&) const override {
573  streamCache(id)->clear();
574  }
575  // create an empty counter
576  std::shared_ptr<Counter> globalBeginRunSummary(edm::Run const&, edm::EventSetup const&) const override {
577  return std::make_shared<Counter>();
578  }
579  // add this stream to the summary
580  void streamEndRunSummary(edm::StreamID id, edm::Run const&, edm::EventSetup const&, Counter* runCounter) const override {
581  runCounter->merge(*streamCache(id));
582  }
583  // nothing to do per se
584  void globalEndRunSummary(edm::Run const&, edm::EventSetup const&, Counter* runCounter) const override {
585  }
586  // write the total to the run
587  void globalEndRunProduce(edm::Run& iRun, edm::EventSetup const&, Counter const* runCounter) const override {
588  auto out = std::make_unique<nanoaod::MergeableCounterTable>();
589  out->addInt("genEventCount", "event count", runCounter->num);
590  out->addFloat("genEventSumw", "sum of gen weights", runCounter->sumw);
591  out->addFloat("genEventSumw2", "sum of gen (weight^2)", runCounter->sumw2);
592 
593  double norm = runCounter->sumw ? 1.0/runCounter->sumw : 1;
594  auto sumScales = runCounter->sumScale; for (auto & val : sumScales) val *= norm;
595  out->addVFloat("LHEScaleSumw", "Sum of genEventWeight * LHEScaleWeight[i], divided by genEventSumw", sumScales);
596  auto sumPDFs = runCounter->sumPDF; for (auto & val : sumPDFs) val *= norm;
597  out->addVFloat("LHEPdfSumw", "Sum of genEventWeight * LHEPdfWeight[i], divided by genEventSumw", sumPDFs);
598  if (!runCounter->sumRwgt.empty()) {
599  auto sumRwgts = runCounter->sumRwgt; for (auto & val : sumRwgts) val *= norm;
600  out->addVFloat("LHEReweightingSumw", "Sum of genEventWeight * LHEReweightingWeight[i], divided by genEventSumw", sumRwgts);
601  }
602  if (!runCounter->sumNamed.empty()) { // it could be empty if there's no LHE info in the sample
603  for (unsigned int i = 0, n = namedWeightLabels_.size(); i < n; ++i) {
604  out->addFloat("LHESumw_"+namedWeightLabels_[i], "Sum of genEventWeight * LHEWeight_"+namedWeightLabels_[i]+", divided by genEventSumw", runCounter->sumNamed[i] * norm);
605  }
606  }
607  iRun.put(std::move(out));
608  }
609  // nothing to do here
610  void globalEndRun(edm::Run const&, edm::EventSetup const&) const override { }
611 
612  static void fillDescriptions(edm::ConfigurationDescriptions & descriptions) {
614  desc.add<edm::InputTag>("genEvent", edm::InputTag("generator"))->setComment("tag for the GenEventInfoProduct, to get the main weight");
615  desc.add<std::vector<edm::InputTag>>("lheInfo", std::vector<edm::InputTag>{{"externalLHEProducer"},{"source"}})->setComment("tag(s) for the LHE information (LHEEventProduct and LHERunInfoProduct)");
616 
618  prefpdf.add<std::string>("name");
619  prefpdf.add<uint32_t>("lhaid");
620  desc.addVPSet("preferredPDFs", prefpdf, std::vector<edm::ParameterSet>())->setComment("LHA PDF Ids of the preferred PDF sets, in order of preference (the first matching one will be used)");
621  desc.add<std::vector<std::string>>("namedWeightIDs")->setComment("set of LHA weight IDs for named LHE weights");
622  desc.add<std::vector<std::string>>("namedWeightLabels")->setComment("output names for the namedWeightIDs (in the same order)");
623  desc.add<int32_t>("lheWeightPrecision")->setComment("Number of bits in the mantissa for LHE weights");
624  desc.add<uint32_t>("maxPdfWeights")->setComment("Maximum number of PDF weights to save (to crop NN replicas)");
625  desc.addOptionalUntracked<bool>("debug")->setComment("dump out all LHE information for one event");
626  descriptions.add("genWeightsTable", desc);
627  }
628 
629 
630  protected:
632  const std::vector<edm::InputTag> lheLabel_;
633  const std::vector<edm::EDGetTokenT<LHEEventProduct>> lheTag_;
634  const std::vector<edm::EDGetTokenT<LHERunInfoProduct>> lheRunTag_;
635 
636  std::vector<uint32_t> preferredPDFLHAIDs_;
637  std::unordered_map<std::string,uint32_t> lhaNameToID_;
638  std::vector<std::string> namedWeightIDs_;
639  std::vector<std::string> namedWeightLabels_;
641  unsigned int maxPdfWeights_;
642 
643  mutable std::atomic<bool> debug_, debugRun_, hasIssuedWarning_;
644 };
645 
648 
const std::vector< edm::EDGetTokenT< LHERunInfoProduct > > lheRunTag_
double originalXWGTUP() const
T getParameter(std::string const &) const
bool getByLabel(std::string const &label, Handle< PROD > &result) const
Definition: Run.h:280
void setComment(std::string const &value)
void streamBeginRun(edm::StreamID id, edm::Run const &, edm::EventSetup const &) const override
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:125
ParameterDescriptionBase * addVPSet(U const &iLabel, ParameterSetDescription const &validator, std::vector< ParameterSet > const &defaults)
std::unordered_map< std::string, uint32_t > lhaNameToID_
const double w
Definition: UKUtility.cc:23
def copy(args, dbName)
void globalEndRun(edm::Run const &, edm::EventSetup const &) const override
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:517
void globalEndRunProduce(edm::Run &iRun, edm::EventSetup const &, Counter const *runCounter) const override
void streamEndRunSummary(edm::StreamID id, edm::Run const &, edm::EventSetup const &, Counter *runCounter) const override
const edm::EDGetTokenT< GenEventInfoProduct > genTag_
std::shared_ptr< DynamicWeightChoice > globalBeginRun(edm::Run const &iRun, edm::EventSetup const &) const override
Definition: weight.py:1
headers_const_iterator headers_end() const
Run const & getRun() const
Definition: Event.cc:99
double weight() const
std::atomic< bool > hasIssuedWarning_
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:20
uint16_t size_type
void fillLHEWeightTables(Counter *counter, const DynamicWeightChoice *weightChoice, double genWeight, const LHEEventProduct &lheProd, const GenEventInfoProduct &genProd, std::unique_ptr< nanoaod::FlatTable > &outScale, std::unique_ptr< nanoaod::FlatTable > &outPdf, std::unique_ptr< nanoaod::FlatTable > &outRwgt, std::unique_ptr< nanoaod::FlatTable > &outNamed, std::unique_ptr< nanoaod::FlatTable > &outPS) const
const std::vector< edm::InputTag > lheLabel_
std::unique_ptr< Counter > beginStream(edm::StreamID) const override
const std::vector< WGT > & weights() const
char const * label
std::function< unsigned int(align::ID)> Counter
int iEvent
Definition: GenABIO.cc:224
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
headers_const_iterator headers_begin() const
void clear(CLHEP::HepGenMatrix &m)
Helper function: Reset all elements of a matrix to 0.
Definition: matutil.cc:167
RunIndex index() const
Definition: Run.cc:21
double f[11][100]
#define end
Definition: vmac.h:39
void fillOnlyPSWeightTable(Counter *counter, double genWeight, const GenEventInfoProduct &genProd, std::unique_ptr< nanoaod::FlatTable > &outPS) const
ParameterDescriptionBase * add(U const &iLabel, T const &value)
bool isValid() const
Definition: HandleBase.h:74
void add(std::map< std::string, TH1 * > &h, TH1 *hist)
auto vector_transform(std::vector< InputType > const &input, Function predicate) -> std::vector< typename std::remove_cv< typename std::remove_reference< decltype(predicate(input.front()))>::type >::type >
Definition: transform.h:11
std::vector< std::string > namedWeightLabels_
GenWeightsTableProducer(edm::ParameterSet const &params)
std::shared_ptr< Counter > globalBeginRunSummary(edm::Run const &, edm::EventSetup const &) const override
void put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Run.h:108
void add(std::string const &label, ParameterSetDescription const &psetDescription)
const std::vector< edm::EDGetTokenT< LHEEventProduct > > lheTag_
bool operator<(DTCELinkId const &lhs, DTCELinkId const &rhs)
Definition: DTCELinkId.h:73
std::vector< uint32_t > preferredPDFLHAIDs_
HLT enums.
std::vector< double > & weights()
void produce(edm::StreamID id, edm::Event &iEvent, const edm::EventSetup &iSetup) const override
ParameterDescriptionBase * addOptionalUntracked(U const &iLabel, T const &value)
std::pair< typename Association::data_type::first_type, double > match(Reference key, Association association, bool bestMatchByMaxValue)
Generic matching function.
Definition: Utils.h:10
std::vector< std::string > namedWeightIDs_
#define str(s)
void globalEndRunSummary(edm::Run const &, edm::EventSetup const &, Counter *runCounter) const override
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:40
def move(src, dest)
Definition: eostools.py:511
Definition: Run.h:45
def merge(dictlist, TELL=False)
Definition: MatrixUtil.py:194