Lethe Open-Source Library version 1.2.0
Developer Guide
Loading...
Searching...
No Matches
simulation_control.cc
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) 2019-2026 The Lethe Authors
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
3
5#include <core/utilities.h>
6
7#include <algorithm>
8#include <cfloat>
9#include <cmath>
10#include <fstream>
11#include <iomanip>
12#include <sstream>
13
14
16 : method(param.method)
17 , assembly_method(param.method)
18 , current_time(0)
19 , previous_time(0)
20 , time_step(param.dt)
21 , initial_time_step(param.dt)
22 , end_time(param.time_end)
25 , end_iteration(param.iteration_end)
26 , number_mesh_adapt(param.number_mesh_adaptation)
27 , CFL(0)
28 , max_CFL(param.maxCFL)
29 , capillary_time_step_constraint(std::numeric_limits<double>::max())
34 , residual(DBL_MAX)
42 , output_path(param.output_folder)
44 , first_assembly(true)
45 , bdf_start_method(param.bdf_startup_method)
47{
49 time_step_vector[0] = param.dt;
50 time_step_vector[1] = param.dt;
51 time_step_vector[2] = param.dt;
52 time_step_vector[3] = param.dt;
53
54 // Resize the bdf_coefficients to ensure they have a default size;
56}
57
58void
60{
61 time_step = p_timestep;
62 // Store previous time step in table
63 for (unsigned int i_time = time_step_vector.size() - 1; i_time > 0; --i_time)
64 time_step_vector[i_time] = time_step_vector[i_time - 1];
65
66 // Calculate time step, right now this is a dummy function
67 time_step_vector[0] = p_timestep;
68}
69
70bool
72{
74 return false;
75 else
76 {
77 // Check if the current step number matches the output frequency
79 }
80}
81
82bool
84 const Parameters::MeshAdaptation &mesh_adaptation)
85{
87
88 if (mesh_adaptation.refinement_at_frequency)
90 get_iteration_number() % mesh_adaptation.frequency == 0;
91 else
93
94 return is_refinement_step;
95}
96
97void
99{
100 if (bdf_start_method ==
102 {
103 if (iteration_number <= 1 &&
105 {
109 }
110 else if (iteration_number == 2 &&
111 method ==
113 {
118 }
119 else if (iteration_number == 3 &&
120 method ==
122 {
126 }
127 else if (iteration_number <= 1 &&
128 method ==
130 {
134 }
135 else if (iteration_number == 2 &&
136 method ==
138 {
142 }
143 else if (iteration_number == 3 &&
144 method ==
146 {
150 (1 - 2 * startup_timestep_scaling));
151 }
152 else if (iteration_number == 4 &&
153 method ==
155 {
159 }
160 }
161 else
162 {
164 }
165}
166
167unsigned int
170{
172
173 switch (method)
174 {
175 case Method::steady:
176 case Method::steady_bdf:
177 case Method::bdf1:
178 case Method::bdf2:
179 case Method::bdf3:
180 return 1;
181
182 // When referencing to SDIRK methods the pattern used is
183 // sdirkOrderStage. For instance, sdirk22 indicates SDIRK method with
184 // order 2 and 2 stages
185 case Method::sdirk22:
186 return 2;
187
188 case Method::sdirk33:
189 return 3;
190
191 case Method::sdirk45:
192 return 5;
193
194 default:
195 AssertThrow(
196 false,
197 ExcMessage(
198 "Unknown TimeSteppingMethod passed to "
199 "get_number_of_stages(). Please add the number of stages of the new method in core/simulation_control.cc."));
200 return 1;
201 }
202}
203
204
205
206bool
211
212void
213SimulationControl::save(const std::string &prefix)
214{
215 std::string filename = prefix + ".simulationcontrol";
216 std::ofstream output(filename.c_str());
217 output << "Simulation control" << std::endl;
218
219 // We set the precision to 17. If the time-step is significantly smaller then
220 // the end time of the simulation, round off errors can become problematic.
221 output << std::fixed << std::setprecision(17);
222
223 for (unsigned int i = 0; i < time_step_vector.size(); ++i)
224 output << "dt_" << i << " " << time_step_vector[i] << std::endl;
225 output << "CFL " << CFL << std::endl;
226 output << "Time " << current_time << std::endl;
227 output << "Iter " << iteration_number << std::endl;
228}
229
230void
231SimulationControl::read(const std::string &prefix)
232{
233 std::string filename = prefix + ".simulationcontrol";
234 check_file_exists(filename,
235 "checkpoint file of the simulation control, given by "
236 "'subsection restart' - 'set filename'");
237 std::ifstream input(filename.c_str());
238
239 std::string buffer;
240 std::getline(input, buffer);
241 for (auto &time_step_value : time_step_vector)
242 input >> buffer >> time_step_value;
243 input >> buffer >> CFL;
244 input >> buffer >> current_time;
245 input >> buffer >> iteration_number;
246
247 // The previous time is only known once the next iteration is integrated.
248 // Until then, set it to the current time so that queries made before the
249 // first iteration after the restart (e.g., is_output_iteration) are defined.
251
252 // Fix time step to be the last time_step that was used
254}
255
256std::vector<double>
258 const std::string &prefix)
259{
260 std::string filename = prefix + ".simulationcontrol";
261 check_file_exists(filename,
262 "checkpoint file of the simulation control, given by "
263 "'subsection restart' - 'set filename'");
264 std::ifstream input(filename.c_str());
265
266 // Store the time steps and last checkpointed time without modifying the
267 // simulation control information
268 std::vector<double> time_steps(time_step_vector.size());
269 double last_checkpointed_time;
270
271 // Returned vector with the last checkpointed time and time step
272 std::vector<double> simulation_control_info(2);
273
274 std::string buffer;
275 std::getline(input, buffer);
276 for (unsigned int i = 0; i < time_step_vector.size(); ++i)
277 input >> buffer >> time_steps[i];
278 input >> buffer >> buffer;
279 input >> buffer >> last_checkpointed_time;
280 input >> buffer >> buffer;
281
282 // Fix the current time as final checkpointed time
283 simulation_control_info[0] = last_checkpointed_time;
284
285 // Fix time step to be the last time_step that was used
286 simulation_control_info[1] = time_steps[0];
287
288 return simulation_control_info;
289}
290
311
312void
313SimulationControlTransient::print_progression(const ConditionalOStream &pcout)
314{
316 return;
317
318 pcout << std::endl;
319
320 std::stringstream ss;
321 ss << std::setprecision(this->log_precision);
322
323 // Copy information into a string stream
324 ss << "Transient iteration: " << std::setw(8) << std::left << iteration_number
325 << " Time: " << std::setw(8) << std::left << current_time
326 << " Time step: " << std::setw(8) << std::left << time_step
327 << " CFL: " << std::setw(8) << std::left << this->get_CFL();
328
329 unsigned int first_line_size = ss.str().size();
330
332 {
333 // Get the length of blank spaces to add
334 std::stringstream cfl_ss;
335 cfl_ss << std::setprecision(this->log_precision) << std::setw(8)
336 << std::left << this->get_CFL();
337 const unsigned int cfl_value_length = cfl_ss.str().size();
338 const unsigned int blank_space_length =
339 first_line_size - std::strlen(" CFL: ") - cfl_value_length;
340
341 // Print CTR value on a new line, under CFL
342 ss << '\n'
343 << std::setw(blank_space_length) << " "
344 << " CTR: " << std::setw(8) << std::left
346 }
347
348 // Announce string
349 announce_string(pcout, ss.str(), first_line_size, '*');
350}
351
352bool
354{
355 if (!is_at_end())
356 {
357 // We store the value of the time at the previous iteration
358 // before we change the current time.
360
361 // Reset the first assembly to true to indicate that we are starting
362 // the time step. This variable is used to monitor the initial residual
363 // of the set of non-linear equation which can be used for example in
364 // steady-bdf methods
365 first_assembly = true;
366
367 // We increment the iteration number since its initial value is zero.
369
370 // Update assembly method is used to change the time marching method
371 // in the case where the methods are not self-starting (all BDF of orders
372 // 2 and above)
376
377 // Calculate CTR to print on the console if capillary time-step constraint
378 // is enabled
380 {
382 }
383
384 if (is_bdf())
386 return true;
387 }
388
389 else
390 return false;
391}
392
393bool
395{
398
399 double floating_point_margin = std::max(1e-6 * time_step, 1e-12 * end_time);
400 return current_time >= (end_time - floating_point_margin);
401}
402
403double
405{
406 double new_time_step = time_step;
407
409 {
410 new_time_step = time_step * adaptative_time_step_scaling;
411 if (adapt_with_cfl && CFL > 0 &&
413 new_time_step = time_step * max_CFL / CFL;
414
415 new_time_step = std::min(new_time_step, max_dt);
416
418 {
419 double capillary_time_step =
421 new_time_step = std::min(new_time_step, capillary_time_step);
422 }
423 }
424
425 // Ensure that the time step for the last iteration is kept regardless of the
426 // end time set. The end time is also irrelevant when the simulation ends at a
427 // given iteration, in which case the time step is never clipped.
430 return new_time_step;
431
432 // Modify last time step to ensure that the last iteration is exactly the end
433 // time specified in the parameter file
434 if (current_time + new_time_step > end_time)
435 new_time_step = end_time - current_time;
436
437 return new_time_step;
438}
439
440bool
442{
443 // If iteration control the only options are to not print or at certain
444 // frequency of iterations for the time interval given. In this mode, we also
445 // always output the last iteration in the simulation.
447 {
449 return false;
450 else
451 {
452 // Check if the current step number matches the following condition:
453 // (The step number matches the output frequency OR is the last
454 // time step) AND the current time is within the output time interval
456 is_at_end()) &&
459 }
460 }
461
462 // If time control there are several options:
463
464 // Case 1. A specific output time frequency is given (with or without a
465 // specific time interval). The output times are
466 // t_k = t_start + k * output_time_frequency, where t_start is the lower bound
467 // of the output time interval. This criterion only depends on the current
468 // and previous times, so it returns the same result when it is called
469 // several times within the same iteration.
470 if (output_time_frequency != -1)
471 {
472 const double start_time = output_time_interval[0];
473
474 // The tolerance prevents round-off errors accumulated in the current time
475 // from delaying or skipping an output. It is proportional to the output
476 // time frequency, and not to the time step, so that it is the same at
477 // every iteration. Consequently, every output time is attributed to
478 // exactly one iteration, even when the time step changes.
479 const double margin = output_time_tolerance * output_time_frequency;
480
481 // We never output outside of the output time interval. The same
482 // tolerance is used so that the bounds of the interval are considered as
483 // reached when they are reached up to round-off errors.
484 if (current_time < start_time - margin ||
486 return false;
487
488 // As for iteration control, we always output the initial iteration and
489 // the last iteration of the simulation, as long as they lie within the
490 // output time interval (checked above)
491 if (iteration_number == 0 || is_at_end())
492 return true;
493
494 // We output if the time step that led to the current time reached or
495 // crossed an output time
496 const auto output_time_index = [&](const double time) {
497 return std::floor((time - start_time + margin) / output_time_frequency);
498 };
499
500 return output_time_index(current_time) > output_time_index(previous_time);
501 }
502
503 // Time reached at the end of the next time step. It is used by the two
504 // remaining cases: since the specific output times and the bounds of the
505 // output time interval do not necessarily correspond to the time of an
506 // iteration, we also output the iteration that precedes them.
507 const double next_time = current_time + calculate_time_step();
508
509 // Case 2. One or several specific output times are given, in any order. We
510 // output the iteration whose time step reaches or crosses one of these times,
511 // and the iteration that precedes it, i.e., the iteration whose next time
512 // step reaches or crosses it. Both conditions amount to an output time lying
513 // within (previous_time, next_time]. At the initial iteration, there is no
514 // previous time step, so only the output times equal to the current time are
515 // considered as reached. The tolerance prevents round-off errors accumulated
516 // in the current time from delaying an output by one iteration. This
517 // criterion only depends on the current, previous and next times, so it
518 // returns the same result when it is called several times within the same
519 // iteration.
520 if (!output_times_vector.empty() && output_times_vector[0] != -1)
521 {
522 const double margin = output_time_tolerance * time_step;
523 const double lower_bound = (iteration_number == 0) ?
524 current_time - margin :
525 previous_time + margin;
526 const double upper_bound = next_time + margin;
527
528 return std::ranges::any_of(output_times_vector,
529 [&](const double output_time) {
530 return output_time > lower_bound &&
531 output_time <= upper_bound;
532 });
533 }
534
535 // Case 3. Only a specific time interval is specified
536 const double lower_bound = output_time_interval[0];
537 const double upper_bound = output_time_interval[1];
538
539 // We output if the current time is within the interval
540 bool is_output_time =
541 (current_time >= lower_bound && current_time <= upper_bound);
542
543 // We always write one step before, in case the interval lower bound does not
544 // correspond exactly to a time iteration performed (due to time step)
546 is_output_time = true;
547
548 // We always write one step after, in case the interval upper bound does not
549 // correspond exactly to a time iteration performed (due to time step)
550 if (current_time >= upper_bound && previous_time < upper_bound)
551 is_output_time = true;
552
553 return is_output_time;
554}
555
556void
557SimulationControlTransient::read(const std::string &prefix)
558{
559 // Checkpoints written by previous versions of Lethe with time output control
560 // contain an additional line with the index of the next specific output time.
561 // This line follows the information read here and is ignored, since the
562 // output criterion no longer depends on it.
564
566 {
567 // Fix the time step to the new provided value.
568 // We understand that users may wish to override the checkpointed
569 // time-step value with another one.
570 const double old_CFL = CFL;
571 const double old_time_step = time_step;
573 set_CFL(old_CFL * initial_time_step / old_time_step);
574 }
575}
576
581
582void
584 const ConditionalOStream &pcout)
585{
587 return;
588
589 pcout << std::endl;
590 std::stringstream ss;
591
592 // Copy information into a string stream
593 ss << "Transient iteration: " << std::setw(8) << std::left << iteration_number
594 << " Time: " << std::setw(8) << std::left << current_time
595 << " Time step: " << std::setw(8) << std::left << time_step;
596
597 // Announce string
598 announce_string(pcout, ss.str(), '*');
599}
600
601
606
607bool
609{
610 if (!is_at_end())
611 {
614 // Fix the time to the iteration number so that pvd outputs
615 // do not lead to confusing results
617 return true;
618 }
619
620 else
621 return false;
622}
623
624void
625SimulationControlSteady::print_progression(const ConditionalOStream &pcout)
626{
628 return;
629
630 pcout << std::endl;
631 std::stringstream ss;
632
633 // Copy information into a string stream
634 ss << "Steady iteration: " << std::setw(8) << std::right << iteration_number
635 << "/" << number_mesh_adapt + 1;
636
637 // Announce string
638 announce_string(pcout, ss.str(), '*');
639}
640
641bool
646
651
652void
654 const ConditionalOStream &pcout)
655{
657 return;
658
659 pcout << std::endl;
660
661 std::stringstream ss;
662 ss << std::setprecision(this->log_precision);
663
664 // Copy information into a string stream
665 ss << "Pseudo steady-state iteration: " << std::setw(8) << std::left
666 << iteration_number << " Time: " << std::setw(8) << std::left
667 << current_time << " Time step: " << std::setw(8) << std::left << time_step
668 << " CFL: " << std::setw(8) << std::left << SimulationControl::get_CFL();
669
670 // Announce string
671 announce_string(pcout, ss.str(), '*');
672}
673
674bool
679
682 Particles::ParticleHandler<3> &input_photon_handler)
683 : SimulationControl(param)
684 , photon_handler(input_photon_handler)
685{}
686
687bool
689{
690 if (!is_at_end())
691 {
693 return true;
694 }
695
696 else
697 return false;
698}
699bool
701{
702 return photon_handler.n_global_particles() == 0;
703}
704
705void
707{
708 pcout << "Iteration : " << iteration_number << std::endl
709 << "Remaining photon : " << photon_handler.n_global_particles()
710 << std::endl
711 << std::endl;
712}
SimulationControlAdjointSteady(const Parameters::SimulationControl &param)
Construct an adjoint steady-state simulation control object.
virtual bool is_at_end() override
End the simulation when the desired residual tolerance is reached.
virtual void print_progression(const ConditionalOStream &pcout) override
Print the current progress status of the adjoint simulation.
void print_progression(const ConditionalOStream &pcout) override
Print the current progress status of the ray tracing simulation.
Particles::ParticleHandler< 3 > & photon_handler
Reference to the photon handler used during the ray-tracing simulation.
bool is_at_end() override
End the simulation when there are no longer any photons in the triangulation.
virtual bool integrate() override
Proceed with the simulation until the end condition is reached.
SimulationControlRayTracing(const Parameters::SimulationControl &param, Particles::ParticleHandler< 3 > &input_photon_handler)
Construct a ray tracing simulation control object.
virtual bool integrate() override
Proceed with the simulation until the end condition is reached.
SimulationControlSteady(const Parameters::SimulationControl &param)
Construct a steady-state simulation control object.
virtual bool is_at_end() override
End the simulation when the number of mesh adaptations is reached.
virtual void print_progression(const ConditionalOStream &pcout) override
Print the current progress status of the steady-state simulation.
SimulationControlTransientDEM(const Parameters::SimulationControl &param)
Construct a DEM transient simulation control object.
virtual void print_progression(const ConditionalOStream &pcout) override
Print the current progress status of the DEM simulation.
bool override_time_step_on_restart
Flag to override the time step with the set value upon restart.
SimulationControlTransient(const Parameters::SimulationControl &param)
Construct a transient simulation control object.
void read(const std::string &prefix) override
Read the simulation control information from a checkpoint file.
std::vector< double > output_time_interval
Time interval for output of transient iterations.
virtual void print_progression(const ConditionalOStream &pcout) override
Print the current progress status of the simulation.
virtual double calculate_time_step() override
Calculate the next value of the time step.
std::vector< double > output_times_vector
Specific output times for time output control.
static constexpr double output_time_tolerance
Relative tolerance used to decide whether an output time has been reached.
virtual bool integrate() override
Proceed with the simulation until the end condition is reached.
virtual bool is_at_end() override
End the simulation when the end condition is reached.
virtual bool is_output_iteration() override
Check if the current iteration is an output iteration.
double max_dt
Maximum allowed time step.
Parameters::SimulationControl::EndControl end_control
End control type: iteration-based or time-based.
double adaptative_time_step_scaling
Time step scaling factor for adaptive time stepping.
Parameters::SimulationControl::OutputControl output_control
Output control type: iteration-based or time-based.
double output_time_frequency
Output frequency for time-based output control.
virtual bool is_output_iteration()
Check if the present iteration is an output iteration.
double startup_timestep_scaling
The time scaling used for small time steps at the startup of the simulation.
bool output_boundaries
Output boundaries flag.
virtual bool is_verbose_iteration()
Check if the present iteration is a verbose iteration.
void set_CFL(const double p_CFL)
Set the value of the CFL condition.
Vector< double > bdf_coefs
BDF coefficients used for time-stepping methods.
double current_time
Time of the current iteration being solved for.
double current_capillary_time_step_ratio
Computed ratio between the current time step and the capillary time-step constraint (Δt/Δt_σ).
bool is_refinement_step(const Parameters::MeshAdaptation &mesh_adaptation)
Check if the current step is a refinement step.
unsigned int get_iteration_number() const
Get current iteration number.
double stop_tolerance
Residual tolerance at which the simulation stops.
double get_current_time() const
Get current simulation time.
double CFL
Courant-Friedrich-Levy (CFL) condition value.
double initial_time_step
Initial time step given in the parameter file.
virtual void read(const std::string &prefix)
Read the simulation control information from a checkpoint file.
unsigned int group_files
Number of parallel files to generate for output.
void add_time_step(double p_timestep)
Add a time step and store the previous one in the history.
unsigned int output_iteration_frequency
Output iteration frequency.
unsigned int iteration_number
Iteration number.
static unsigned int get_number_of_stages(const Parameters::SimulationControl::TimeSteppingMethod &method)
Return the number of stages associated with the time-stepping method. For SDIRK methods,...
double capillary_time_step_constraint
Capillary time-step constraint for simulation time-stepping.
std::string output_path
Output directory path.
unsigned int number_mesh_adapt
Number of mesh adaptation iterations performed.
void update_assembly_method()
Define the assembly method to use while integrating.
double previous_time
Time of the previous iteration.
double max_CFL
Maximal CFL condition for adaptive time stepping.
std::string output_name
Output file name prefix.
bool time_step_independent_of_end_time
Boolean to keep the time step for the last iteration regardless of the end time.
std::vector< double > get_checkpointed_simulation_control_info(const std::string &prefix)
Read and return simulation control information from checkpoint without updating.
virtual void save(const std::string &prefix)
Save the simulation control information to a checkpoint file.
double residual
Current value of the norm of the right-hand side residual.
void set_current_time_step(const double new_time_step)
Manually force the value of the time step for the present iteration.
SimulationControl(const Parameters::SimulationControl &param)
Construct a SimulationControl object from parameter structure.
unsigned int log_precision
Log precision.
bool adapt_with_capillary_time_step_ratio
Enable adaptive time-stepping that respects the capillary time-step constraint.
double max_capillary_time_step_ratio
The user inputted ratio between the time step and the capillary time-step constraint (Δt/Δt_σ).
void set_current_capillary_time_step_ratio()
Set the current capillary time-step ratio (Δt/Δt_σ).
double time_step
Time step linking the previous iteration and the current time.
void update_bdf_coefficients()
Update the BDF coefficients.
Parameters::SimulationControl::BDFStartupMethods bdf_start_method
The method used to start high-order BDF schemes.
double end_time
Simulation end time.
bool first_assembly
Indicator to tell if this is the first assembly of a time step.
bool is_bdf() const
Establish if the method is a BDF method.
unsigned int subdivision
Number of mesh subdivisions to be used when outputting the results.
static constexpr unsigned int n_previous_time_steps
Number of time steps stored.
unsigned int end_iteration
Simulation end iteration.
unsigned int log_frequency
Log iteration frequency.
Parameters::SimulationControl::TimeSteppingMethod method
Time stepping method used for the simulation (BDF, SDIRK, steady, etc.).
double get_current_capillary_time_step_ratio() const
Get current capillary time-step ratio (Δt/Δt_σ).
double get_CFL() const
Get current CFL number.
std::vector< double > time_step_vector
Time step vector storing previous time steps.
Parameters::SimulationControl::TimeSteppingMethod assembly_method
Current method used for the present assembly.
void check_file_exists(const std::string &file_name, const std::string &file_description)
Verify that a file that Lethe must read exists and can be opened, and raise an error stated in the us...
Definition utilities.cc:225
void announce_string(const ConditionalOStream &pcout, const std::string &expression, const char delimiter='-')
Prints a string and then adds a line above and below made with dashes containing as many dashes as th...
Definition utilities.h:500
Simulation control classes for managing time-stepping and iteration control in Lethe.
MeshAdaption - Parameters that control dynamic mesh adaptation. Dynamic mesh adaptation in Lethe is v...
SimulationControl - Defines the parameter that control the flow of the simulation as well as the freq...
Definition parameters.h:87