HepMC3 event record library
class_example_read.cc
1 // -*- C++ -*-
2 //
3 // This file is part of HepMC
4 // Copyright (C) 2014-2019 The HepMC collaboration (see AUTHORS for details)
5 //
6 /**
7  * @example class_example_read.cc
8  * @brief Basic example of use of root I/O: reading events from file
9  *
10  * @author Witold Pokorski
11  * @date 16/10/14
12  */
13 #include "HepMC3/GenEvent.h"
14 #include "HepMC3/GenRunInfo.h"
15 #include "HepMC3/WriterAscii.h"
16 #include "HepMC3/Print.h"
17 
18 #include "MyClass.h"
19 #include "MyRunClass.h"
20 
21 #include "TFile.h"
22 #include "TSystem.h"
23 #include "TKey.h"
24 
25 #include <iostream>
26 
27 using namespace HepMC3;
28 using std::cout;
29 using std::endl;
30 
31 /** Main */
32 int main(int argc, char **argv) {
33 
34  if( argc<3 ) {
35  cout << "Usage: " << argv[0] << " <input_root_file> <output_hepmc3_file>" << endl;
36  exit(-1);
37  }
38 
39 
40  TFile fo(argv[1]);
41  WriterAscii text_output(argv[2]);
42 
43  MyClass* myevent;
44  int events_parsed = 0;
45 
46  // Get GenRunInfo, if available
47  MyRunClass *my_run = (MyRunClass*)fo.Get("MyRunClass");
48  shared_ptr<GenRunInfo> run_info;
49 
50  if( my_run ) run_info.reset(my_run->GetRunInfo());
51 
52 
53  fo.GetListOfKeys()->Print();
54 
55  TIter next(fo.GetListOfKeys());
56  TKey *key;
57 
58  while ((key=(TKey*)next()))
59  {
60  const char *cl = key->GetClassName();
61 
62  if( strncmp(cl,"MyClass",7) != 0 ) continue;
63 
64  fo.GetObject(key->GetName(), myevent);
65 
66  cout << "Event: " << key->GetName() << endl;
67 
68  if( events_parsed == 0 ) {
69  cout << "First event: " << endl;
70  Print::listing(*(myevent->GetEvent()));
71  }
72 
73  if( run_info ) {
74  cout << "Setting run info" << endl;
75  myevent->GetEvent()->set_run_info(run_info);
76  run_info.reset();
77  }
78 
79  text_output.write_event(*(myevent->GetEvent()));
80  ++events_parsed;
81 
82  if( events_parsed%1000 == 0 ) {
83  cout << "Event: " << events_parsed << endl;
84  }
85 
86  delete myevent->GetEvent();
87  delete myevent;
88  }
89 
90  text_output.close();
91 
92  std::cout << "Events parsed and written: " << events_parsed << std::endl;
93 
94  return 0;
95 }
void set_run_info(shared_ptr< GenRunInfo > run)
Set the GenRunInfo object by smart pointer.
Definition: GenEvent.h:129
Definition of class GenRunInfo.
Sample class for root I/O test.
Definition: MyClass.h:9
Definition of class WriterAscii.
static void listing(std::ostream &os, const GenEvent &event, unsigned short precision=2)
Print event in listing (HepMC2) format.
Definition: Print.cc:51
Sample class for root I/O test.
Definition: MyRunClass.h:9
int main(int argc, char **argv)
GenRunInfo * GetRunInfo()
Get HepMC event.
Definition: MyRunClass.cc:10
Definition of class GenEvent.
GenEvent I/O serialization for structured text files.
Definition: WriterAscii.h:25
GenEvent * GetEvent()
Get HepMC event.
Definition: MyClass.cc:10