LDMX Software
HepMCReader.cxx
2
3#include <fstream>
4#include <string>
5
6#include "Framework/Exception/Exception.h"
7#include "HepMC3/ReaderAscii.h"
8#include "HepMC3/ReaderAsciiHepMC2.h"
9
10namespace simcore {
11namespace hepmc {
12
13HepMCReader::HepMCReader(std::string& filename) {
14 ldmx_log(info) << "Opening HepMC file " << filename;
15
16 // Try to detect the file format by reading the first non-empty line
17 std::ifstream test_file(filename);
18 std::string first_line;
19 bool found_line = false;
20
21 if (test_file.is_open()) {
22 // Skip empty lines and find the first non-empty line
23 while (std::getline(test_file, first_line)) {
24 // Trim whitespace
25 first_line.erase(0, first_line.find_first_not_of(" \t\r\n"));
26 first_line.erase(first_line.find_last_not_of(" \t\r\n") + 1);
27
28 if (!first_line.empty()) {
29 found_line = true;
30 break;
31 }
32 }
33 test_file.close();
34 }
35
36 if (found_line) {
37 ldmx_log(debug) << "First non-empty line: " << first_line;
38
39 // Check if it's HepMC2 format
40 if (first_line.find("HepMC::") != std::string::npos ||
41 first_line.find("IO_GenEvent") != std::string::npos) {
42 ldmx_log(info) << "Detected HepMC2 format, using ReaderAsciiHepMC2";
43 reader_ = std::make_shared<HepMC3::ReaderAsciiHepMC2>(filename);
44 } else {
45 ldmx_log(info) << "Assuming HepMC3 format, using ReaderAscii";
46 reader_ = std::make_shared<HepMC3::ReaderAscii>(filename);
47 }
48 } else {
49 ldmx_log(warn)
50 << "Could not find non-empty line, defaulting to HepMC3 format";
51 reader_ = std::make_shared<HepMC3::ReaderAscii>(filename);
52 }
53
54 if (reader_->failed()) {
55 EXCEPTION_RAISE("BadFile", "Failed to open HepMC file: " + filename);
56 }
57}
58
59std::unique_ptr<HepMCEvent> HepMCReader::readNextEvent() {
60 // Create a new HepMC3 GenEvent
61 auto gen_event = std::make_shared<HepMC3::GenEvent>();
62
63 // Read the next event from the file
64 if (!reader_->read_event(*gen_event)) {
65 ldmx_log(warn) << "No next event was found by the HepMC reader.";
66 return nullptr;
67 }
68
69 // Check if the event is empty
70 if (gen_event->particles().empty()) {
71 ldmx_log(warn) << "Empty event found by HepMC reader.";
72 return nullptr;
73 }
74
75 // Increment event counter and log progress every 100 events
77 if (event_counter_ % 100 == 0) {
78 ldmx_log(debug) << "HepMCReader: Read " << event_counter_ << " events";
79 }
80
81 // Create and return the wrapped event
82 return std::make_unique<HepMCEvent>(gen_event);
83}
84
85} // namespace hepmc
86} // namespace simcore
Class for reading HepMC event data.
HepMCReader(std::string &fileName)
Class constructor.
std::shared_ptr< HepMC3::Reader > reader_
The HepMC3 reader.
Definition HepMCReader.h:50
std::unique_ptr< HepMCEvent > readNextEvent()
Read the next event.
int event_counter_
Event counter for tracking progress.
Definition HepMCReader.h:55
Dynamically loadable photonuclear models either from SimCore or external libraries implementing this ...