CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
EventContentAnalyzer.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: Modules
4 // Class: EventContentAnalyzer
5 //
12 //
13 // Original Author: Chris Jones
14 // Created: Mon Sep 19 11:47:28 CEST 2005
15 //
16 //
17 
18 // user include files
36 
37 // system include files
38 #include <algorithm>
39 #include <iomanip>
40 #include <iostream>
41 #include <map>
42 #include <sstream>
43 #include <string>
44 #include <vector>
45 
46 namespace edm {
48  namespace {
49  std::string formatClassName(std::string const& iName) { return std::string("(") + iName + ")"; }
50 
51  char const* kNameValueSep = "=";
53  template <typename T>
54  void doPrint(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
55  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
56  << *reinterpret_cast<T*>(iObject.address()); // << "\n";
57  }
58 
59  template <>
60  void doPrint<char>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
61  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
62  << static_cast<int>(*reinterpret_cast<char*>(iObject.address())); // << "\n";
63  }
64 
65  template <>
66  void doPrint<unsigned char>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
67  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
68  << static_cast<unsigned int>(
69  *reinterpret_cast<unsigned char*>(iObject.address())); // << "\n";
70  }
71 
72  template <>
73  void doPrint<bool>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
74  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
75  << ((*reinterpret_cast<bool*>(iObject.address())) ? "true" : "false"); // << "\n";
76  }
77 
78  typedef void (*FunctionType)(std::string const&, ObjectWithDict const&, std::string const&);
79  typedef std::map<std::string, FunctionType> TypeToPrintMap;
80 
81  template <typename T>
82  void addToMap(TypeToPrintMap& iMap) {
83  iMap[typeid(T).name()] = doPrint<T>;
84  }
85 
86  bool printAsBuiltin(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
87  typedef void (*FunctionType)(std::string const&, ObjectWithDict const&, std::string const&);
88  typedef std::map<std::string, FunctionType> TypeToPrintMap;
89  static TypeToPrintMap s_map;
90  static bool isFirst = true;
91  if (isFirst) {
92  addToMap<bool>(s_map);
93  addToMap<char>(s_map);
94  addToMap<short>(s_map);
95  addToMap<int>(s_map);
96  addToMap<long>(s_map);
97  addToMap<unsigned char>(s_map);
98  addToMap<unsigned short>(s_map);
99  addToMap<unsigned int>(s_map);
100  addToMap<unsigned long>(s_map);
101  addToMap<float>(s_map);
102  addToMap<double>(s_map);
103  isFirst = false;
104  }
105  TypeToPrintMap::iterator itFound = s_map.find(iObject.typeOf().name());
106  if (itFound == s_map.end()) {
107  return false;
108  }
109  itFound->second(iName, iObject, iIndent);
110  return true;
111  }
112 
113  bool printAsContainer(std::string const& iName,
114  ObjectWithDict const& iObject,
115  std::string const& iIndent,
116  std::string const& iIndentDelta);
117 
118  void printObject(std::string const& iName,
119  ObjectWithDict const& iObject,
120  std::string const& iIndent,
121  std::string const& iIndentDelta) {
122  const std::string& printName = iName;
123  const ObjectWithDict& objectToPrint = iObject;
124  std::string indent(iIndent);
125  if (iObject.typeOf().isPointer()) {
126  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep << formatClassName(iObject.typeOf().name())
127  << std::hex << iObject.address() << std::dec; // << "\n";
128  TypeWithDict pointedType = iObject.typeOf().toType(); // for Pointers, I get the real type this way
129  if (TypeWithDict::byName("void") == pointedType || pointedType.isPointer() || iObject.address() == nullptr) {
130  return;
131  }
132  return;
133  /*
134  //have the code that follows print the contents of the data to which the pointer points
135  objectToPrint = ObjectWithDict(pointedType, iObject.address());
136  //try to convert it to its actual type (assuming the original type was a base class)
137  objectToPrint = ObjectWithDict(objectToPrint.castObject(objectToPrint.dynamicType()));
138  printName = std::string("*")+iName;
139  indent += iIndentDelta;
140  */
141  }
142  std::string typeName(objectToPrint.typeOf().name());
143  if (typeName.empty()) {
144  typeName = "<unknown>";
145  }
146 
147  if (printAsBuiltin(printName, objectToPrint, indent)) {
148  return;
149  }
150  if (printAsContainer(printName, objectToPrint, indent, iIndentDelta)) {
151  return;
152  }
153 
154  LogAbsolute("EventContent") << indent << printName << " " << formatClassName(typeName); // << "\n";
155  indent += iIndentDelta;
156  //print all the data members
157  TypeDataMembers dataMembers(objectToPrint.typeOf());
158  for (auto const& dataMember : dataMembers) {
159  MemberWithDict const member(dataMember);
160  //LogAbsolute("EventContent") << " debug " << member.name() << " " << member.typeName() << "\n";
161  try {
162  printObject(member.name(), member.get(objectToPrint), indent, iIndentDelta);
163  } catch (std::exception& iEx) {
164  LogAbsolute("EventContent") << indent << member.name() << " <exception caught(" << iEx.what() << ")>\n";
165  }
166  }
167  }
168 
169  bool printAsContainer(std::string const& iName,
170  ObjectWithDict const& iObject,
171  std::string const& iIndent,
172  std::string const& iIndentDelta) {
173  ObjectWithDict sizeObj;
174  try {
175  size_t temp; //used to hold the memory for the return value
176  FunctionWithDict sizeFunc = iObject.typeOf().functionMemberByName("size");
177  assert(sizeFunc.finalReturnType() == typeid(size_t));
178  sizeObj = ObjectWithDict(TypeWithDict(typeid(size_t)), &temp);
179  sizeFunc.invoke(iObject, &sizeObj);
180  //std::cout << "size of type '" << sizeObj.name() << "' " << sizeObj.typeName() << std::endl;
181  size_t size = *reinterpret_cast<size_t*>(sizeObj.address());
182  FunctionWithDict atMember;
183  try {
184  atMember = iObject.typeOf().functionMemberByName("at");
185  } catch (std::exception const& x) {
186  //std::cerr << "could not get 'at' member because " << x.what() << std::endl;
187  return false;
188  }
189  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep << "[size=" << size << "]"; //"\n";
190  ObjectWithDict contained;
191  std::string indexIndent = iIndent + iIndentDelta;
192  TypeWithDict atReturnType(atMember.finalReturnType());
193  //std::cout << "return type " << atReturnType.name() << " size of " << atReturnType.SizeOf()
194  // << " pointer? " << atReturnType.isPointer() << " ref? " << atReturnType.isReference() << std::endl;
195 
196  //Return by reference must be treated differently since reflex will not properly create
197  // memory for a ref (which should just be a pointer to the object and not the object itself)
198  //So we will create memory on the stack which can be used to hold a reference
199  bool const isRef = atReturnType.isReference();
200  void* refMemoryBuffer = nullptr;
201  size_t index = 0;
202  //The argument to the 'at' function is the index. Since the argument list holds pointers to the arguments
203  // we only need to create it once and then when the value of index changes the pointer already
204  // gets the new value
205  std::vector<void*> args;
206  args.push_back(&index);
207  for (; index != size; ++index) {
208  std::ostringstream sizeS;
209  sizeS << "[" << index << "]";
210  if (isRef) {
211  ObjectWithDict refObject(atReturnType, &refMemoryBuffer);
212  atMember.invoke(iObject, &refObject, args);
213  //Although to hold the return value from a reference reflex requires you to pass it a
214  // void** when it tries to call methods on the reference it expects to be given a void*
215  contained = ObjectWithDict(atReturnType, refMemoryBuffer);
216  } else {
217  contained = atReturnType.construct();
218  atMember.invoke(iObject, &contained, args);
219  }
220  //LogAbsolute("EventContent") << "invoked 'at'" << std::endl;
221  try {
222  printObject(sizeS.str(), contained, indexIndent, iIndentDelta);
223  } catch (std::exception& iEx) {
224  LogAbsolute("EventContent") << indexIndent << iName << " <exception caught(" << iEx.what() << ")>\n";
225  }
226  if (!isRef) {
227  contained.destruct(true);
228  }
229  }
230  return true;
231  } catch (std::exception const& x) {
232  //std::cerr << "failed to invoke 'at' because " << x.what() << std::endl;
233  return false;
234  }
235  return false;
236  }
237 
238  void printObject(Event const& iEvent,
239  std::string const& iClassName,
240  std::string const& iModuleLabel,
241  std::string const& iInstanceLabel,
242  std::string const& iProcessName,
243  std::string const& iIndent,
244  std::string const& iIndentDelta) {
245  try {
246  GenericHandle handle(iClassName);
247  } catch (edm::Exception const&) {
248  LogAbsolute("EventContent") << iIndent << " \"" << iClassName << "\""
249  << " is an unknown type" << std::endl;
250  return;
251  }
252  GenericHandle handle(iClassName);
253  iEvent.getByLabel(InputTag(iModuleLabel, iInstanceLabel, iProcessName), handle);
254  std::string className = formatClassName(iClassName);
255  printObject(className, *handle, iIndent, iIndentDelta);
256  }
257  } // namespace
258 
260  public:
261  explicit EventContentAnalyzer(ParameterSet const&);
262  ~EventContentAnalyzer() override;
263 
264  void analyze(Event const&, EventSetup const&) override;
265  void endJob() override;
266 
267  static void fillDescriptions(ConfigurationDescriptions& descriptions);
268 
269  private:
270  // ----------member data ---------------------------
271  std::string indentation_;
272  std::string verboseIndentation_;
273  std::vector<std::string> moduleLabels_;
274  bool verbose_;
275  std::vector<std::string> getModuleLabels_;
276  bool getData_;
277  int evno_;
278  std::map<std::string, int> cumulates_;
281  };
282 
283  //
284  // constructors and destructor
285  //
287  : indentation_(iConfig.getUntrackedParameter("indentation", std::string("++"))),
288  verboseIndentation_(iConfig.getUntrackedParameter("verboseIndentation", std::string(" "))),
289  moduleLabels_(iConfig.getUntrackedParameter("verboseForModuleLabels", std::vector<std::string>())),
290  verbose_(iConfig.getUntrackedParameter("verbose", false) || !moduleLabels_.empty()),
291  getModuleLabels_(iConfig.getUntrackedParameter("getDataForModuleLabels", std::vector<std::string>())),
292  getData_(iConfig.getUntrackedParameter("getData", false) || !getModuleLabels_.empty()),
293  evno_(1),
294  listContent_(iConfig.getUntrackedParameter("listContent", true)),
295  listProvenance_(iConfig.getUntrackedParameter("listProvenance", false)) {
296  //now do what ever initialization is needed
299  if (getData_) {
301  if (getModuleLabels_.empty()) {
302  const std::string kPathStatus("edm::PathStatus");
303  const std::string kEndPathStatus("edm::EndPathStatus");
304  if (iBranch.className() != kPathStatus && iBranch.className() != kEndPathStatus) {
306  edm::InputTag{iBranch.moduleLabel(), iBranch.productInstanceName(), iBranch.processName()});
307  }
308  } else {
309  for (auto const& mod : this->getModuleLabels_) {
310  if (iBranch.moduleLabel() == mod) {
312  edm::InputTag{mod, iBranch.productInstanceName(), iBranch.processName()});
313  break;
314  }
315  }
316  }
317  });
318  }
319  }
320 
322  // do anything here that needs to be done at destruction time
323  // (e.g. close files, deallocate resources etc.)
324  }
325 
326  //
327  // member functions
328  //
329 
330  // ------------ method called to produce the data ------------
331  void EventContentAnalyzer::analyze(Event const& iEvent, EventSetup const&) {
332  typedef std::vector<StableProvenance const*> Provenances;
333  Provenances provenances;
334 
335  iEvent.getAllStableProvenance(provenances);
336 
337  if (listContent_) {
338  LogAbsolute("EventContent") << "\n"
339  << indentation_ << "Event " << std::setw(5) << evno_ << " contains "
340  << provenances.size() << " product" << (provenances.size() == 1 ? "" : "s")
341  << " with friendlyClassName, moduleLabel, productInstanceName and processName:"
342  << std::endl;
343  }
344 
345  std::string startIndent = indentation_ + verboseIndentation_;
346  for (auto const& provenance : provenances) {
347  std::string const& className = provenance->className();
348  const std::string kPathStatus("edm::PathStatus");
349  const std::string kEndPathStatus("edm::EndPathStatus");
350  if (className == kPathStatus || className == kEndPathStatus) {
351  continue;
352  }
353  std::string const& friendlyName = provenance->friendlyClassName();
354  //if(friendlyName.empty()) friendlyName = std::string("||");
355 
356  std::string const& modLabel = provenance->moduleLabel();
357  //if(modLabel.empty()) modLabel = std::string("||");
358 
359  std::string const& instanceName = provenance->productInstanceName();
360  //if(instanceName.empty()) instanceName = std::string("||");
361 
362  std::string const& processName = provenance->processName();
363 
364  bool doVerbose = verbose_ && (moduleLabels_.empty() || binary_search_all(moduleLabels_, modLabel));
365 
366  if (listContent_ || doVerbose) {
367  LogAbsolute("EventContent") << indentation_ << friendlyName << " \"" << modLabel << "\" \"" << instanceName
368  << "\" \"" << processName << "\""
369  << " (productId = " << provenance->productID() << ")" << std::endl;
370 
371  if (listProvenance_) {
372  const bool isAlias = provenance->branchDescription().isAlias();
373  std::string aliasForModLabel;
374  LogAbsolute("EventContent") << *provenance;
375  if (isAlias) {
376  aliasForModLabel = iEvent.getStableProvenance(provenance->originalBranchID()).moduleLabel();
377  LogAbsolute("EventContent") << "Is an alias for " << aliasForModLabel;
378  }
379  ProcessHistory const& processHistory = iEvent.processHistory();
380  for (ProcessConfiguration const& pc : processHistory) {
381  if (pc.processName() == provenance->processName()) {
382  ParameterSetID const& psetID = pc.parameterSetID();
383  pset::Registry const* psetRegistry = pset::Registry::instance();
384  ParameterSet const* processPset = psetRegistry->getMapped(psetID);
385  if (processPset) {
386  if (processPset->existsAs<ParameterSet>(modLabel)) {
387  if (isAlias) {
388  LogAbsolute("EventContent") << "Alias PSet";
389  }
390  LogAbsolute("EventContent") << processPset->getParameterSet(modLabel);
391  }
392  if (isAlias and processPset->existsAs<ParameterSet>(aliasForModLabel)) {
393  LogAbsolute("EventContent") << processPset->getParameterSet(aliasForModLabel);
394  }
395  }
396  }
397  }
398  }
399  }
400  std::string key = friendlyName + std::string(" + \"") + modLabel + std::string("\" + \"") + instanceName +
401  "\" \"" + processName + "\"";
402  ++cumulates_[key];
403 
404  if (doVerbose) {
405  //indent one level before starting to print
406  printObject(iEvent, className, modLabel, instanceName, processName, startIndent, verboseIndentation_);
407  continue;
408  }
409  if (getData_) {
410  std::string class_and_label = friendlyName + "_" + modLabel;
411  if (getModuleLabels_.empty() || binary_search_all(getModuleLabels_, modLabel) ||
412  binary_search_all(getModuleLabels_, class_and_label)) {
413  try {
414  GenericHandle handle(className);
415  } catch (edm::Exception const&) {
416  LogAbsolute("EventContent") << startIndent << " \"" << className << "\""
417  << " is an unknown type" << std::endl;
418  return;
419  }
420  GenericHandle handle(className);
421  iEvent.getByLabel(InputTag(modLabel, instanceName, processName), handle);
422  }
423  }
424  }
425  //std::cout << "Mine" << std::endl;
426  ++evno_;
427  }
428 
429  // ------------ method called at end of job -------------------
431  typedef std::map<std::string, int> nameMap;
432 
433  LogAbsolute("EventContent") << "\nSummary for key being the concatenation of friendlyClassName, moduleLabel, "
434  "productInstanceName and processName"
435  << std::endl;
436  for (nameMap::const_iterator it = cumulates_.begin(), itEnd = cumulates_.end(); it != itEnd; ++it) {
437  LogAbsolute("EventContent") << std::setw(6) << it->second << " occurrences of key " << it->first << std::endl;
438  }
439  }
440 
442  descriptions.setComment(
443  "This plugin will print a list of all products in the event "
444  "provenance. It also has options to print and/or get each product.");
445 
447 
449 
450  std::string defaultString("++");
451  np = desc.addOptionalUntracked<std::string>("indentation", defaultString);
452  np->setComment("This string is printed at the beginning of every line printed during event processing.");
453 
454  np = desc.addOptionalUntracked<bool>("verbose", false);
455  np->setComment("If true, the contents of products are printed.");
456 
457  defaultString = " ";
458  np = desc.addOptionalUntracked<std::string>("verboseIndentation", defaultString);
459  np->setComment(
460  "This string is used to further indent lines when printing the contents of products in verbose mode.");
461 
462  std::vector<std::string> defaultVString;
463 
464  np = desc.addOptionalUntracked<std::vector<std::string> >("verboseForModuleLabels", defaultVString);
465  np->setComment("If this vector is not empty, then only products with module labels on this list are printed.");
466 
467  np = desc.addOptionalUntracked<bool>("getData", false);
468  np->setComment("If true the products will be retrieved using getByLabel.");
469 
470  np = desc.addOptionalUntracked<std::vector<std::string> >("getDataForModuleLabels", defaultVString);
471  np->setComment(
472  "If this vector is not empty, then only products with module labels on this list are retrieved by getByLabel.");
473 
474  np = desc.addOptionalUntracked<bool>("listContent", true);
475  np->setComment("If true then print a list of all the event content.");
476 
477  np = desc.addOptionalUntracked<bool>("listProvenance", false);
478  np->setComment("If true, and if listContent or verbose is true, print provenance information for each product");
479 
480  descriptions.add("printContent", desc);
481  }
482 } // namespace edm
483 
std::vector< std::string > getModuleLabels_
void setComment(std::string const &value)
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:171
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
isFirst
Definition: cuy.py:418
std::string const & processName() const
std::map< std::string, int > cumulates_
assert(be >=bs)
static TypeWithDict byName(std::string const &name)
Definition: TypeWithDict.cc:74
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
int iEvent
Definition: GenABIO.cc:224
void analyze(Event const &, EventSetup const &) override
std::string const & className() const
int np
Definition: AMPTWrapper.h:43
std::string friendlyName(std::string const &iFullName)
std::string const & moduleLabel() const
std::string const & productInstanceName() const
TypeID unwrappedTypeID() const
tuple key
prepare the HTCondor submission files and eventually submit them
tuple handle
Definition: patZpeak.py:25
void callWhenNewProductsRegistered(std::function< void(BranchDescription const &)> const &func)
bool getMapped(key_type const &k, value_type &result) const
Definition: Registry.cc:17
static void fillDescriptions(ConfigurationDescriptions &descriptions)
bool getByLabel(InputTag const &tag, Handle< PROD > &result) const
Definition: Event.h:500
void setComment(std::string const &value)
ProcessHistory const & processHistory() const override
Definition: Event.cc:250
void sort_all(RandomAccessSequence &s)
wrappers for std::sort
Definition: Algorithms.h:92
ParameterSet const & getParameterSet(std::string const &) const
std::vector< std::string > moduleLabels_
void add(std::string const &label, ParameterSetDescription const &psetDescription)
bool binary_search_all(ForwardSequence const &s, Datum const &d)
wrappers for std::binary_search
Definition: Algorithms.h:58
Log< level::System, true > LogAbsolute
ParameterDescriptionBase * addOptionalUntracked(U const &iLabel, T const &value)
bool isPointer() const
StableProvenance const & getStableProvenance(BranchID const &theID) const
Definition: Event.cc:124
long double T
T mod(const T &a, const T &b)
Definition: ecalDccMap.h:4
static const bool doPrint
EventContentAnalyzer(ParameterSet const &)
tuple size
Write out results.
static Registry * instance()
Definition: Registry.cc:12
std::string className(const T &t)
Definition: ClassName.h:31
void getAllStableProvenance(std::vector< StableProvenance const * > &provenances) const
Definition: Event.cc:136