MARLEY (Model of Argon Reaction Low Energy Yields) v2.0.0
A Monte Carlo event generator for tens-of-MeV neutrino interactions
Loading...
Searching...
No Matches
marley::OutputFileAscii Class Reference

Class that represents an output file in the standard ASCII format for HepMC3 events. More...

#include <OutputFileAscii.hh>

Inheritance diagram for marley::OutputFileAscii:
marley::OutputFile

Public Member Functions

 OutputFileAscii (const JSON &output_config)
 
virtual int_fast64_t bytes_written () override
 The number of bytes that have been written during the current MARLEY session to this file.
 
virtual bool resume (std::unique_ptr< marley::Generator > &gen, long &num_previous_events) override
 Load a marley::Generator object whose configuration and state were saved to the metadata in the output file.
 
virtual void write_event (HepMC3::GenEvent *event) override
 Write a new HepMC3::GenEvent to this output file.
 
- Public Member Functions inherited from marley::OutputFile
bool mode_is_resume () const
 
const std::string & name () const
 

Protected Member Functions

virtual void open ()
 Opens the owned std::fstream with the correct settings.
 
- Protected Member Functions inherited from marley::OutputFile
 OutputFile (const JSON &output_config)
 
bool check_if_file_exists (const std::string &filename)
 Checks that a given file exists (and is readable)
 
void prompt_before_overwrite ()
 If mode_ is OVERWRITE and the output file already exists and force_ is false, prompt the user before overwriting. If the user declines, throw a marley::Error with a diagnostic message suggesting the "force" and "mode" configuration keys.
 
std::unique_ptr< marley::Generatorrestore_generator (const marley::JSON &config)
 Helper function for resume() that instantiates a marley::Generator object given the previous JSON configuration object.
 

Protected Attributes

int_fast64_t byte_count_ = 0
 Storage for the number of bytes written to disk.
 
std::shared_ptr< HepMC3::GenEventpending_flush_event_
 
std::streampos pending_truncate_pos_ = std::streampos( -1 )
 
std::shared_ptr< HepMC3::ReaderAsciireader_
 
std::fstream stream_
 Stream used to read and write from the output file as needed.
 
std::shared_ptr< HepMC3::WriterAsciiwriter_
 Helper object used to produce standard ASCII HepMC3 output.
 
- Protected Attributes inherited from marley::OutputFile
bool force_
 
Format format_
 Format to use when writing events to the file.
 
Mode mode_
 
std::string name_
 Name of the file to receive output.
 

Additional Inherited Members

- Public Types inherited from marley::OutputFile
enum class  Format { ASCII , ROOT }
 
- Static Public Member Functions inherited from marley::OutputFile
static std::shared_ptr< OutputFilemake_OutputFile (const JSON &output_config)
 
- Protected Types inherited from marley::OutputFile
enum class  Mode { OVERWRITE , RESUME }
 
- Static Protected Member Functions inherited from marley::OutputFile
static void merge_reweight_provenance_weights (HepMC3::GenRunInfo &run_info, marley::Generator &gen)
 When resuming from a file that has been through one or more reweight passes, merge the reweight provenance weight calculator configurations with the original generate-time weights. Builds a combined Weighter and gives the Generator ownership. If no reweight provenance is found, this function is a no-op.
 

Detailed Description

Class that represents an output file in the standard ASCII format for HepMC3 events.

Definition at line 35 of file OutputFileAscii.hh.

Constructor & Destructor Documentation

◆ OutputFileAscii()

marley::OutputFileAscii::OutputFileAscii ( const JSON & output_config)

Definition at line 65 of file OutputFileAscii.cc.

66 : marley::OutputFile( output_config )
67{
68 format_ = Format::ASCII;
69
70 this->open();
71 reader_ = std::make_shared< HepMC3::ReaderAscii >( stream_ );
72 writer_ = std::make_shared< HepMC3::WriterAscii >( stream_ );
73
74 // Ensure that all floating-point values are output with full precision
75 writer_->set_precision( std::numeric_limits<double>::max_digits10 );
76}
virtual void open()
Opens the owned std::fstream with the correct settings.
std::fstream stream_
Stream used to read and write from the output file as needed.
std::shared_ptr< HepMC3::ReaderAscii > reader_
std::shared_ptr< HepMC3::WriterAscii > writer_
Helper object used to produce standard ASCII HepMC3 output.
Format format_
Format to use when writing events to the file.

Member Function Documentation

◆ bytes_written()

int_fast64_t marley::OutputFileAscii::bytes_written ( )
overridevirtual

The number of bytes that have been written during the current MARLEY session to this file.

Implements marley::OutputFile.

Definition at line 211 of file OutputFileAscii.cc.

211 {
212 // If the stream is open, then update the byte count. Otherwise, just
213 // use the saved value.
214 if ( stream_.is_open() ) {
215 stream_.flush();
216 byte_count_ = static_cast<int_fast64_t>( stream_.tellp() );
217 }
218 return byte_count_;
219}
int_fast64_t byte_count_
Storage for the number of bytes written to disk.

References byte_count_, and stream_.

◆ open()

void marley::OutputFileAscii::open ( )
protectedvirtual

Opens the owned std::fstream with the correct settings.

Definition at line 78 of file OutputFileAscii.cc.

78 {
79
81
82 auto open_mode_flag = std::ios::in | std::ios::out | std::ios::trunc;
83
84 if ( mode_ == Mode::RESUME ) {
86 throw marley::Error( "Cannot resume run. Could"
87 " not open the file \"" + name_ + '\"' );
88 else open_mode_flag = std::ios::in | std::ios::out;
89 }
90 else if ( mode_ != Mode::OVERWRITE ) {
91 throw marley::Error( "Unrecognized file mode encountered in"
92 " OutputFileAscii::open()" );
93 }
94
95 stream_.open( name_, open_mode_flag );
96
97}
void prompt_before_overwrite()
If mode_ is OVERWRITE and the output file already exists and force_ is false, prompt the user before ...
Definition OutputFile.cc:63
bool check_if_file_exists(const std::string &filename)
Checks that a given file exists (and is readable)
Definition OutputFile.hh:85
std::string name_
Name of the file to receive output.

References marley::OutputFile::check_if_file_exists(), marley::OutputFile::name_, marley::OutputFile::prompt_before_overwrite(), and stream_.

◆ resume()

bool marley::OutputFileAscii::resume ( std::unique_ptr< marley::Generator > & gen,
long & num_previous_events )
overridevirtual

Load a marley::Generator object whose configuration and state were saved to the metadata in the output file.

Parameters
[out]genA std::unique_ptr that will be filled with a restored Generator object constructed using the saved metadata
[out]num_previous_eventsThe number of events previously saved to the output file
Returns
true if the Generator is successfully restored using the file's saved metadata, or false otherwise.

Implements marley::OutputFile.

Definition at line 99 of file OutputFileAscii.cc.

101{
102 if ( mode_ != Mode::RESUME ) {
103 throw marley::Error( "Cannot call OutputFileAscii::resume() for an output"
104 " mode other than \"resume\"" );
105 return false;
106 }
107
108 MARLEY_LOG( INFO, "io" ) << "Continuing previous run from the file " << name_;
109
110 // Create a temporary event to use for storage while parsing the file
111 auto evt = std::make_shared< HepMC3::GenEvent >();
112
113 // Read back the first event from the file so that we can retrieve the run
114 // information
115 stream_.seekg( 0, std::ios::beg );
116 bool read_ok = reader_->read_event( *evt );
117
118 auto run_info = evt->run_info();
119
120 if ( !read_ok || !run_info ) {
121 throw marley::Error( "Failed to retrieve run information from the file "
122 + name_ );
123 return false;
124 }
125
126 // Extract the prior generator JSON configuration from the RunInfo
127 auto config_str = run_info->attribute< HepMC3::StringAttribute >(
128 "MARLEY.JSONconfig" );
129
130 if ( !config_str ) {
131 throw marley::Error( "Failed to retrieve generator configuration from the"
132 " file " + name_ );
133 return false;
134 }
135
136 auto seed_str = run_info->attribute< HepMC3::StringAttribute >(
137 "MARLEY.RNGseed" );
138
139 if ( !seed_str ) {
140 throw marley::Error( "Failed to load previous random number"
141 " generator seed from the file " + name_ );
142 return false;
143 }
144
145 // Parse the prior generator configuration into a JSON object
146 auto json_config = marley::JSON::load( config_str->value() );
147
148 // Move to the beginning of the last HepMC3 event in the file and
149 // save its stream position for truncation
150 std::streampos last_event_pos = seek_to_last_genevent( stream_ );
151
152 if ( last_event_pos == std::streampos( -1 ) ) {
153 throw marley::Error( "Failed to find the last event in the file "
154 + name_ );
155 return false;
156 }
157
158 // Parse the last HepMC3 event so that we can retrieve the generator state
159 read_ok = reader_->read_event( *evt );
160
161 auto state_str = evt->attribute< HepMC3::StringAttribute >(
162 "MARLEY.GeneratorState" );
163
164 if ( !read_ok || !state_str ) {
165 throw marley::Error( "Failed to retrieve generator state from the file "
166 + name_ );
167 return false;
168 }
169
170 // We assume that the events in the file were originally written out using
171 // the convention in the marley executable: the event number of the last
172 // event in the file is equal to the total number of events.
173 num_previous_events = evt->event_number();
174
175 MARLEY_LOG( INFO, "io" ) << "Resuming run from \"" << name_ << "\":"
176 << " found " << num_previous_events << " previous event(s)";
177
178 // We're done retrieving the information. Restore the Generator to its
179 // previous state
180 gen = this->restore_generator( json_config );
181 gen->seed_using_state_string( state_str->value() );
182
183 MARLEY_LOG( INFO, "io" ) << "The previous run was initialized using"
184 << " the random number generator seed " << seed_str->value();
185
186 // If the file has reweight provenance, merge the accumulated weight
187 // calculator configurations into the Generator's Weighter before
188 // setting up run info. This ensures new events have the correct
189 // number of weight slots to match the existing events in the file.
190 merge_reweight_provenance_weights( *run_info, *gen );
191
192 // Initialize the Generator's run info now so that it is available for
193 // use below (it is normally initialized lazily inside create_event()).
194 gen->set_up_run_info();
195
196 // Defer truncation: save the event and truncation position so that
197 // the stale GeneratorState and HepMC3 footer are removed only on the
198 // first write_event() call. This ensures the GeneratorState remains in
199 // the file should an exception occur before any new event is written.
200 // Also reassign the event's run_info to the Generator's so that the
201 // pointer-identity comparison in WriterAscii::write_event() does not
202 // produce spurious "different GenRunInfo" warnings.
203 evt->set_run_info( gen->run_info() );
204 evt->remove_attribute( "MARLEY.GeneratorState" );
205 pending_truncate_pos_ = last_event_pos;
207
208 return true;
209}
std::shared_ptr< HepMC3::GenEvent > pending_flush_event_
std::streampos pending_truncate_pos_
std::unique_ptr< marley::Generator > restore_generator(const marley::JSON &config)
Helper function for resume() that instantiates a marley::Generator object given the previous JSON con...
Definition OutputFile.cc:55
static void merge_reweight_provenance_weights(HepMC3::GenRunInfo &run_info, marley::Generator &gen)
When resuming from a file that has been through one or more reweight passes, merge the reweight prove...
Definition OutputFile.cc:80

References marley::OutputFile::merge_reweight_provenance_weights(), marley::OutputFile::name_, pending_flush_event_, pending_truncate_pos_, reader_, marley::OutputFile::restore_generator(), and stream_.

◆ write_event()

void marley::OutputFileAscii::write_event ( HepMC3::GenEvent * event)
overridevirtual

Write a new HepMC3::GenEvent to this output file.

If a nullptr is passed to this function, then a marley::Error will be thrown

Implements marley::OutputFile.

Definition at line 221 of file OutputFileAscii.cc.

221 {
222
223 if ( !event ) throw marley::Error( "Null pointer passed to"
224 " OutputFileAscii::write_event()" );
225
226 if ( pending_flush_event_ ) {
227 stream_.flush();
228 std::filesystem::resize_file( name_,
229 static_cast<std::uintmax_t>( pending_truncate_pos_ ) );
230 stream_.clear();
233 writer_->set_run_info( pending_flush_event_->run_info() );
234 writer_->write_event( *pending_flush_event_ );
235 stream_.flush();
236 pending_flush_event_.reset();
237 pending_truncate_pos_ = std::streampos( -1 );
238 }
239
240 writer_->write_event( *event );
241}

References marley::OutputFile::name_, pending_flush_event_, pending_truncate_pos_, stream_, and writer_.

Member Data Documentation

◆ byte_count_

int_fast64_t marley::OutputFileAscii::byte_count_ = 0
protected

Storage for the number of bytes written to disk.

Definition at line 66 of file OutputFileAscii.hh.

Referenced by bytes_written().

◆ pending_flush_event_

std::shared_ptr< HepMC3::GenEvent > marley::OutputFileAscii::pending_flush_event_
protected

Last event without its GeneratorState, to be flushed on the first write() call after resume

Definition at line 74 of file OutputFileAscii.hh.

Referenced by resume(), and write_event().

◆ pending_truncate_pos_

std::streampos marley::OutputFileAscii::pending_truncate_pos_ = std::streampos( -1 )
protected

Stream position at which to truncate on the first write after resume, removing the stale GeneratorState and HepMC3 footer

Definition at line 70 of file OutputFileAscii.hh.

Referenced by resume(), and write_event().

◆ reader_

std::shared_ptr< HepMC3::ReaderAscii > marley::OutputFileAscii::reader_
protected

Helper object used to read back HepMC3 events for restoring the generator state, etc.

Definition at line 60 of file OutputFileAscii.hh.

Referenced by resume().

◆ stream_

std::fstream marley::OutputFileAscii::stream_
protected

Stream used to read and write from the output file as needed.

Definition at line 56 of file OutputFileAscii.hh.

Referenced by bytes_written(), open(), resume(), and write_event().

◆ writer_

std::shared_ptr< HepMC3::WriterAscii > marley::OutputFileAscii::writer_
protected

Helper object used to produce standard ASCII HepMC3 output.

Definition at line 63 of file OutputFileAscii.hh.

Referenced by write_event().


The documentation for this class was generated from the following files: