https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Checkpoint.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10// C POSIX includes
11#include <sstream>
12#include <sys/stat.h>
13
14#include <system_error>
15
16// Moose includes
17#include "Checkpoint.h"
18#include "FEProblem.h"
19#include "MooseApp.h"
21#include "MooseMesh.h"
24
25#include "libmesh/checkpoint_io.h"
26#include "libmesh/enum_xdr_mode.h"
27#include "libmesh/utility.h"
28
30
33{
34 // Get the parameters from the base classes
36
37 params.addClassDescription("Output for MOOSE recovery checkpoint files.");
38
39 // Typical checkpoint options
40 params.addParam<unsigned int>("num_files", 2, "Number of the restart files to save");
41 params.addParam<std::string>(
42 "suffix",
43 "cp",
44 "This will be appended to the file_base to create the directory name for checkpoint files.");
45 // For checkpoints, set the wall time output interval to defualt of 1 hour (3600 s)
46 params.addParam<Real>(
47 "wall_time_interval", 3600, "The target wall time interval (in seconds) at which to output");
48
49 // Since it makes the most sense to write checkpoints at the end of time steps,
50 // change the default value of execute_on to TIMESTEP_END
51 ExecFlagEnum & exec_enum = params.set<ExecFlagEnum>("execute_on", true);
52 exec_enum = {EXEC_TIMESTEP_END};
53
54 return params;
55}
56
58 : FileOutput(parameters),
59 _num_files(getParam<unsigned int>("num_files")),
60 _suffix(getParam<std::string>("suffix"))
61{
62 // Prevent the checkpoint from executing at any time other than INITIAL,
63 // TIMESTEP_END, and FINAL
65
66 // The following updates the value of _wall_time_interval if the
67 // '--output-wall-time-interval' command line parameter is used.
68 // If it is not used, _wall_time_interval keeps its current value.
69 // 'The --output-wall-time-interval parameter is necessary for testing
70 // and should only be used in the test suite.
72}
73
74std::string
76{
77 // Get the time step with correct zero padding
78 std::ostringstream output;
79 output << directory() << "/" << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
80 << std::right << timeStep();
81
82 return output.str();
83}
84
85std::string
87{
88 return _file_base + "_" + _suffix;
89}
90
91bool
93{
94 // should_output_parent ensures that we output only when _execute_on contains
95 // _current_execute_flag (see Output::shouldOutput), ensuring that we wait
96 // until the end of the timestep to write, preventing the output of an
97 // unconverged solution.
98 const bool should_output_parent = FileOutput::shouldOutput();
99 if (!should_output_parent)
100 return false; // No point in continuing
101
102 // Check for signal
103 // Reading checkpoint on time step 0 is not supported
104 const bool should_output_signal = (Moose::interrupt_signal_number != 0) && (timeStep() > 0);
105 if (should_output_signal)
106 {
107 _console << "Unix signal SIGUSR1 detected. Outputting checkpoint file.\n";
108 // Reset signal number since we output
110 return true;
111 }
112
113 // Check if enough wall time has elapsed to output
114 const bool should_output_wall_time = _wall_time_since_last_output >= _wall_time_interval;
115 if (should_output_wall_time)
116 return true;
117
118 // Check if the checkpoint should "normally" output, i.e. if it was created
119 // through the input file
120 const bool should_output = (onInterval() || _current_execute_flag == EXEC_FINAL);
121
122 return should_output;
123}
124
125void
127{
128 // Create the output directory
129 const auto cp_dir = directory();
130 Utility::mkdir(cp_dir.c_str());
131
132 // Create the output filename
133 const auto current_file = filename();
134
135 // Create checkpoint file structure
136 CheckpointFileNames curr_file_struct;
137
138 curr_file_struct.checkpoint = current_file + _app.checkpointSuffix();
139
140 const auto mesh_paths = _problem_ptr->mesh().writeRecoveryFiles(curr_file_struct.checkpoint);
141 curr_file_struct.restart.insert(
142 curr_file_struct.restart.end(), mesh_paths.begin(), mesh_paths.end());
143
144 // Write out meta data if there is any (only on processor zero)
145 if (processor_id() == 0)
146 {
147 const auto paths = _app.writeRestartableMetaData(curr_file_struct.checkpoint);
148 curr_file_struct.restart.insert(curr_file_struct.restart.begin(), paths.begin(), paths.end());
149 }
150
151 // Write out the backup
152 const auto paths = _app.backup(_app.restartFolderBase(current_file));
153 curr_file_struct.restart.insert(curr_file_struct.restart.begin(), paths.begin(), paths.end());
154
155 // Remove old checkpoint files
156 updateCheckpointFiles(curr_file_struct);
157}
158
159void
161{
162 // It is possible to have already written a checkpoint with the same file
163 // names contained in file_struct. If this is the case, file_struct will
164 // already be stored in _file_names. When this happens, the current state of
165 // the simulation is likely different than the state when the duplicately
166 // named checkpoint was last written. Because of this, we want to go ahead and
167 // rewrite the duplicately named checkpoint, overwritting the files
168 // representing the old state. For accurate bookkeeping, we will delete the
169 // existing instance of file_struct from _file_names and re-append it to the
170 // end of _file_names (to keep the order in which checkpoints are written
171 // accurate).
172
173 const auto it = std::find(_file_names.begin(), _file_names.end(), file_struct);
174 // file_struct was found in _file_names.
175 // Delete it so it can be re-added as the last element.
176 if (it != _file_names.end())
177 _file_names.erase(it);
178
179 _file_names.push_back(file_struct);
180
181 // Remove the file and the corresponding directory if it's empty
182 const auto remove_file = [this](const std::filesystem::path & path)
183 {
184 std::error_code err;
185
186 if (!std::filesystem::remove(path, err))
187 mooseWarning("Error during the deletion of checkpoint file\n",
188 std::filesystem::absolute(path),
189 "\n\n",
190 err.message());
191
192 const auto dir = path.parent_path();
193 if (std::filesystem::is_empty(dir))
194 if (!std::filesystem::remove(dir, err))
195 mooseError("Error during the deletion of checkpoint directory\n",
196 std::filesystem::absolute(dir),
197 "\n\n",
198 err.message());
199 };
200
201 // Remove un-wanted files
202 if (_file_names.size() > _num_files)
203 {
204 // Extract the filenames to be removed
205 CheckpointFileNames delete_files = _file_names.front();
206
207 // Remove these filenames from the list
208 _file_names.pop_front();
209
210 // Delete restartable data
211 for (const auto & path : delete_files.restart)
212 remove_file(path);
213
214 // Delete checkpoint files
215 // This file may not exist so don't worry about checking for success
216 if (processor_id() == 0)
219 }
220}
221
222void
224{
225 const auto & execute_on = getParam<ExecFlagEnum>("execute_on");
226 const std::set<ExecFlagType> allowed = {EXEC_INITIAL, EXEC_TIMESTEP_END, EXEC_FINAL};
227 for (const auto & value : execute_on)
228 if (!allowed.count(value))
229 paramError("execute_on",
230 "The exec flag ",
231 value,
232 " is not allowed. Allowed flags are INITIAL, TIMESTEP_END, and FINAL.");
233}
234
235std::stringstream
237{
238 static const unsigned int console_field_width = 27;
239 std::stringstream checkpoint_info;
240
241 std::stringstream interval_info_ss;
242 interval_info_ss << "Every " << std::defaultfloat << _wall_time_interval << " s";
243 const std::string interval_info = interval_info_ss.str();
244
245 checkpoint_info << std::left << std::setw(console_field_width)
246 << " Wall Time Interval:" << interval_info << "\n";
247
248 const std::string user_info = "Outputs/" + name();
249
250 checkpoint_info << std::left << std::setw(console_field_width) << " Checkpoint:" << user_info
251 << "\n";
252
253 checkpoint_info << std::left << std::setw(console_field_width)
254 << " # Checkpoints Kept:" << std::to_string(_num_files) << "\n";
255 std::string exec_on_values = "";
256 for (const auto & item : _execute_on)
257 exec_on_values += item.name() + " ";
258 checkpoint_info << std::left << std::setw(console_field_width)
259 << " Execute On:" << exec_on_values << "\n";
260
261 return checkpoint_info;
262}
registerMooseObject("MooseApp", Checkpoint)
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition MooseError.h:345
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
const ExecFlagType EXEC_TIMESTEP_END
Definition Moose.C:37
const ExecFlagType EXEC_INITIAL
Definition Moose.C:31
const ExecFlagType EXEC_FINAL
Definition Moose.C:49
void ErrorVector unsigned int
Writes out three things:
Definition Checkpoint.h:49
void updateCheckpointFiles(CheckpointFileNames file_struct)
Definition Checkpoint.C:160
std::stringstream checkpointInfo() const
Gathers and records information used later for console output.
Definition Checkpoint.C:236
void validateExecuteOn() const
Determines if the requested values of execute_on are valid for checkpoints.
Definition Checkpoint.C:223
std::string directory() const
Retrieve the checkpoint output directory.
Definition Checkpoint.C:86
virtual std::string filename() override
Returns the base filename for the checkpoint files.
Definition Checkpoint.C:75
virtual void output() override
Outputs a checkpoint file.
Definition Checkpoint.C:126
virtual bool shouldOutput() override
Determines if the checkpoint should write out to a file.
Definition Checkpoint.C:92
static InputParameters validParams()
Definition Checkpoint.C:32
Checkpoint(const InputParameters &parameters)
Class constructor.
Definition Checkpoint.C:57
std::deque< CheckpointFileNames > _file_names
Vector of checkpoint filename structures.
Definition Checkpoint.h:108
const std::string _suffix
Directory suffix.
Definition Checkpoint.h:105
unsigned int _num_files
Max no. of output files to store.
Definition Checkpoint.h:102
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
A MultiMooseEnum object to hold "execute_on" flags.
virtual MooseMesh & mesh() override
An outputter with filename support.
Definition FileOutput.h:21
unsigned int _padding
Number of digits to pad the extensions.
Definition FileOutput.h:83
static InputParameters validParams()
Definition FileOutput.C:24
virtual bool shouldOutput() override
Checks if the output method should be executed.
Definition FileOutput.C:88
std::string _file_base
The base filename from the input paramaters.
Definition FileOutput.h:89
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object.
void addClassDescription(const std::string &doc_string)
This method adds a description of the class that will be displayed in the input file syntax dump.
T & set(const std::string &name, bool quiet_mode=false)
Returns a writable reference to the named parameters.
std::vector< std::filesystem::path > backup(const std::filesystem::path &folder_base)
Backs up the application to the folder folder_base.
Definition MooseApp.C:1721
static const std::string & checkpointSuffix()
The file suffix for the checkpoint mesh.
Definition MooseApp.C:3044
std::vector< std::filesystem::path > writeRestartableMetaData(const RestartableDataMapName &name, const std::filesystem::path &folder_base)
Writes the restartable meta data for name with a folder base of folder_base.
Definition MooseApp.C:2557
std::filesystem::path restartFolderBase(const std::filesystem::path &folder_base) const
The file suffix for restartable data.
Definition MooseApp.C:3059
const std::string & name() const
Get the name of the class.
Definition MooseBase.h:103
void paramError(const std::string &param, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
Definition MooseBase.h:457
virtual std::vector< std::filesystem::path > writeRecoveryFiles(const std::filesystem::path &file_base)
Write the mesh files needed for recovery/checkpointing.
Definition MooseMesh.C:2986
virtual bool isDistributedMesh() const
Returns the final Mesh distribution type.
Definition MooseMesh.h:1141
MooseApp & _app
The MOOSE application this is associated with.
Definition MooseBase.h:375
Real _wall_time_since_last_output
time in seconds since last output
Definition Output.h:286
Real _wall_time_interval
Target wall time between outputs in seconds.
Definition Output.h:241
ExecFlagEnum _execute_on
The common Execution types; this is used as the default execution type for everything except system i...
Definition Output.h:203
FEProblemBase * _problem_ptr
Pointer the the FEProblemBase object for output object (use this)
Definition Output.h:185
void setWallTimeIntervalFromCommandLineParam()
Function to set the wall time interval based on value of command line parameter (used for testing onl...
Definition Output.C:336
virtual int timeStep()
Get the current time step.
Definition Output.C:387
ExecFlagType _current_execute_flag
Current execute on flag.
Definition Output.h:211
virtual bool onInterval()
Returns true if the output interval is satisfied.
Definition Output.C:280
processor_id_type size() const
static void cleanup(const std::string &input_name, processor_id_type n_procs)
processor_id_type processor_id() const
const Parallel::Communicator & comm() const
volatile std::sig_atomic_t interrupt_signal_number
Used by the signal handler to determine if we should write a checkpoint file out at any point during ...
Definition Moose.C:913
int mkdir(const char *pathname)
A structure for storing the various output files associated with checkpoint output.
Definition Checkpoint.h:25
std::string checkpoint
Filename for CheckpointIO file (the mesh)
Definition Checkpoint.h:27
std::vector< std::filesystem::path > restart
Filenames for restartable data.
Definition Checkpoint.h:30