CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
NanoAODOutputModule.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: PhysicsTools/NanoAODOutput
4 // Class : NanoAODOutputModule
5 //
6 // Implementation:
7 // [Notes on implementation]
8 //
9 // Original Author: Christopher Jones
10 // Created: Mon, 07 Aug 2017 14:21:41 GMT
11 //
12 
13 // system include files
14 #include <algorithm>
15 #include <memory>
16 
17 #include "Compression.h"
18 #include "TFile.h"
19 #include "TObjString.h"
20 #include "TROOT.h"
21 #include "TTree.h"
22 #include <string>
23 
24 // user include files
46 
47 #include <iostream>
48 
49 #include "oneapi/tbb/task_arena.h"
50 
52 public:
54  ~NanoAODOutputModule() override;
55 
56  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
57 
58 private:
59  void write(edm::EventForOutput const& e) override;
61  void writeRun(edm::RunForOutput const&) override;
62  bool isFileOpen() const override;
63  void openFile(edm::FileBlock const&) override;
64  void reallyCloseFile() override;
65 
72  bool m_fakeName; //crab workaround, remove after crab is fixed
76  std::unique_ptr<TFile> m_file;
78 
79  static constexpr int m_firstFlush{1000};
80 
82  public:
83  void branch(TTree& tree) {
84  tree.Branch("run", &m_run, "run/i");
85  tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i");
86  tree.Branch("event", &m_event, "event/l");
87  }
88  void fill(const edm::EventID& id) {
89  m_run = id.run();
90  m_luminosityBlock = id.luminosityBlock();
91  m_event = id.event();
92  }
93 
94  private:
95  UInt_t m_run;
97  ULong64_t m_event;
99 
101  public:
102  void branch(TTree& tree) {
103  tree.Branch("run", &m_run, "run/i");
104  tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i");
105  }
106  void fill(const edm::LuminosityBlockID& id) {
107  m_run = id.run();
108  m_luminosityBlock = id.value();
109  }
110 
111  private:
112  UInt_t m_run;
115 
117  public:
118  void branch(TTree& tree) { tree.Branch("run", &m_run, "run/i"); }
119  void fill(const edm::RunID& id) { m_run = id.run(); }
120 
121  private:
122  UInt_t m_run;
124 
125  std::vector<TableOutputBranches> m_tables;
126  std::vector<TriggerOutputBranches> m_triggers;
127  bool m_triggers_areSorted = false;
128  std::vector<EventStringOutputBranches> m_evstrings;
129 
130  std::vector<SummaryTableOutputBranches> m_runTables;
131  std::vector<SummaryTableOutputBranches> m_lumiTables;
132  std::vector<LumiOutputBranches> m_lumiTables2;
133  std::vector<TableOutputBranches> m_runFlatTables;
134 
135  std::vector<std::pair<std::string, edm::EDGetToken>> m_nanoMetadata;
136 };
137 
138 //
139 // constants, enums and typedefs
140 //
141 
142 //
143 // static data member definitions
144 //
145 
146 //
147 // constructors and destructor
148 //
150  : edm::one::OutputModuleBase::OutputModuleBase(pset),
151  edm::one::OutputModule<>(pset),
152  m_fileName(pset.getUntrackedParameter<std::string>("fileName")),
153  m_logicalFileName(pset.getUntrackedParameter<std::string>("logicalFileName")),
154  m_compressionLevel(pset.getUntrackedParameter<int>("compressionLevel")),
155  m_compressionAlgorithm(pset.getUntrackedParameter<std::string>("compressionAlgorithm")),
156  m_writeProvenance(pset.getUntrackedParameter<bool>("saveProvenance", true)),
157  m_fakeName(pset.getUntrackedParameter<bool>("fakeNameForCrab", false)),
158  m_autoFlush(pset.getUntrackedParameter<int>("autoFlush", -10000000)),
159  m_processHistoryRegistry() {}
160 
162 
164  //Get data from 'e' and write it to the file
166  jr->eventWrittenToFile(m_jrToken, iEvent.id().run(), iEvent.id().event());
167 
168  if (m_autoFlush) {
169  int64_t events = m_tree->GetEntriesFast();
170  if (events == m_firstFlush) {
171  m_tree->FlushBaskets();
172  float maxMemory;
173  if (m_autoFlush > 0) {
174  // Estimate the memory we'll be using at the first full flush by
175  // linearly scaling the number of events.
176  float percentClusterDone = m_firstFlush / static_cast<float>(m_autoFlush);
177  maxMemory = static_cast<float>(m_tree->GetTotBytes()) / percentClusterDone;
178  } else if (m_tree->GetZipBytes() == 0) {
179  maxMemory = 100 * 1024 * 1024; // Degenerate case of no information in the tree; arbitrary value
180  } else {
181  // Estimate the memory we'll be using by scaling the current compression ratio.
182  float cxnRatio = m_tree->GetTotBytes() / static_cast<float>(m_tree->GetZipBytes());
183  maxMemory = -m_autoFlush * cxnRatio;
184  float percentBytesDone = -m_tree->GetZipBytes() / static_cast<float>(m_autoFlush);
185  m_autoFlush = m_firstFlush / percentBytesDone;
186  }
187  //std::cout << "OptimizeBaskets: total bytes " << m_tree->GetTotBytes() << std::endl;
188  //std::cout << "OptimizeBaskets: zip bytes " << m_tree->GetZipBytes() << std::endl;
189  //std::cout << "OptimizeBaskets: autoFlush " << m_autoFlush << std::endl;
190  //std::cout << "OptimizeBaskets: maxMemory " << static_cast<uint32_t>(maxMemory) << std::endl;
191  //m_tree->OptimizeBaskets(static_cast<uint32_t>(maxMemory), 1, "d");
192  m_tree->OptimizeBaskets(static_cast<uint32_t>(maxMemory), 1, "");
193  }
195  m_tree->FlushBaskets();
196  m_eventsSinceFlush = 0;
197  }
199  }
200 
201  m_commonBranches.fill(iEvent.id());
202  // fill all tables, starting from main tables and then doing extension tables
203  for (unsigned int extensions = 0; extensions <= 1; ++extensions) {
204  for (auto& t : m_tables)
205  t.fill(iEvent, *m_tree, extensions);
206  }
207  if (!m_triggers_areSorted) { // sort triggers/flags in inverse processHistory order, to save without any special label the most recent ones
208  std::vector<std::string> pnames;
209  for (auto& p : iEvent.processHistory())
210  pnames.push_back(p.processName());
211  std::sort(m_triggers.begin(), m_triggers.end(), [pnames](TriggerOutputBranches& a, TriggerOutputBranches& b) {
212  return ((std::find(pnames.begin(), pnames.end(), a.processName()) - pnames.begin()) >
213  (std::find(pnames.begin(), pnames.end(), b.processName()) - pnames.begin()));
214  });
215  m_triggers_areSorted = true;
216  }
217  // fill triggers
218  for (auto& t : m_triggers)
219  t.fill(iEvent, *m_tree);
220  // fill event branches
221  for (auto& t : m_evstrings)
222  t.fill(iEvent, *m_tree);
223  tbb::this_task_arena::isolate([&] { m_tree->Fill(); });
224 
226 }
227 
230  jr->reportLumiSection(m_jrToken, iLumi.id().run(), iLumi.id().value());
231 
232  m_commonLumiBranches.fill(iLumi.id());
233 
234  for (auto& t : m_lumiTables)
235  t.fill(iLumi, *m_lumiTree);
236 
237  for (unsigned int extensions = 0; extensions <= 1; ++extensions) {
238  for (auto& t : m_lumiTables2)
239  t.fill(iLumi, *m_lumiTree, extensions);
240  }
241 
242  tbb::this_task_arena::isolate([&] { m_lumiTree->Fill(); });
243 
245 }
246 
249  jr->reportRunNumber(m_jrToken, iRun.id().run());
250 
251  m_commonRunBranches.fill(iRun.id());
252 
253  for (auto& t : m_runTables)
254  t.fill(iRun, *m_runTree);
255 
256  for (unsigned int extensions = 0; extensions <= 1; ++extensions) {
257  for (auto& t : m_runFlatTables)
258  t.fill(iRun, *m_runTree, extensions);
259  }
260 
262  for (const auto& p : m_nanoMetadata) {
263  iRun.getByToken(p.second, hstring);
264  TObjString* tos = dynamic_cast<TObjString*>(m_file->Get(p.first.c_str()));
265  if (tos) {
266  if (hstring->str() != tos->GetString())
267  throw cms::Exception("LogicError", "Inconsistent nanoMetadata " + p.first + " (" + hstring->str() + ")");
268  } else {
269  auto ostr = std::make_unique<TObjString>(hstring->str().c_str());
270  m_file->WriteTObject(ostr.release(), p.first.c_str());
271  }
272  }
273 
274  tbb::this_task_arena::isolate([&] { m_runTree->Fill(); });
275 
277 }
278 
279 bool NanoAODOutputModule::isFileOpen() const { return nullptr != m_file.get(); }
280 
282  m_file = std::make_unique<TFile>(m_fileName.c_str(), "RECREATE", "", m_compressionLevel);
284  cms::Digest branchHash;
285  m_jrToken = jr->outputFileOpened(m_fileName,
287  std::string(),
288  m_fakeName ? "PoolOutputModule" : "NanoAODOutputModule",
289  description().moduleLabel(),
291  std::string(),
292  branchHash.digest().toString(),
293  std::vector<std::string>());
294 
295  if (m_compressionAlgorithm == std::string("ZLIB")) {
296  m_file->SetCompressionAlgorithm(ROOT::kZLIB);
297  } else if (m_compressionAlgorithm == std::string("LZMA")) {
298  m_file->SetCompressionAlgorithm(ROOT::kLZMA);
299  } else {
300  throw cms::Exception("Configuration")
301  << "NanoAODOutputModule configured with unknown compression algorithm '" << m_compressionAlgorithm << "'\n"
302  << "Allowed compression algorithms are ZLIB and LZMA\n";
303  }
304  /* Setup file structure here */
305  m_tables.clear();
306  m_triggers.clear();
307  m_triggers_areSorted = false;
308  m_evstrings.clear();
309  m_runTables.clear();
310  m_lumiTables.clear();
311  m_lumiTables2.clear();
312  m_runFlatTables.clear();
313  const auto& keeps = keptProducts();
314  for (const auto& keep : keeps[edm::InEvent]) {
315  if (keep.first->className() == "nanoaod::FlatTable")
316  m_tables.emplace_back(keep.first, keep.second);
317  else if (keep.first->className() == "edm::TriggerResults") {
318  m_triggers.emplace_back(keep.first, keep.second);
319  } else if (keep.first->className() == "std::basic_string<char,std::char_traits<char> >" &&
320  keep.first->productInstanceName() == "genModel") { // friendlyClassName == "String"
321  m_evstrings.emplace_back(keep.first, keep.second, true); // update only at lumiBlock transitions
322  } else
323  throw cms::Exception("Configuration", "NanoAODOutputModule cannot handle class " + keep.first->className());
324  }
325 
326  for (const auto& keep : keeps[edm::InLumi]) {
327  if (keep.first->className() == "nanoaod::MergeableCounterTable")
328  m_lumiTables.push_back(SummaryTableOutputBranches(keep.first, keep.second));
329  else if (keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata")
330  m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second);
331  else if (keep.first->className() == "nanoaod::FlatTable")
332  m_lumiTables2.push_back(LumiOutputBranches(keep.first, keep.second));
333  else
334  throw cms::Exception(
335  "Configuration",
336  "NanoAODOutputModule cannot handle class " + keep.first->className() + " in LuminosityBlock branch");
337  }
338 
339  for (const auto& keep : keeps[edm::InRun]) {
340  if (keep.first->className() == "nanoaod::MergeableCounterTable")
341  m_runTables.push_back(SummaryTableOutputBranches(keep.first, keep.second));
342  else if (keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata")
343  m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second);
344  else if (keep.first->className() == "nanoaod::FlatTable")
345  m_runFlatTables.emplace_back(keep.first, keep.second);
346  else
347  throw cms::Exception("Configuration",
348  "NanoAODOutputModule cannot handle class " + keep.first->className() + " in Run branch");
349  }
350 
351  // create the trees
352  m_tree = std::make_unique<TTree>("Events", "Events");
353  m_tree->SetAutoSave(0);
354  m_tree->SetAutoFlush(0);
356 
357  m_lumiTree = std::make_unique<TTree>("LuminosityBlocks", "LuminosityBlocks");
358  m_lumiTree->SetAutoSave(0);
360 
361  m_runTree = std::make_unique<TTree>("Runs", "Runs");
362  m_runTree->SetAutoSave(0);
364 
365  if (m_writeProvenance) {
366  m_metaDataTree = std::make_unique<TTree>(edm::poolNames::metaDataTreeName().c_str(), "Job metadata");
367  m_metaDataTree->SetAutoSave(0);
368  m_parameterSetsTree = std::make_unique<TTree>(edm::poolNames::parameterSetsTreeName().c_str(), "Parameter sets");
369  m_parameterSetsTree->SetAutoSave(0);
370  }
371 }
373  if (m_writeProvenance) {
374  int basketSize = 16384; // fixme configurable?
377  if (m_metaDataTree->GetNbranches() != 0) {
378  m_metaDataTree->SetEntries(-1);
379  }
380  if (m_parameterSetsTree->GetNbranches() != 0) {
381  m_parameterSetsTree->SetEntries(-1);
382  }
383  }
384  m_file->Write();
385  m_file->Close();
386  m_file.reset();
387  m_tree.release(); // apparently root has ownership
388  m_lumiTree.release(); //
389  m_runTree.release(); //
390  m_metaDataTree.release(); //
391  m_parameterSetsTree.release(); //
394 }
395 
398 
399  desc.addUntracked<std::string>("fileName");
400  desc.addUntracked<std::string>("logicalFileName", "");
401 
402  desc.addUntracked<int>("compressionLevel", 9)->setComment("ROOT compression level of output file.");
403  desc.addUntracked<std::string>("compressionAlgorithm", "ZLIB")
404  ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA");
405  desc.addUntracked<bool>("saveProvenance", true)
406  ->setComment("Save process provenance information, e.g. for edmProvDump");
407  desc.addUntracked<bool>("fakeNameForCrab", false)
408  ->setComment(
409  "Change the OutputModule name in the fwk job report to fake PoolOutputModule. This is needed to run on cran "
410  "(and publish) till crab is fixed");
411  desc.addUntracked<int>("autoFlush", -10000000)->setComment("Autoflush parameter for ROOT file");
412 
413  //replace with whatever you want to get from the EDM by default
414  const std::vector<std::string> keep = {"drop *",
415  "keep nanoaodFlatTable_*Table_*_*",
416  "keep edmTriggerResults_*_*_*",
417  "keep String_*_genModel_*",
418  "keep nanoaodMergeableCounterTable_*Table_*_*",
419  "keep nanoaodUniqueString_nanoMetadata_*_*"};
421 
422  //Used by Workflow management for their own meta data
424  dataSet.setAllowAnything();
425  desc.addUntracked<edm::ParameterSetDescription>("dataset", dataSet)
426  ->setComment("PSet is only used by Data Operations and not by this module.");
427 
429  branchSet.setAllowAnything();
430  desc.add<edm::ParameterSetDescription>("branches", branchSet);
431 
432  descriptions.addDefault(desc);
433 }
434 
RunNumber_t run() const
Definition: EventID.h:38
std::unique_ptr< TTree > m_runTree
EventNumber_t event() const
Definition: EventID.h:40
std::vector< TableOutputBranches > m_runFlatTables
std::unique_ptr< TTree > m_lumiTree
EventID const & id() const
std::vector< SummaryTableOutputBranches > m_lumiTables
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
RunNumber_t run() const
Definition: RunID.h:36
std::unique_ptr< TTree > m_tree
void setAllowAnything()
allow any parameter label/value pairs
RunID const & id() const
Definition: RunForOutput.h:55
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void fillParameterSetBranch(TTree *parameterSetsTree, int basketSize)
bool registerProcessHistory(ProcessHistory const &processHistory)
void fillProcessHistoryBranch(TTree *metaDataTree, int basketSize, ProcessHistoryRegistry const &processHistoryRegistry)
NanoAODOutputModule(edm::ParameterSet const &pset)
bool isFileOpen() const override
void fill(const edm::LuminosityBlockID &id)
void reportRunNumber(JobReport::Token token, unsigned int run)
Definition: JobReport.cc:470
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
std::string const & parameterSetsTreeName()
Definition: BranchType.cc:216
std::unique_ptr< TTree > m_parameterSetsTree
void writeRun(edm::RunForOutput const &) override
class NanoAODOutputModule::CommonLumiBranches m_commonLumiBranches
std::unique_ptr< TTree > m_metaDataTree
const int keep
std::unique_ptr< TFile > m_file
int iEvent
Definition: GenABIO.cc:224
void addDefault(ParameterSetDescription const &psetDescription)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
virtual ProcessHistory const & processHistory() const
MD5Result digest()
Definition: Digest.cc:171
std::vector< EventStringOutputBranches > m_evstrings
ModuleDescription const & description() const
std::vector< SummaryTableOutputBranches > m_runTables
std::vector< TableOutputBranches > m_tables
static constexpr int m_firstFlush
std::vector< TriggerOutputBranches > m_triggers
RunNumber_t run() const
uint64_t value() const
std::vector< std::pair< std::string, edm::EDGetToken > > m_nanoMetadata
std::string const & metaDataTreeName()
Definition: BranchType.cc:159
ParameterDescriptionBase * add(U const &iLabel, T const &value)
std::vector< LumiOutputBranches > m_lumiTables2
std::size_t Token
Definition: JobReport.h:106
void openFile(edm::FileBlock const &) override
std::string createGlobalIdentifier(bool binary=false)
void reallyCloseFile() override
void eventWrittenToFile(Token fileToken, RunNumber_t run, EventNumber_t event)
Definition: JobReport.cc:429
std::string toString() const
Definition: Digest.cc:95
double b
Definition: hdecay.h:118
BasicHandle getByToken(EDGetToken token, TypeID const &typeID) const
tuple events
Definition: patZpeak.py:20
double a
Definition: hdecay.h:119
void outputFileClosed(Token fileToken)
Definition: JobReport.cc:434
void write(edm::EventForOutput const &e) override
class NanoAODOutputModule::CommonRunBranches m_commonRunBranches
SelectedProductsForBranchType const & keptProducts() const
edm::JobReport::Token m_jrToken
class NanoAODOutputModule::CommonEventBranches m_commonBranches
edm::ProcessHistoryRegistry m_processHistoryRegistry
LuminosityBlockID const & id() const
static void fillDescription(ParameterSetDescription &desc, std::vector< std::string > const &iDefaultOutputCommands=ProductSelectorRules::defaultSelectionStrings())
std::string m_compressionAlgorithm
void reportLumiSection(JobReport::Token token, unsigned int run, unsigned int lumiSectId, unsigned long nEvents=0)
Definition: JobReport.cc:459
void writeLuminosityBlock(edm::LuminosityBlockForOutput const &) override