| 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 |
* @file WriterRoot.cc |
| 8 |
* @brief Implementation of \b class WriterRoot |
| 9 |
* |
| 10 |
*/ |
| 11 |
#include "HepMC3/WriterRoot.h" |
| 12 |
#include <cstdio> // sprintf |
| 13 |
// ROOT header files |
| 14 |
#include "TFile.h" |
| 15 |
#include "TTree.h" |
| 16 |
|
| 17 |
namespace HepMC3 { |
| 18 |
|
| 19 |
WriterRoot::WriterRoot(const std::string &filename, shared_ptr<GenRunInfo> run): |
| 20 |
m_events_count(0) { |
| 21 |
set_run_info(run); |
| 22 |
|
| 23 |
m_file = TFile::Open(filename.c_str(),"RECREATE"); |
| 24 |
if ( !m_file->IsOpen() ) { |
| 25 |
ERROR( "WriterRoot: problem opening file: " << filename ) |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
if ( run_info() ) write_run_info(); |
| 30 |
} |
| 31 |
|
| 32 |
void WriterRoot::write_event(const GenEvent &evt) { |
| 33 |
if ( !m_file->IsOpen() ) return; |
| 34 |
|
| 35 |
if ( !run_info() ) { |
| 36 |
set_run_info(evt.run_info()); |
| 37 |
write_run_info(); |
| 38 |
} else { |
| 39 |
if ( evt.run_info() && run_info() != evt.run_info() ) |
| 40 |
WARNING( "WriterAscii::write_event: GenEvents contain " |
| 41 |
"different GenRunInfo objects from - only the " |
| 42 |
"first such object will be serialized." ) |
| 43 |
} |
| 44 |
|
| 45 |
GenEventData data; |
| 46 |
evt.write_data(data); |
| 47 |
|
| 48 |
char buf[16] = ""; |
| 49 |
sprintf(buf,"%15i",++m_events_count); |
| 50 |
|
| 51 |
int nbytes = m_file->WriteObject(&data, buf); |
| 52 |
|
| 53 |
if( nbytes == 0 ) { |
| 54 |
ERROR( "WriterRoot: error writing event") |
| 55 |
m_file->Close(); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
void WriterRoot::write_run_info() { |
| 60 |
if ( !m_file->IsOpen() || !run_info() ) return; |
| 61 |
|
| 62 |
GenRunInfoData data; |
| 63 |
run_info()->write_data(data); |
| 64 |
|
| 65 |
int nbytes = m_file->WriteObject(&data,"GenRunInfoData"); |
| 66 |
|
| 67 |
if( nbytes == 0 ) { |
| 68 |
ERROR( "WriterRoot: error writing GenRunInfo") |
| 69 |
m_file->Close(); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
void WriterRoot::close() { |
| 74 |
m_file->Close(); |
| 75 |
} |
| 76 |
|
| 77 |
bool WriterRoot::failed() { |
| 78 |
if ( !m_file->IsOpen() ) return true; |
| 79 |
|
| 80 |
return false; |
| 81 |
} |
| 82 |
|
| 83 |
} // namespace HepMC3 |