HepMC3 event record library
class_example_write.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_write.cc
8  * @brief Basic example of use of root I/O: writing events to 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/ReaderAscii.h"
16 #include "HepMC3/Print.h"
17 
18 #include "TFile.h"
19 
20 #include <iostream>
21 #include <sstream>
22 
23 using namespace HepMC3;
24 
25 #include "MyClass.h"
26 #include "MyRunClass.h"
27 
28 /** Main */
29 int main(int argc, char **argv) {
30 
31  if( argc<3 ) {
32  std::cout << "Usage: " << argv[0] << " <input_hepmc3_file> <output_root_file>" <<std:: endl;
33  exit(-1);
34  }
35 
36  ReaderAscii text_input(argv[1]);
37 
38  TFile* fFile = new TFile(argv[2],"RECREATE");
39 
40  int events_parsed = 0;
41 
42  bool is_gen_run_info_written = false;
43 
44  while( !text_input.failed() ) {
45 
46  GenEvent evt(Units::GEV,Units::MM);
47 
48  text_input.read_event(evt);
49 
50  if( text_input.failed() ) break;
51 
52  if( events_parsed == 0 ) {
53  std::cout << "First event: " << std::endl;
54  Print::listing(evt);
55  }
56 
57  if(!is_gen_run_info_written) {
58  if(evt.run_info()) {
59  GenRunInfo run_info(*evt.run_info());
60 
61  MyRunClass *my_run = new MyRunClass();
62 
63  my_run->SetRunInfo(&run_info);
64 
65  fFile->WriteObject(my_run,"MyRunClass");
66 
67  is_gen_run_info_written = true;
68  }
69  }
70 
71  MyClass* myclass = new MyClass();
72 
73  myclass->SetEvent(&evt);
74  //
75  std::ostringstream os;
76  os << events_parsed;
77  std::string stevt = "Event_" + os.str();
78  const char* chevt = stevt.c_str();
79 
80  std::cout << "writing " << stevt << std::endl;
81 
82  fFile->WriteObject(myclass, chevt);
83 
84  ++events_parsed;
85 
86  if( events_parsed%100 == 0 ) {
87  std::cout << "Event: " << events_parsed << std::endl;
88  }
89  }
90 
91  text_input.close();
92  fFile->Close();
93  std::cout << "Events parsed and written: " << events_parsed << std::endl;
94 
95  return 0;
96 }
Definition of class GenRunInfo.
Sample class for root I/O test.
Definition: MyClass.h:9
GenEvent I/O parsing for structured text files.
Definition: ReaderAscii.h:29
Stores run-related information.
Definition: GenRunInfo.h:33
static void listing(std::ostream &os, const GenEvent &event, unsigned short precision=2)
Print event in listing (HepMC2) format.
Definition: Print.cc:50
Sample class for root I/O test.
Definition: MyRunClass.h:9
Stores event-related information.
Definition: GenEvent.h:41
Definition of class ReaderAscii.
int main(int argc, char **argv)
void SetEvent(GenEvent *)
Set HepMC event.
Definition: MyClass.cc:5
Definition of class GenEvent.