15#include <deal.II/base/logstream.h>
16#include <deal.II/base/work_stream.h>
17#include <deal.II/numerics/vector_tools.h>
18#include <deal.II/numerics/vector_tools.templates.h>
30using namespace dealii;
34 template <
typename Description,
int dim,
typename Number>
36 : ParameterAcceptor(
"/A - TimeLoop")
37 , mpi_ensemble_(mpi_comm,
39 if constexpr (has_n_mpi_ensembles_v<Description>)
40 return Description::n_mpi_ensembles();
44 , hyperbolic_system_(mpi_ensemble_,
"/B - Equation")
45 , parabolic_system_(mpi_ensemble_,
"/B - Equation")
46 , discretization_(mpi_ensemble_,
"/C - Discretization")
47 , offline_data_(mpi_ensemble_, discretization_,
"/D - OfflineData")
48 , initial_values_(mpi_ensemble_,
54 , hyperbolic_module_(mpi_ensemble_,
58 "/F - HyperbolicModule")
59 , parabolic_module_(mpi_ensemble_,
64 "/G - ParabolicModule")
65 , time_integrator_(mpi_ensemble_,
69 "/H - TimeIntegrator")
70 , mesh_adaptor_(mpi_ensemble_,
74 hyperbolic_module_.initial_precomputed(),
75 hyperbolic_module_.alpha(),
77 , solution_transfer_(mpi_ensemble_,
82 , postprocessor_(mpi_ensemble_,
87 , vtu_output_(mpi_ensemble_,
92 hyperbolic_module_.initial_precomputed(),
93 hyperbolic_module_.alpha(),
94 mesh_adaptor_.smoothness_indicators(),
96 , quantities_(mpi_ensemble_,
105 add_parameter(
"basename", base_name_,
"Base name for all output files");
107 t_final_ = Number(5.);
108 add_parameter(
"final time", t_final_,
"Final time");
110 enforce_t_final_ =
false;
111 add_parameter(
"enforce final time",
113 "Boolean indicating whether the final time should be "
114 "enforced strictly. If set to true the last time step is "
115 "shortened so that the simulation ends precisely at t_final");
117 timer_granularity_ = Number(0.01);
118 add_parameter(
"timer granularity",
120 "The timer granularity specifies the time interval after "
121 "which compute, output, postprocessing, and mesh adaptation "
122 "routines are run. This \"baseline tick\" is further "
123 "modified by the corresponding \"*_multiplier\" options");
125 enable_output_full_ =
false;
126 add_parameter(
"enable output full",
128 "Write out full pvtu records. The frequency is determined by "
129 "\"timer granularity\" and \"timer output full multiplier\"");
131 enable_output_levelsets_ =
false;
133 "enable output levelsets",
134 enable_output_levelsets_,
135 "Write out levelsets pvtu records. The frequency is determined by "
136 "\"timer granularity\" and \"timer output levelsets multiplier\"");
138 enable_compute_error_ =
false;
139 add_parameter(
"enable compute error",
140 enable_compute_error_,
141 "Flag to control whether we compute the Linfty Linf_norm of "
142 "the difference to an analytic solution. Implemented only "
143 "for certain initial state configurations.");
145 enable_compute_quantities_ =
false;
147 "enable compute quantities",
148 enable_compute_quantities_,
149 "Flag to control whether we compute quantities of interest. The "
150 "frequency how often quantities are logged is determined by \"timer "
151 "granularity\" and \"timer compute quantities multiplier\"");
153 enable_mesh_adaptivity_ =
false;
155 "enable mesh adaptivity",
156 enable_mesh_adaptivity_,
157 "Flag to control whether we use an adaptive mesh refinement strategy. "
158 "The frequency how often we query MeshAdaptor::analyze() for deciding "
159 "on adapting the mesh is determined by \"timer granularity\" and "
160 "\"timer mesh refinement multiplier\"");
162 timer_output_full_multiplier_ = 1;
163 add_parameter(
"timer output full multiplier",
164 timer_output_full_multiplier_,
165 "Multiplicative modifier applied to \"timer granularity\" "
166 "that determines the full pvtu writeout granularity");
168 timer_output_levelsets_multiplier_ = 1;
169 add_parameter(
"timer output levelsets multiplier",
170 timer_output_levelsets_multiplier_,
171 "Multiplicative modifier applied to \"timer granularity\" "
172 "that determines the levelsets pvtu writeout granularity");
174 timer_compute_quantities_multiplier_ = 1;
176 "timer compute quantities multiplier",
177 timer_compute_quantities_multiplier_,
178 "Multiplicative modifier applied to \"timer granularity\" that "
179 "determines the writeout granularity for quantities of interest");
181 std::copy(std::begin(View::component_names),
182 std::end(View::component_names),
183 std::back_inserter(error_quantities_));
185 add_parameter(
"error quantities",
187 "List of conserved quantities used in the computation of the "
190 error_normalize_ =
true;
191 add_parameter(
"error normalize",
193 "Flag to control whether the error should be normalized by "
194 "the corresponding norm of the analytic solution.");
197 add_parameter(
"resume", resume_,
"Resume an interrupted computation");
199 resume_at_time_zero_ =
false;
200 add_parameter(
"resume at time zero",
201 resume_at_time_zero_,
202 "Resume from the latest checkpoint but set the time to t=0.");
204 terminal_update_interval_ = 5;
205 add_parameter(
"terminal update interval",
206 terminal_update_interval_,
207 "Number of seconds after which output statistics are "
208 "recomputed and printed on the terminal. Setting the "
209 "interval to zero disables terminal output.");
211 terminal_correct_for_hypertreadhing_ =
true;
213 "terminal correct for hyperthreading",
214 terminal_correct_for_hypertreadhing_,
215 "If set to true, the CPU throughput is corrected by dividing the total "
216 "consumed CPU time by a factor of 2. This correction is only active if "
217 "the number of threads (per MPI rank) is 2.");
219 checkpoint_update_interval_ = 0;
221 "checkpoint update interval",
222 checkpoint_update_interval_,
223 "Number of seconds after which a new checkpoint is written out to "
224 "disk. Setting the interval to zero disables checkpointing.");
227 add_parameter(
"debug command",
229 "If set to a nonempty string then the host environment's "
230 "command processor is invoked via std::system() with the "
231 "specified string as command parameter.");
233 debug_filename_ =
"";
234 add_parameter(
"debug filename",
236 "If set to a nonempty string then we output the contents of "
237 "this file at the end. This is mainly useful in the "
238 "testsuite to output files we wish to compare");
249 template <
typename Description,
int dim,
typename Number>
253 std::cout <<
"TimeLoop<dim, Number>::run()" << std::endl;
260 base_name_ensemble_ = base_name_;
261 if (mpi_ensemble_.n_ensembles() > 1) {
262 print_info(
"setting up MPI ensemble");
263 unsigned int digits =
264 dealii::Utilities::needed_digits(mpi_ensemble_.n_ensembles() - 1);
265 base_name_ensemble_ +=
267 dealii::Utilities::int_to_string(mpi_ensemble_.ensemble(), digits);
273 if (mpi_ensemble_.world_rank() == 0)
274 logfile_.open(base_name_ +
".log");
276 print_parameters(logfile_);
283 unsigned int timer_cycle = 0;
287 const auto prepare_compute_kernels = [&]() {
288 print_info(
"preparing compute kernels");
290 offline_data_.prepare(problem_dimension, n_precomputed_values);
292 hyperbolic_module_.prepare();
293 parabolic_module_.prepare();
294 time_integrator_.prepare();
295 mesh_adaptor_.prepare( t);
296 postprocessor_.prepare();
297 vtu_output_.prepare();
298 quantities_.prepare(base_name_ensemble_);
299 print_mpi_partition(logfile_);
301 if (mpi_ensemble_.ensemble_rank() == 0)
302 n_global_dofs_ = dealii::Utilities::MPI::sum(
303 offline_data_.dof_handler().n_dofs(),
304 mpi_ensemble_.ensemble_leader_communicator());
309 print_info(
"initializing data structures");
312 print_info(
"resume: reading mesh and loading state vector");
314 read_checkpoint(state_vector,
318 prepare_compute_kernels);
320 if (resume_at_time_zero_) {
327 print_info(
"creating mesh and interpolating initial values");
329 discretization_.prepare(base_name_ensemble_);
331 prepare_compute_kernels();
333 hyperbolic_module_.reinit_state_vector(state_vector);
334 parabolic_module_.reinit_state_vector(state_vector);
337 "time step [X] - interpolate data vectors");
338 std::get<0>(state_vector) =
339 initial_values_.get().interpolate_hyperbolic_vector();
345 print_device_information(logfile_);
348 time_integrator_.prepare_state_vector(state_vector, t);
354 Number last_terminal_output = terminal_update_interval_ == Number(0.)
355 ? std::numeric_limits<Number>::max()
357 Number last_checkpoint = checkpoint_update_interval_ == Number(0.)
358 ? std::numeric_limits<Number>::max()
361 print_info(
"entering main loop");
364 constexpr Number relax =
365 Number(1.) - Number(10.) * std::numeric_limits<Number>::epsilon();
367 unsigned int cycle = 1;
371 std::cout <<
"\n\n### cycle = " << cycle <<
" ###\n\n" << std::endl;
376 if (enable_compute_quantities_) {
378 quantities_.accumulate(state_vector, t);
383 if (t >= relax * timer_cycle * timer_granularity_) {
384 if (enable_compute_error_) {
394 "time step [X] - interpolate data vectors");
395 hyperbolic_module_.reinit_state_vector(analytic);
396 parabolic_module_.reinit_state_vector(analytic);
397 std::get<0>(analytic) =
398 initial_values_.get().interpolate_hyperbolic_vector(t);
401 time_integrator_.prepare_state_vector(analytic, t);
404 base_name_ensemble_ +
"-analytic_solution",
409 output(state_vector, base_name_ensemble_ +
"-solution", t, timer_cycle);
411 if (enable_compute_quantities_ &&
412 (timer_cycle % timer_compute_quantities_multiplier_ == 0)) {
414 quantities_.write_out(state_vector, t, timer_cycle);
422 if (t >= relax * t_final_)
427 if (enable_mesh_adaptivity_) {
430 "time step [X] - analyze for mesh adaptation");
432 mesh_adaptor_.analyze(state_vector, t, cycle);
435 if (mesh_adaptor_.need_mesh_adaptation()) {
438 "time step [X] - perform mesh adaptation");
439 print_info(
"performing mesh adaptation");
441 adapt_mesh_and_transfer_state_vector(state_vector,
442 prepare_compute_kernels);
445 time_integrator_.prepare_state_vector(state_vector, t);
451 const auto tau = time_integrator_.step(
455 ? std::min(t_final_, timer_cycle * timer_granularity_)
456 : std::numeric_limits<Number>::max());
460 time_integrator_.prepare_state_vector(state_vector, t);
467 "time step [X] _ - synchronization barriers");
469 Utilities::MPI::max(wall_time, mpi_ensemble_.world_communicator());
474 const bool write_to_log_file =
475 (terminal_update_interval_ != Number(0.)) &&
476 (t >= relax * timer_cycle * timer_granularity_);
478 const bool update_terminal =
479 (wall_time >= last_terminal_output + terminal_update_interval_);
481 if (write_to_log_file || update_terminal) {
483 "time step [X] _ - synchronization barriers");
484 print_cycle_statistics(cycle,
489 last_terminal_output = wall_time;
492 const bool update_checkpoint =
493 (wall_time >= last_checkpoint + checkpoint_update_interval_);
495 if (update_checkpoint) {
498 print_info(
"scheduling checkpointing");
499 write_checkpoint(state_vector, base_name_ensemble_, t, timer_cycle);
500 last_checkpoint = wall_time;
507 if (checkpoint_update_interval_ != Number(0.)) {
510 print_info(
"scheduling checkpointing");
511 write_checkpoint(state_vector, base_name_ensemble_, t, timer_cycle);
516 if (terminal_update_interval_ != Number(0.)) {
518 print_cycle_statistics(cycle,
526 if (enable_compute_error_) {
528 compute_error(state_vector, t);
535 if (mpi_ensemble_.world_rank() == 0) {
536 if (debug_command_ !=
"") {
537 auto result [[maybe_unused]] = std::system(debug_command_.c_str());
540 if (debug_filename_ !=
"") {
541 std::ifstream f(debug_filename_);
543 std::cout << f.rdbuf();
556 template <
typename Description,
int dim,
typename Number>
557 template <
typename Callable>
559 StateVector &state_vector,
560 const std::string &base_name,
562 unsigned int &timer_cycle,
563 const Callable &prepare_compute_kernels)
566 std::cout <<
"TimeLoop<dim, Number>::read_checkpoint()" << std::endl;
573 discretization_.refinement() = 0;
574 discretization_.prepare(base_name);
575 discretization_.triangulation().load(base_name +
"-checkpoint.mesh");
577 prepare_compute_kernels();
583 std::string name = base_name +
"-checkpoint";
585 unsigned int transfer_handle;
586 if (mpi_ensemble_.ensemble_rank() == 0) {
587 std::string meta = name +
".metadata";
589 std::ifstream file(meta, std::ios::binary);
590 boost::archive::binary_iarchive ia(file);
591 ia >> t >> timer_cycle >> transfer_handle;
595 if constexpr (std::is_same_v<Number, double>)
597 &t, 1, MPI_DOUBLE, 0, mpi_ensemble_.ensemble_communicator());
600 MPI_Bcast(&t, 1, MPI_FLOAT, 0, mpi_ensemble_.ensemble_communicator());
601 AssertThrowMPI(ierr);
603 ierr = MPI_Bcast(&timer_cycle,
607 mpi_ensemble_.ensemble_communicator());
608 AssertThrowMPI(ierr);
610 ierr = MPI_Bcast(&transfer_handle,
614 mpi_ensemble_.ensemble_communicator());
615 AssertThrowMPI(ierr);
619 hyperbolic_module_.reinit_state_vector(state_vector);
620 parabolic_module_.reinit_state_vector(state_vector);
622 solution_transfer_.set_handle(transfer_handle);
623 solution_transfer_.project(state_vector);
624 solution_transfer_.reset_handle();
627 time_integrator_.prepare_state_vector(state_vector, t);
631 template <
typename Description,
int dim,
typename Number>
632 void TimeLoop<Description, dim, Number>::write_checkpoint(
633 const StateVector &state_vector,
634 const std::string &base_name,
636 const unsigned int &timer_cycle)
639 std::cout <<
"TimeLoop<dim, Number>::write_checkpoint()" << std::endl;
642 solution_transfer_.prepare_projection(state_vector);
643 const auto transfer_handle = solution_transfer_.get_handle();
644 solution_transfer_.reset_handle();
646 std::string name = base_name +
"-checkpoint";
648 if (mpi_ensemble_.ensemble_rank() == 0) {
649 for (
const std::string suffix :
650 {
".mesh",
".mesh_fixed.data",
".mesh.info",
".metadata"})
651 if (std::filesystem::exists(name + suffix))
652 std::filesystem::rename(name + suffix, name + suffix +
"~");
655 const auto &triangulation = discretization_.triangulation();
656 triangulation.save(name +
".mesh");
662 if (mpi_ensemble_.ensemble_rank() == 0) {
663 std::string meta = name +
".metadata";
664 std::ofstream file(meta, std::ios::binary | std::ios::trunc);
665 boost::archive::binary_oarchive oa(file);
666 oa << t << timer_cycle << transfer_handle;
669 const int ierr = MPI_Barrier(mpi_ensemble_.ensemble_communicator());
670 AssertThrowMPI(ierr);
674 template <
typename Description,
int dim,
typename Number>
675 template <
typename Callable>
676 void TimeLoop<Description, dim, Number>::adapt_mesh_and_transfer_state_vector(
677 StateVector &state_vector,
const Callable &prepare_compute_kernels)
680 std::cout <<
"TimeLoop<dim, Number>::adapt_mesh_and_transfer_state_vector()"
684 AssertThrow(mpi_ensemble_.n_ensembles() == 1, dealii::ExcNotImplemented());
690 auto &triangulation = discretization_.triangulation();
691 mesh_adaptor_.mark_cells_for_coarsening_and_refinement(triangulation);
693 triangulation.prepare_coarsening_and_refinement();
695 solution_transfer_.prepare_projection(state_vector);
699 triangulation.execute_coarsening_and_refinement();
700 prepare_compute_kernels();
702 hyperbolic_module_.reinit_state_vector(state_vector);
703 parabolic_module_.reinit_state_vector(state_vector);
705 solution_transfer_.project(state_vector);
706 solution_transfer_.reset_handle();
711 template <
typename Description,
int dim,
typename Number>
712 void TimeLoop<Description, dim, Number>::compute_error(
713 const StateVector &state_vector,
const Number t)
716 std::cout <<
"TimeLoop<dim, Number>::compute_error()" << std::endl;
721 ComputingTimer::Scope scope(
"time step [X] _ - memory space transfers");
722 const auto &[U, precomputed, parabolic] = state_vector;
723 U.template copy_to_memory_space<dealii::MemorySpace::Host>();
726 Vector<Number> difference_per_cell(
727 discretization_.triangulation().n_active_cells());
729 Number linf_norm = 0.;
733 const auto analytic_U =
734 initial_values_.get().interpolate_hyperbolic_vector(t);
735 const auto &U = std::get<0>(state_vector);
740 analytic_component.reinit(offline_data_.scalar_partitioner());
741 error_component.reinit(offline_data_.scalar_partitioner());
744 for (
const auto &entry : error_quantities_) {
745 const auto &names = View::component_names;
746 const auto pos = std::find(std::begin(names), std::end(names), entry);
747 if (pos == std::end(names)) {
750 dealii::ExcMessage(
"Unknown component name »" + entry +
"«"));
754 const auto index = std::distance(std::begin(names), pos);
756 analytic_U.view().extract_component(analytic_component, index);
760 Number linf_norm_analytic = 0.;
761 Number l1_norm_analytic = 0.;
762 Number l2_norm_analytic = 0.;
764 if (error_normalize_) {
765 linf_norm_analytic = analytic_component.linfty_norm();
767 VectorTools::integrate_difference(
768 discretization_.mapping(),
769 offline_data_.dof_handler(),
771 Functions::ZeroFunction<dim, Number>(),
773 discretization_.quadrature_high_order(),
774 VectorTools::L1_norm);
777 Utilities::MPI::sum(difference_per_cell.l1_norm(),
778 mpi_ensemble_.ensemble_communicator());
780 VectorTools::integrate_difference(
781 discretization_.mapping(),
782 offline_data_.dof_handler(),
784 Functions::ZeroFunction<dim, Number>(),
786 discretization_.quadrature_high_order(),
787 VectorTools::L2_norm);
789 l2_norm_analytic = Number(std::sqrt(
790 Utilities::MPI::sum(std::pow(difference_per_cell.l2_norm(), 2),
791 mpi_ensemble_.ensemble_communicator())));
796 U.view().extract_component(error_component, index);
798 offline_data_.affine_constraints().distribute(error_component);
799 error_component.update_ghost_values();
800 error_component -= analytic_component;
802 const Number linf_norm_error = error_component.linfty_norm();
804 VectorTools::integrate_difference(discretization_.mapping(),
805 offline_data_.dof_handler(),
807 Functions::ZeroFunction<dim, Number>(),
809 discretization_.quadrature_high_order(),
810 VectorTools::L1_norm);
812 const Number l1_norm_error = Utilities::MPI::sum(
813 difference_per_cell.l1_norm(), mpi_ensemble_.ensemble_communicator());
815 VectorTools::integrate_difference(discretization_.mapping(),
816 offline_data_.dof_handler(),
818 Functions::ZeroFunction<dim, Number>(),
820 discretization_.quadrature_high_order(),
821 VectorTools::L2_norm);
823 const Number l2_norm_error = Number(std::sqrt(
824 Utilities::MPI::sum(std::pow(difference_per_cell.l2_norm(), 2),
825 mpi_ensemble_.ensemble_communicator())));
827 if (error_normalize_) {
828 linf_norm += linf_norm_error / linf_norm_analytic;
829 l1_norm += l1_norm_error / l1_norm_analytic;
830 l2_norm += l2_norm_error / l2_norm_analytic;
832 linf_norm += linf_norm_error;
833 l1_norm += l1_norm_error;
834 l2_norm += l2_norm_error;
838 if (mpi_ensemble_.ensemble_rank() != 0)
846 if (mpi_ensemble_.n_ensembles() > 1) {
847 linf_norm = Utilities::MPI::sum(
848 linf_norm, mpi_ensemble_.ensemble_leader_communicator());
849 l1_norm = Utilities::MPI::sum(
850 l1_norm, mpi_ensemble_.ensemble_leader_communicator());
851 l2_norm = Utilities::MPI::sum(
852 l2_norm, mpi_ensemble_.ensemble_leader_communicator());
855 if (mpi_ensemble_.world_rank() != 0)
858 logfile_ << std::endl <<
"Computed errors:" << std::endl << std::endl;
859 logfile_ << std::setprecision(16);
861 std::string description =
862 error_normalize_ ?
"Normalized consolidated" :
"Consolidated";
864 logfile_ << description +
" Linf, L1, and L2 errors at final time \n";
865 logfile_ << std::setprecision(16);
866 logfile_ <<
"#dofs = " << n_global_dofs_ << std::endl;
867 logfile_ <<
"t = " << t << std::endl;
868 logfile_ <<
"Linf = " << linf_norm << std::endl;
869 logfile_ <<
"L1 = " << l1_norm << std::endl;
870 logfile_ <<
"L2 = " << l2_norm << std::endl;
872 std::cout << description +
" Linf, L1, and L2 errors at final time \n";
873 std::cout << std::setprecision(16);
874 std::cout <<
"#dofs = " << n_global_dofs_ << std::endl;
875 std::cout <<
"t = " << t << std::endl;
876 std::cout <<
"Linf = " << linf_norm << std::endl;
877 std::cout <<
"L1 = " << l1_norm << std::endl;
878 std::cout <<
"L2 = " << l2_norm << std::endl;
882 template <
typename Description,
int dim,
typename Number>
884 TimeLoop<Description, dim, Number>::output(
const StateVector &state_vector,
885 const std::string &name,
887 const unsigned int cycle)
890 std::cout <<
"TimeLoop<dim, Number>::output(t = " << t <<
")" << std::endl;
893 const bool do_full_output =
894 (cycle % timer_output_full_multiplier_ == 0) && enable_output_full_;
895 const bool do_levelsets =
896 (cycle % timer_output_levelsets_multiplier_ == 0) &&
897 enable_output_levelsets_;
900 if (!(do_full_output || do_levelsets))
905 ComputingTimer::Scope scope(
"time step [X] - perform vtu output");
906 print_info(
"scheduling output");
908 postprocessor_.compute(state_vector);
915 postprocessor_.reset_bounds();
918 mesh_adaptor_.compute_smoothness_indicators(state_vector);
920 vtu_output_.schedule_output(
921 state_vector, name, t, cycle, do_full_output, do_levelsets);
932 template <
typename Description,
int dim,
typename Number>
934 TimeLoop<Description, dim, Number>::print_parameters(std::ostream &stream)
936 if (mpi_ensemble_.world_rank() != 0)
945 stream << std::endl <<
"Run time parameters:" << std::endl << std::endl;
946 ParameterAcceptor::prm.print_parameters(
947 stream, ParameterHandler::OutputStyle::ShortPRM);
952 std::ofstream output(base_name_ +
"-parameters.prm");
953 ParameterAcceptor::prm.print_parameters(output, ParameterHandler::ShortPRM);
957 template <
typename Description,
int dim,
typename Number>
959 TimeLoop<Description, dim, Number>::print_mpi_partition(std::ostream &stream)
968 std::vector<double> values = {
969 (double)offline_data_.n_export_indices(),
970 (double)offline_data_.n_locally_internal(),
971 (double)offline_data_.n_locally_owned(),
972 (double)offline_data_.n_locally_relevant(),
973 (double)offline_data_.n_export_indices() /
974 (double)offline_data_.n_locally_relevant(),
975 (double)offline_data_.n_locally_internal() /
976 (double)offline_data_.n_locally_relevant(),
977 (double)offline_data_.n_locally_owned() /
978 (double)offline_data_.n_locally_relevant()};
982 Utilities::MPI::min_max_avg(values, mpi_ensemble_.world_communicator());
984 if (mpi_ensemble_.world_rank() != 0)
987 std::ostringstream output;
990 dealii::Utilities::needed_digits(mpi_ensemble_.n_world_ranks());
992 const auto print_snippet = [&output, n](
const std::string &name,
993 const auto &values) {
994 output << name <<
": ";
996 output << std::setw(9) << (
unsigned int)values.min
997 <<
" [p" << std::setw(n) << values.min_index <<
"] "
998 << std::setw(9) << (
unsigned int)values.avg <<
" "
999 << std::setw(9) << (
unsigned int)values.max
1000 <<
" [p" << std::setw(n) << values.max_index <<
"]";
1004 const auto print_percentages = [&output, n](
const auto &percentages) {
1005 output << std::endl <<
" ";
1006 output <<
" (" << std::setw(3) << std::setprecision(2)
1007 << percentages.min * 100 <<
"% )"
1008 <<
" [p" << std::setw(n) << percentages.min_index <<
"] "
1009 <<
" (" << std::setw(3) << std::setprecision(2)
1010 << percentages.avg * 100 <<
"% )"
1012 <<
" (" << std::setw(3) << std::setprecision(2)
1013 << percentages.max * 100 <<
"% )"
1014 <<
" [p" << std::setw(n) << percentages.max_index <<
"]";
1017 output << std::endl << std::endl <<
"Partition: ";
1018 print_snippet(
"exp", data[0]);
1019 print_percentages(data[4]);
1021 output << std::endl <<
" ";
1022 print_snippet(
"int", data[1]);
1023 print_percentages(data[5]);
1025 output << std::endl <<
" ";
1026 print_snippet(
"own", data[2]);
1027 print_percentages(data[6]);
1029 output << std::endl <<
" ";
1030 print_snippet(
"rel", data[3]);
1032 stream << output.str() << std::endl;
1036 template <
typename Description,
int dim,
typename Number>
1037 void TimeLoop<Description, dim, Number>::print_device_information(
1038 std::ostream &stream)
1044#if defined(KOKKOS_ENABLE_CUDA) || defined(KOKKOS_ENABLE_HIP)
1051 using Device = std::pair<std::string, int>;
1053 const Device local{dealii::Utilities::System::get_hostname(),
1054 Kokkos::device_id()};
1055 const auto all = dealii::Utilities::MPI::all_gather(
1056 mpi_ensemble_.world_communicator(), local);
1057 n_devices_ = std::set<Device>(all.begin(), all.end()).size();
1061 if (mpi_ensemble_.world_rank() != 0)
1064 std::ostringstream output;
1066 const auto entry [[maybe_unused]] =
1067 [&output](
const std::string &label) -> std::ostream & {
1069 <<
" " << std::left << std::setw(22) << label;
1075 <<
"Device: " << std::left << std::setw(22) <<
"backend"
1076 << Kokkos::DefaultExecutionSpace::name();
1083#if defined(KOKKOS_ENABLE_CUDA)
1084 const auto &prop = Kokkos::Cuda{}.cuda_device_prop();
1086 entry(
"device") << prop.name;
1087 entry(
"compute capability") << prop.major <<
"." << prop.minor;
1088 entry(
"device id") << Kokkos::device_id() <<
" of "
1089 << Kokkos::num_devices();
1090 entry(
"devices in use")
1091 << n_devices_ <<
" on " << mpi_ensemble_.n_world_ranks() <<
" ranks";
1092 entry(
"multiprocessors") << prop.multiProcessorCount;
1093 entry(
"warp size") << prop.warpSize <<
" (hardware), " <<
warp_size
1094 <<
" (ryujin::warp_size)";
1095 entry(
"threads per SM")
1096 << prop.maxThreadsPerMultiProcessor <<
" ("
1097 << prop.maxThreadsPerMultiProcessor / prop.warpSize <<
" warps)";
1098 entry(
"threads per block") << prop.maxThreadsPerBlock;
1099 entry(
"concurrency") << Kokkos::DefaultExecutionSpace{}.concurrency();
1100 entry(
"registers per SM") << prop.regsPerBlock;
1101 entry(
"shared memory per SM")
1102 << prop.sharedMemPerMultiprocessor / 1024 <<
" KiB";
1103 entry(
"L2 cache") << prop.l2CacheSize / 1024 / 1024 <<
" MiB";
1104 entry(
"global memory") << prop.totalGlobalMem / 1024 / 1024 <<
" MiB";
1106#elif defined(KOKKOS_ENABLE_HIP)
1107 const auto &prop = Kokkos::HIP::hip_device_prop();
1109 entry(
"device") << prop.name;
1110 entry(
"architecture") << prop.gcnArchName;
1111 entry(
"device id") << Kokkos::device_id() <<
" of "
1112 << Kokkos::num_devices();
1113 entry(
"devices in use")
1114 << n_devices_ <<
" on " << mpi_ensemble_.n_world_ranks() <<
" ranks";
1115 entry(
"compute units") << prop.multiProcessorCount;
1116 entry(
"warp size") << prop.warpSize <<
" (hardware), " <<
warp_size
1117 <<
" (ryujin::warp_size)";
1118 entry(
"threads per CU")
1119 << prop.maxThreadsPerMultiProcessor <<
" ("
1120 << prop.maxThreadsPerMultiProcessor / prop.warpSize <<
" warps)";
1121 entry(
"threads per block") << prop.maxThreadsPerBlock;
1122 entry(
"concurrency") << Kokkos::DefaultExecutionSpace{}.concurrency();
1123 entry(
"registers per block") << prop.regsPerBlock;
1124 entry(
"shared memory per block") << prop.sharedMemPerBlock / 1024 <<
" KiB";
1125 entry(
"L2 cache") << prop.l2CacheSize / 1024 / 1024 <<
" MiB";
1126 entry(
"global memory") << prop.totalGlobalMem / 1024 / 1024 <<
" MiB";
1129 stream << output.str() << std::endl;
1133 template <
typename Description,
int dim,
typename Number>
1134 void TimeLoop<Description, dim, Number>::print_info(
const std::string &header)
1136 if (mpi_ensemble_.world_rank() != 0)
1139 std::cout <<
"[INFO] " << header << std::endl;
1143 template <
typename Description,
int dim,
typename Number>
1145 TimeLoop<Description, dim, Number>::print_head(
const std::string &header,
1146 const std::string &secondary,
1147 std::ostream &stream)
1149 if (mpi_ensemble_.world_rank() != 0)
1152 const int header_size = header.size();
1153 const auto padded_header =
1154 std::string(std::max(0, 34 - header_size) / 2,
' ') + header +
1155 std::string(std::max(0, 35 - header_size) / 2,
' ');
1157 const int secondary_size = secondary.size();
1158 const auto padded_secondary =
1159 std::string(std::max(0, 34 - secondary_size) / 2,
' ') + secondary +
1160 std::string(std::max(0, 35 - secondary_size) / 2,
' ');
1164 stream <<
" ####################################################\n";
1165 stream <<
" #########" << padded_header <<
"#########\n";
1166 stream <<
" #########" << padded_secondary <<
"#########\n";
1167 stream <<
" ####################################################\n";
1168 stream << std::endl;
1173 template <
typename Description,
int dim,
typename Number>
1174 void TimeLoop<Description, dim, Number>::print_information(
1175 unsigned int timer_cycle,
1176 Number last_checkpoint,
1177 std::ostream &stream,
1180 static const std::string backend_name = [] {
1181 const auto precision = [] {
1182 if constexpr (std::is_same_v<Number, double>)
1183 return std::string(
"FP64");
1184 else if constexpr (std::is_same_v<Number, float>)
1185 return std::string(
"FP32");
1190 constexpr auto simd_size = VectorizedArray<Number>::size();
1193 return "GPU, " + precision +
", warp size " + std::to_string(
warp_size);
1194 else if constexpr (simd_size == 1)
1195 return "scalar, " + precision;
1197 return "SIMD, " + precision +
", width " + std::to_string(simd_size);
1200 stream <<
"Information: (HYP) " << hyperbolic_system_.get().problem_name;
1201 if constexpr (!ParabolicSystem::is_identity) {
1202 stream <<
"\n (PAR) " << parabolic_system_.get().problem_name;
1204 stream <<
"\n [" << base_name_ <<
"] ";
1205 if (mpi_ensemble_.n_ensembles() > 1) {
1206 stream << mpi_ensemble_.n_ensembles() <<
" ensembles ";
1208 stream <<
"with " << n_global_dofs_ <<
" Qdofs on "
1209 << mpi_ensemble_.n_world_ranks() <<
" ranks "
1210#if defined(WITH_OPENMP)
1211 <<
"/ " << omp_get_max_threads() <<
" threads "
1212#ifndef WITH_DEAL_II_THREADS
1213 <<
"[serial dealii] "
1215#elif defined(WITH_DEAL_II_THREADS)
1216 <<
"/ " << MultithreadInfo::n_threads() <<
" threads "
1218 <<
"<" << backend_name <<
">\n";
1220 stream <<
" Last output cycle "
1222 <<
" at t = " << timer_granularity_ * (timer_cycle - 1)
1225 if (enable_output_full_)
1227 if (enable_output_levelsets_)
1228 stream <<
"levelsets ";
1229 if (enable_compute_quantities_)
1230 stream <<
"quantities ";
1234 if (checkpoint_update_interval_ != Number(0.)) {
1235 const auto wall_time = Utilities::MPI::min_max_avg(
1237 mpi_ensemble_.world_communicator());
1240 stream <<
" Last checkpoint at FINAL TIME\n";
1242 stream <<
" Last checkpoint at wall time "
1243 << std::setprecision(2) << std::fixed << last_checkpoint
1244 <<
"s (" << std::setprecision(0)
1245 << std::max(0., wall_time.max - last_checkpoint)
1246 <<
"s ago, interval " << checkpoint_update_interval_ <<
"s)\n";
1252 template <
typename Description,
int dim,
typename Number>
1253 void TimeLoop<Description, dim, Number>::print_memory_statistics(
1254 std::ostream &stream)
1256 Utilities::System::MemoryStats stats;
1257 Utilities::System::get_memory_stats(stats);
1259 Utilities::MPI::MinMaxAvg data = Utilities::MPI::min_max_avg(
1260 stats.VmRSS / 1024., mpi_ensemble_.world_communicator());
1262 if (mpi_ensemble_.world_rank() != 0)
1265 std::ostringstream output;
1268 dealii::Utilities::needed_digits(mpi_ensemble_.n_world_ranks());
1270 output <<
"\nMemory: [MiB]"
1271 << std::setw(8) << data.min
1272 <<
" [p" << std::setw(n) << data.min_index <<
"] "
1273 << std::setw(8) << data.avg <<
" "
1274 << std::setw(8) << data.max
1275 <<
" [p" << std::setw(n) << data.max_index <<
"]";
1277 stream << output.str() << std::endl;
1281 template <
typename Description,
int dim,
typename Number>
1282 void TimeLoop<Description, dim, Number>::print_timers(std::ostream &stream)
1286 const auto equalize = [&]() {
1288 std::max_element(output.begin(),
1290 [](
const auto &left,
const auto &right) {
1291 return left.str().length() < right.str().length();
1293 const auto length = ptr->str().length();
1294 for (
auto &it : output)
1295 it << std::string(length - it.str().length() + 1,
' ');
1298 const auto print_wall_time = [&](
auto &timer,
auto &stream) {
1299 const auto wall_time = Utilities::MPI::min_max_avg(
1300 timer.wall_time(), mpi_ensemble_.world_communicator());
1302 constexpr auto eps = std::numeric_limits<double>::epsilon();
1307 const auto skew_negative = std::max(
1308 100. * (wall_time.min - wall_time.avg) / wall_time.avg - eps, -99.9);
1309 const auto skew_positive = std::min(
1310 100. * (wall_time.max - wall_time.avg) / wall_time.avg + eps, 99.9);
1312 stream << std::setprecision(2) << std::fixed << std::setw(9)
1313 << wall_time.avg <<
"s [sk: " << std::setprecision(1)
1314 << std::setw(5) << std::fixed << skew_negative <<
"%/"
1315 << std::setw(4) << std::fixed << skew_positive <<
"%]";
1317 dealii::Utilities::needed_digits(mpi_ensemble_.n_world_ranks());
1318 stream <<
" [p" << std::setw(n) << wall_time.min_index <<
"/"
1319 << wall_time.max_index <<
"]";
1322 const auto cpu_time_statistics = Utilities::MPI::min_max_avg(
1324 mpi_ensemble_.world_communicator());
1325 const double total_cpu_time = cpu_time_statistics.sum;
1327 const auto print_cpu_time =
1328 [&](
auto &timer,
auto &stream,
bool percentage) {
1329 const auto cpu_time = Utilities::MPI::min_max_avg(
1330 timer.cpu_time(), mpi_ensemble_.world_communicator());
1332 stream << std::setprecision(2) << std::fixed << std::setw(12)
1333 << cpu_time.sum <<
"s ";
1336 stream <<
"(" << std::setprecision(1) << std::setw(4)
1337 << 100. * cpu_time.sum / total_cpu_time <<
"%)";
1340 auto jt = output.begin();
1341 for (
auto &it : ComputingTimer::timers())
1342 *jt++ <<
" " << it.first;
1345 jt = output.begin();
1346 for (
auto &it : ComputingTimer::timers())
1347 print_wall_time(it.second, *jt++);
1350 jt = output.begin();
1351 bool compute_percentages =
false;
1352 for (
auto &it : ComputingTimer::timers()) {
1353 print_cpu_time(it.second, *jt++, compute_percentages);
1354 if (it.first.starts_with(
"time loop"))
1355 compute_percentages =
true;
1359 if (mpi_ensemble_.world_rank() != 0)
1362 stream << std::endl <<
"Timer statistics:\n";
1363 for (
auto &it : output)
1364 stream << it.str() << std::endl;
1368 template <
typename Description,
int dim,
typename Number>
1369 void TimeLoop<Description, dim, Number>::print_throughput(
1370 unsigned int cycle, Number t, std::ostream &stream,
bool final_time)
1376 static struct Data {
1377 unsigned int cycle = 0;
1379 double cpu_time_sum = 0.;
1380 double cpu_time_avg = 0.;
1381 double cpu_time_min = 0.;
1382 double cpu_time_max = 0.;
1383 double wall_time = 0.;
1384 double device_time_sum = 0.;
1385 } previous, current;
1387 static double time_per_second_exp = 0.;
1394 current.cycle = cycle;
1397 const auto wall_time_statistics = Utilities::MPI::min_max_avg(
1399 mpi_ensemble_.world_communicator());
1400 current.wall_time = wall_time_statistics.max;
1402 const auto cpu_time_statistics = Utilities::MPI::min_max_avg(
1404 mpi_ensemble_.world_communicator());
1405 current.cpu_time_sum = cpu_time_statistics.sum;
1406 current.cpu_time_avg = cpu_time_statistics.avg;
1407 current.cpu_time_min = cpu_time_statistics.min;
1408 current.cpu_time_max = cpu_time_statistics.max;
1411 const auto device_time_statistics = Utilities::MPI::min_max_avg(
1413 current.device_time_sum = device_time_statistics.sum;
1422 double delta_cycles = current.cycle - previous.cycle;
1423 const double cycles_per_second =
1424 delta_cycles / (current.wall_time - previous.wall_time);
1426 const auto efficiency = time_integrator_.efficiency();
1427 const auto n_dofs =
static_cast<double>(n_global_dofs_);
1429 double wall_m_dofs_per_sec = delta_cycles * n_dofs * efficiency / 1.e6 /
1430 (current.wall_time - previous.wall_time);
1432 const double delta_time =
1433 (current.t - previous.t) / (current.cycle - previous.cycle);
1434 const double time_per_second =
1435 (current.t - previous.t) / (current.wall_time - previous.wall_time);
1439 std::ostringstream output;
1442 output << std::endl;
1444 output <<
"Throughput:" << std::endl;
1449 const double delta_wall_time = current.wall_time - previous.wall_time;
1450 const double delta_device_time =
1451 current.device_time_sum - previous.device_time_sum;
1453 const double utilization =
1454 delta_device_time / (n_devices_ * delta_wall_time);
1456 const double device_m_dofs_per_sec =
1457 delta_cycles * n_dofs * efficiency / 1.e6 / delta_device_time;
1459 << std::setprecision(4) << std::fixed << device_m_dofs_per_sec
1460 <<
" MQ/s in compute kernels (on "
1461 << n_devices_ << (n_devices_ == 1 ?
" device)" :
" devices)")
1465 << std::setprecision(2) << std::fixed << delta_device_time
1467 << std::setprecision(2) << std::fixed << delta_wall_time
1469 << std::setprecision(1) << std::fixed << 100. * utilization
1470 <<
"% utilization ]" << std::endl;
1475 double cpu_m_dofs_per_sec = delta_cycles * n_dofs * efficiency / 1.e6 /
1476 (current.cpu_time_sum - previous.cpu_time_sum);
1479 const bool fudge_cpu_timings = terminal_correct_for_hypertreadhing_ &&
1480#if defined(WITH_OPENMP)
1481 (omp_get_max_threads() == 2);
1482#elif defined(WITH_DEAL_II_THREADS)
1483 (MultithreadInfo::n_threads() == 2);
1488 if (fudge_cpu_timings)
1489 cpu_m_dofs_per_sec *= 2.;
1491 double cpu_time_skew = (current.cpu_time_max - current.cpu_time_min -
1492 previous.cpu_time_max + previous.cpu_time_min) /
1495 cpu_time_skew = std::max(0., cpu_time_skew);
1497 const double cpu_time_skew_percentage =
1498 cpu_time_skew * delta_cycles /
1499 (current.cpu_time_avg - previous.cpu_time_avg);
1502 << (fudge_cpu_timings ?
"CPU*: " :
"CPU : ")
1503 << std::setprecision(4) << std::fixed << cpu_m_dofs_per_sec
1505 << std::scientific << 1. / cpu_m_dofs_per_sec * 1.e-6
1506 <<
" s/Qdof/substep)" << std::endl;
1508 output <<
" [cpu time skew: "
1509 << std::setprecision(2) << std::scientific << cpu_time_skew
1511 << std::setprecision(1) << std::setw(4) << std::setfill(
' ') << std::fixed
1512 << 100. * cpu_time_skew_percentage
1513 <<
"%)]" << std::endl;
1517 << std::setprecision(4) << std::fixed << wall_m_dofs_per_sec
1519 << std::scientific << 1. / wall_m_dofs_per_sec * 1.e-6
1520 <<
" s/Qdof/substep) ("
1521 << std::setprecision(2) << std::fixed << cycles_per_second
1522 <<
" cycles/s)" << std::endl;
1524 const auto &scheme = time_integrator_.time_stepping_scheme();
1526 << Patterns::Tools::Convert<TimeSteppingScheme>::to_string(scheme)
1528 << std::setprecision(2) << std::fixed << hyperbolic_module_.cfl()
1530 << std::setprecision(0) << std::fixed << hyperbolic_module_.n_restarts()
1532 << std::setprecision(0) << std::fixed << parabolic_module_.n_restarts()
1534 << std::setprecision(0) << std::fixed << hyperbolic_module_.n_warnings()
1536 << std::setprecision(0) << std::fixed << parabolic_module_.n_warnings()
1538 << std::setprecision(0) << std::fixed << hyperbolic_module_.n_corrections()
1540 << std::setprecision(0) << std::fixed << parabolic_module_.n_corrections()
1541 <<
" corr) ]" << std::endl;
1543 if constexpr (!ParabolicSystem::is_identity)
1544 parabolic_module_.print_solver_statistics(output);
1546 output <<
" [ dt = "
1547 << std::scientific << std::setprecision(2) << delta_time
1550 <<
" dt/s) ]" << std::endl;
1555 time_per_second_exp = 0.8 * time_per_second_exp + 0.2 * time_per_second;
1556 auto eta =
static_cast<unsigned int>(std::max(t_final_ - t, Number(0.)) /
1557 time_per_second_exp);
1559 output <<
"\n ETA : ";
1561 const unsigned int days = eta / (24 * 3600);
1563 output << days <<
" d ";
1567 const unsigned int hours = eta / 3600;
1569 output << hours <<
" h ";
1573 const unsigned int minutes = eta / 60;
1574 output << minutes <<
" min";
1576 output <<
" (terminal update every "
1577 << std::setprecision(2) << std::fixed << terminal_update_interval_
1580 if (mpi_ensemble_.world_rank() != 0)
1583 stream << output.str() << std::endl;
1587 template <
typename Description,
int dim,
typename Number>
1588 void TimeLoop<Description, dim, Number>::print_cycle_statistics(
1591 unsigned int timer_cycle,
1592 Number last_checkpoint,
1593 bool write_to_logfile,
1596 std::ostringstream output;
1600 std::ostringstream primary;
1602 primary <<
"FINAL (cycle " << Utilities::int_to_string(cycle, 6) <<
")";
1604 primary <<
"Cycle " << Utilities::int_to_string(cycle, 6)
1605 <<
" (" << std::fixed << std::setprecision(1)
1606 << t / t_final_ * 100 <<
"%)";
1609 std::ostringstream secondary;
1610 secondary <<
"at time t = " << std::setprecision(8) << std::fixed << t;
1612 print_head(primary.str(), secondary.str(), output);
1616 print_information(timer_cycle, last_checkpoint, output, final_time);
1617 print_memory_statistics(output);
1618 print_timers(output);
1619 print_throughput(cycle, t, output, final_time);
1622 if (mpi_ensemble_.world_rank() != 0)
1626 std::cout <<
"\033[2J\033[H";
1628 std::cout << output.str() << std::flush;
1630 if (write_to_logfile) {
1631 logfile_ <<
"\n" << output.str() << std::flush;
static dealii::Timer & timer(const std::string §ion)
static const std::map< std::string, dealii::Timer > & timers()
TimeLoop(const MPI_Comm &mpi_comm)
typename View::StateVector StateVector
constexpr unsigned int warp_size
constexpr bool have_separate_memory_spaces
void debug_poison_invalid_values(StateVector< Number, prob_dim, prec_dim > &state_vector, const OfflineData &offline_data)
dealii::LinearAlgebra::distributed::Vector< Number > ScalarHostVector
void print_revision_and_version(std::ostream &stream)