Lethe Open-Source Library version 1.2.0
Developer Guide
Loading...
Searching...
No Matches
utilities.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) 2020-2026 The Lethe Authors
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
3
4#ifndef lethe_utilities_h
5#define lethe_utilities_h
6
8
9#include <deal.II/base/conditional_ostream.h>
10#include <deal.II/base/exceptions.h>
11#include <deal.II/base/mpi_remote_point_evaluation.h>
12#include <deal.II/base/parameter_handler.h>
13#include <deal.II/base/patterns.h>
14#include <deal.II/base/point.h>
15#include <deal.II/base/table_handler.h>
16#include <deal.II/base/tensor.h>
17
18#include <deal.II/dofs/dof_handler.h>
19
20#include <deal.II/fe/fe_values.h>
21
22#include <deal.II/numerics/vector_tools.h>
23
24#include <deal.II/particles/particle_iterator.h>
25
26#include <boost/archive/text_iarchive.hpp>
27#include <boost/archive/text_oarchive.hpp>
28
29#include <magic_enum.hpp>
30
31#include <algorithm>
32#include <fstream>
33#include <map>
34#include <optional>
35#include <string>
36#include <string_view>
37#include <tuple>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42using namespace dealii;
43
44/**
45 * @class statistics
46 * @brief A simple container for storing basic statistical values.
47 *
48 * This class holds the minimum, maximum, total, and average values
49 * of a dataset. It is initialized with zeros by default. This small class
50 * allows us to agglomerate the statistics instead of returning tuples. For
51 * example, this class is used to store the kinetic energy of the particles in
52 * the DEM model.
53 */
54
56{
57 /**
58 * @brief Default constructor.
59 *
60 * Initializes all statistical values (min, max, total, average) to 0.
61 */
62public:
64 : min(0)
65 , max(0)
66 , total(0)
67 , average(0)
68 {}
69
70
71 /// The minimum value in the dataset.
72 double min;
73
74 /// The maximum value in the dataset.
75 double max;
76
77 /// The sum of all values in the dataset.
78 double total;
79
80 /// The average value of the dataset.
81 double average;
82};
83
84
85/**
86 * @brief Add statistical values to a TableHandler.
87 *
88 * This function inserts a variable name and its associated statistics
89 * (minimum, maximum, total, average) into a given TableHandler.
90 *
91 * @param[in] variable The name of the variable being recorded.
92 * @param[in] stats The statistics associated with the variable.
93 * @param[in,out] table Reference to the TableHandler where the values will be
94 * added.
95 */
96inline void
97add_statistics_to_table_handler(const std::string &variable,
98 const statistics &stats,
99 TableHandler &table)
100{
101 table.add_value("Variable", variable);
102 table.add_value("Min", stats.min);
103 table.add_value("Max", stats.max);
104 table.add_value("Total", stats.total);
105 table.add_value("Average", stats.average);
106}
107
108/**
109 * @brief Generate a table from a vector of scalars (independent variable) and
110 * a vector of vectors of scalars (dependent variables).
111 *
112 * @tparam T Scalar type of independent variables.
113 *
114 * @param[in] independent_values Vector of scalar values that serve as the
115 * independent variable (e.g., time).
116 *
117 * @param[in] independent_column_name Label of the independent variable.
118 *
119 * @param[in] dependent_vector Vector of vectors of scalar values containing
120 * dependant variables values.
121 *
122 * @param[in] dependent_column_names Vector of strings representing the labels
123 * of dependent variables.
124 *
125 * @param[in] display_precision Integer indicating the precision at which the
126 * table is written.
127 *
128 * @param[in] display_scientific_notation Boolean indicating if the values
129 * should be displayed in scientific notation (true) or not (false).
130 *
131 * @return Table with the independent variable values followed by the dependent
132 * variables values.
133 */
134template <typename T>
135TableHandler
137 const std::vector<T> &independent_values,
138 const std::string &independent_column_name,
139 const std::vector<std::vector<double>> &dependent_vector,
140 const std::vector<std::string> &dependent_column_names,
141 const unsigned int display_precision,
142 const bool display_scientific_notation = false);
143
144
145/**
146 * @brief Generate a table from a vector of scalars (independent variable) and
147 * a vector of Tensor<1,dim> (dependent variables).
148 *
149 * @tparam T Scalar type of independent variables.
150 *
151 * @tparam dim Integer that denotes the number of spatial dimensions.
152 *
153 * @param[in] independent_values Vector of scalar values that serve as the
154 * independent variable (e.g., time).
155 *
156 * @param[in] independent_column_name Label of the independent variable.
157 *
158 * @param[in] dependent_vector Vector of Tensor<1,dim> containing dependent
159 * variables values (e.g., force).
160 *
161 * @param[in] dependent_column_names Vector of strings representing the labels
162 * of dependent variables.
163 *
164 * @param[in] display_precision Integer indicating the precision at which the
165 * table is written.
166 *
167 * @param[in] display_scientific_notation Boolean indicating if the values
168 * should be displayed in scientific notation (true) or not (false).
169 *
170 * @return Table with the independent variable values followed by the dependent
171 * variables values.
172 */
173template <int dim, typename T>
174TableHandler
176 const std::vector<T> &independent_values,
177 const std::string &independent_column_name,
178 const std::vector<Tensor<1, dim>> &dependent_vector,
179 const std::vector<std::string> &dependent_column_names,
180 const unsigned int display_precision,
181 const bool display_scientific_notation = false);
182
183/**
184 * @brief Generate a table from a vector of scalar (independent variable) and a
185 * vector of vectors of Tensor<1,dim> (dependent variables).
186 *
187 * @tparam T Scalar type of independent variables.
188 *
189 * @tparam dim Integer that denotes the number of spatial dimensions.
190 *
191 * @param[in] independent_values Vector of scalar values that serve as the
192 * independent variable (e.g., time).
193 *
194 * @param[in] independent_column_name Label of the independent variable.
195 *
196 * @param[in] dependent_vector Vector of vectors of Tensor<1,dim> containing
197 * dependent variables values (e.g., force).
198 *
199 * @param[in] dependent_column_names Vector of strings representing the labels
200 * of dependent variables.
201 *
202 * @param[in] display_precision Integer indicating the precision at which the
203 * table is written.
204 *
205 * @param[in] display_scientific_notation Boolean indicating if the values
206 * should be displayed in scientific notation (true) or not (false).
207 *
208 * @return Table with the independent variable values followed by the dependent
209 * variables values.
210 */
211template <int dim, typename T>
212TableHandler
214 const std::vector<T> &independent_values,
215 const std::string &independent_column_name,
216 const std::vector<std::vector<Tensor<1, dim>>> &dependent_vector,
217 const std::vector<std::string> &dependent_column_names,
218 const unsigned int display_precision,
219 const bool display_scientific_notation = false);
220
221/**
222 * @brief Generate a table from a vector of Tensor<1,dim> (independent
223 * variables) and a vector of Tensor<1,dim> (dependent variables).
224 *
225 * @tparam dim Integer that denotes the number of spatial dimensions.
226 *
227 * @param[in] independent_vector Vector of Tensor<1,dim> that serves as the
228 * independent variable (e.g., position).
229 *
230 * @param[in] independent_column_names Vector of strings representing labels of
231 * the independent tensor.
232 *
233 * @param[in] dependent_vector Vector of vectors of Tensor<1,dim> containing
234 * dependent variables values (e.g., force).
235 *
236 * @param[in] dependent_column_names Vector of strings representing the labels
237 * of dependent variables.
238 *
239 * @param[in] display_precision Integer indicating the precision at which the
240 * table is written.
241 *
242 * @param[in] display_scientific_notation Boolean indicating if the values
243 * should be displayed in scientific notation (true) or not (false).
244 *
245 * @return Table with the independent variables values followed by the dependent
246 * variables values.
247 */
248template <int dim>
249TableHandler
251 const std::vector<Tensor<1, dim>> &independent_vector,
252 const std::vector<std::string> &independent_column_names,
253 const std::vector<Tensor<1, dim>> &dependent_vector,
254 const std::vector<std::string> &dependent_column_names,
255 const unsigned int display_precision,
256 const bool display_scientific_notation = false);
257
258
259/**
260 * @brief Generate a table from a vector of Tensor<1,dim> (independent
261 * variables) and a vector of scalars (dependent variable).
262 *
263 * @tparam dim Integer that denotes the number of spatial dimensions.
264 *
265 * @param[in] independent_vector Vector of Tensor<1,dim> that serves as the
266 * independent variable (e.g., position).
267 *
268 * @param[in] independent_column_names Vector of strings representing labels of
269 * the independent tensor.
270 *
271 * @param[in] dependent_values Vector of doubles containing dependent variables
272 * values (e.g., force).
273 *
274 * @param[in] dependent_column_name Label of the dependent variable.
275 *
276 * @param[in] display_precision Integer indicating the precision at which the
277 * table is written.
278 *
279 * @param[in] display_scientific_notation Boolean indicating if the values
280 * should be displayed in scientific notation (true) or not (false).
281 *
282 * @return Table with the independent variables values followed by the dependent
283 * variable values.
284 */
285template <int dim>
286TableHandler
288 const std::vector<Tensor<1, dim>> &independent_vector,
289 const std::vector<std::string> &independent_column_names,
290 const std::vector<double> &dependent_values,
291 const std::string &dependent_column_name,
292 const unsigned int display_precision,
293 const bool display_scientific_notation = false);
294
295
296/**
297 * @brief Calculate the equivalent properties for a given phase. Method called
298 * in quadrature points loops in CLS simulations.
299 *
300 * @param phase Phase value for the given quadrature point
301 *
302 * @param property0 Property value for the fluid with index 0 (fluid for phase = 0)
303 *
304 * @param property1 Property value for the fluid with index 1 (fluid for phase = 1)
305 */
306inline double
308 const double property0,
309 const double property1)
310{
311 double property_eq = phase * property1 + (1 - phase) * property0;
312
313 // Limit parameters value (patch)
314 // TODO see if necessary after compression term is added in the
315 // CLS advection equation
316 const double property_min = std::min(property0, property1);
317 const double property_max = std::max(property0, property1);
318 if (property_eq < property_min)
319 {
320 property_eq = property_min;
321 }
322 if (property_eq > property_max)
323 {
324 property_eq = property_max;
325 }
326
327 return property_eq;
328}
329
330/**
331 * @brief Retrieve the sign of a value.
332 *
333 * Used in calculate_point_property_cahn_hilliard to determine the sign of the
334 * phase parameter.
335 *
336 * @tparam T The argument's type (must support comparison with zero).
337 * @param[in] val Value of the variable for which the sign is evaluated.
338 * @retval -1 if the value is negative.
339 * @retval +1 if the value is positive.
340 * @retval 0 if the value is zero.
341 */
342template <typename T>
343[[nodiscard]] constexpr int
344sgn(const T val) noexcept
345{
346 return (static_cast<T>(0) < val) - (val < static_cast<T>(0));
347}
348
349
350/**
351 * @brief Clip a property between a lower and a higher value
352 * @tparam T argument's type
353 * @param[in,out] lower Lower admissible value
354 * @param[in,out] upper Upper admissible value
355 * @param[in,out] n
356 * @return Clipped variable that is not below the lower limit and not above the upper limit
357 *
358 */
359template <typename T>
360T
361clip(const T &n, const T &lower, const T &upper)
362{
363 return std::max(lower, std::min(n, upper));
364}
365
366/**
367 * @brief Calculate the equivalent property for a given phase.
368 *
369 * This method is called in quadrature point loops in Cahn-Hilliard simulations.
370 * It interpolates between two fluid properties based on the phase value.
371 *
372 * @param[in] phase_cahn_hilliard Phase value for the given quadrature point.
373 * @param[in] property0 Property value for the fluid with index 0 (fluid for
374 * phase = -1).
375 * @param[in] property1 Property value for the fluid with index 1 (fluid for
376 * phase = 1).
377 * @return double Equivalent property for the given phase.
378 */
379[[nodiscard]] inline double
381 const double property0,
382 const double property1)
383{
384 double phase = phase_cahn_hilliard;
385
386 if (std::abs(phase_cahn_hilliard) > 1)
387 {
389 }
390
391 double property_avg = (property0 + property1) * 0.5;
392 double property_diff = (property0 - property1) * 0.5;
393
394 double property_eq = phase * property_diff + property_avg;
395
396 return property_eq;
397}
398
399
400/**
401 * @brief Verify that a file that Lethe must read exists and can be opened, and
402 * raise an error stated in the user's terms otherwise.
403 *
404 * This function is meant to be called right before a file whose path comes
405 * from the user, either from the command line or from the parameter file, is
406 * opened. It distinguishes a file name that was left empty, a file that does
407 * not exist and a file that exists but cannot be read, so that the user is
408 * told what to correct instead of facing the error that the reader of the file
409 * would raise further down.
410 *
411 * @param[in] file_name Path of the file, exactly as it was given by the user.
412 *
413 * @param[in] file_description Role of the file in the simulation. It is used
414 * to build the error message and should read naturally after "The", for
415 * example "parameter file given to the application" or "gmsh mesh file given
416 * by 'subsection mesh' - 'set file name'".
417 */
418void
419check_file_exists(const std::string &file_name,
420 const std::string &file_description);
421
422/**
423 * @brief Reads a file generated by a deal.II TableHandler and fills a TableHandler with its data.
424 *
425 * This function reads a table from a file and populates the given TableHandler.
426 * Warning: If the table already contains data, it will be erased.
427 *
428 * @param[in,out] table The table to be filled. Existing content will be
429 * overwritten.
430 * @param[in] file_name Path to the file to read the table from.
431 * @param[in] delimiter Delimiter used in the file to separate values. Default
432 * is a space (" ").
433 */
434void
435fill_table_from_file(TableHandler &table,
436 const std::string &file_name,
437 const std::string &delimiter = " ");
438
439/**
440 * @brief function that read a file that was build from a dealii table and fill 2 vectors.
441 * The first vector contains all the columns names and the second one contained
442 * all the column data.
443 *
444 * @param[in,out] map A map used to store the data based on column names.
445 * @param[in] file_name Path to the file to read the table from.
446 * @param[in] delimiter Delimiter used in the file to separate values. Default
447 * is a space (" ").
448 */
449void
450fill_vectors_from_file(std::map<std::string, std::vector<double>> &map,
451 const std::string &file_name,
452 const std::string &delimiter = " ");
453
454/**
455 * @brief Function that read a file that was build from a dealii table and create a map with the key being the column name and the variable the vectors of data.
456 *
457 * @param[in,out] map A map used to store the data based on column names.
458 * @param[in] file_name Path to the file to read the table from.
459 * @param[in] delimiter Delimiter used in the file to separate values. Default
460 * is a space (" ").
461 */
462void
464 std::map<std::string, std::vector<std::string>> &map,
465 const std::string &file_name,
466 const std::string &delimiter = " ");
467
468/**
469 * @brief Creates the simulation output folder
470 *
471 * @param[in] dirname Output directory name
472 */
473void
474create_output_folder(const std::string &dirname);
475
476/**
477 * @brief Delete the output folder and its content.
478 *
479 * @param[in] dirname Output directory name.
480 */
481void
482delete_output_folder(const std::string &dirname);
483
484/**
485 * @brief Prints a string and then adds a line above and below made with dashes containing as many dashes as the string has characters+1
486 *
487 * For example, if the string to be printed is "Tracer" the result will be:
488 * @code
489 * -------
490 * Tracer
491 * -------
492 * @endcode
493 *
494 * @param[in] pcout the parallel cout used to print the information
495 * @param[in] expression string that will be printed
496 * @param[in] delimiter the character used to delimit the printing. Default
497 * value is "-"
498 */
499inline void
500announce_string(const ConditionalOStream &pcout,
501 const std::string &expression,
502 const char delimiter = '-')
503{
504 pcout << std::string(expression.size() + 1, delimiter) << std::endl;
505 pcout << expression << std::endl;
506 pcout << std::string(expression.size() + 1, delimiter) << std::endl;
507}
508
509/**
510 * @brief Prints an expression string surrounded from above and bottom with a
511 * lines of a specified @p delimiter character (by default, '-'). The length of
512 * the banner lines is the length of the string + 1 character.
513 *
514 * @param[in] pcout Parallel conditional output stream used to print the
515 * information
516 * @param[in] expression Expression string that will be printed
517 * @param[in] banner_size Length of the decorative banner lines
518 * @param[in] delimiter Characters composing the decorative lines of the banner.
519 * By default, '-' is used.
520 *
521 * @remark The overload of the function with @p banner_size is used for cases
522 * where the @p expression string is multiple lines long.
523 */
524inline void
525announce_string(const ConditionalOStream &pcout,
526 const std::string &expression,
527 const unsigned int banner_size,
528 const char delimiter = '-')
529{
530 pcout << std::string(banner_size + 1, delimiter) << std::endl;
531 pcout << expression << std::endl;
532 pcout << std::string(banner_size + 1, delimiter) << std::endl;
533}
534/**
535 * @brief Serializes a TableHandler to a file using Boost serialization.
536 *
537 * The filename should include the desired extension.
538 *
539 * @param[in] table The table to be serialized.
540 * @param[in] filename Path to the file (including extension) where the table
541 * will be saved.
542 * @param[in] mpi_communicator The MPI communicator
543 * @param[in] serialize_on_rank_zero Boolean indicating if the table should only
544 * be serialized on rank 0 only. By default, it is set to `true`.
545 */
546inline void
547serialize_table(const TableHandler &table,
548 const std::string &filename,
549 const MPI_Comm &mpi_communicator,
550 const bool serialize_on_rank_zero = true)
551{
552 unsigned int this_mpi_process(
553 Utilities::MPI::this_mpi_process(mpi_communicator));
554
555 if (!serialize_on_rank_zero || this_mpi_process == 0)
556 {
557 std::ofstream ofile(filename);
558 boost::archive::text_oarchive oa(ofile, boost::archive::no_header);
559 oa << table;
560 }
561}
562
563/**
564 * @brief Loads a TableHandler from a file using Boost serialization.
565 *
566 * The filename should include the desired extension.
567 *
568 * @param[in,out] table The table to be deserialized (will be overwritten).
569 * @param[in] filename Path to the file (including extension) to read the table
570 * from.
571 * @param[in] mpi_communicator The MPI communicator
572 * @param[in] deserialize_on_rank_zero Boolean indicating if the table should
573 * only be deserialized on rank 0 only. By default, it is set to `true`.
574 */
575inline void
576deserialize_table(TableHandler &table,
577 const std::string &filename,
578 const MPI_Comm &mpi_communicator,
579 const bool deserialize_on_rank_zero = true)
580{
581 unsigned int this_mpi_process(
582 Utilities::MPI::this_mpi_process(mpi_communicator));
583
584 if (!deserialize_on_rank_zero || this_mpi_process == 0)
585 {
586 std::ifstream ifile(filename);
587 boost::archive::text_iarchive ia(ifile, boost::archive::no_header);
588 ia >> table;
589 }
590}
591
592/**
593 * @brief Serializes all the TableHandler objects in table_output_structs.
594 *
595 * @param[in] table_output_structs Vector of structures containing references
596 * to TableHandler objects that need to be serialized/deserialized for a
597 * given solver, and their corresponding file names.
598 *
599 * @param[in] mpi_communicator The MPI communicator
600 */
601inline void
603 const std::vector<OutputStructTableHandler> &table_output_structs,
604 const MPI_Comm mpi_communicator)
605{
606 for (const auto &output_table : table_output_structs)
607 {
608 serialize_table(output_table.table,
609 output_table.table_filename,
610 mpi_communicator);
611 }
612}
613
614/**
615 * @brief Deserializes all the TableHandler objects in table_output_structs.
616 *
617 * @param[in,out] table_output_structs Vector of structures containing
618 * references to TableHandler objects that needs to be serialized/deserialized
619 * for a given solver, and their corresponding file names.
620 *
621 * @param[in] mpi_communicator The MPI communicator
622 */
623inline void
625 std::vector<OutputStructTableHandler> &table_output_structs,
626 const MPI_Comm mpi_communicator)
627{
628 for (auto &output_table : table_output_structs)
629 {
630 deserialize_table(output_table.table,
631 output_table.table_filename,
632 mpi_communicator);
633 }
634}
635
636/**
637 * @brief Retrieves the value of a specific parameter from an input file.
638 * Returns an empty string if the parameter is not found. This function is
639 * adapted from ASPECT and is mainly used to parse the dimension of the problem
640 * before creating the full parameter parser.
641 *
642 * @param[in] file_name File from which we retrieve the parameter.
643 * @param[in] parameter_name Name of the parameter to retrieve.
644 * @return std::string Value of the parameter, or an empty string if not found.
645 */
646std::string
647get_last_value_of_parameter(const std::string &file_name,
648 const std::string &parameter_name);
649/**
650 * @brief Extract the dimension in which to run Lethe from
651 * the contents of the parameter file. This is something that
652 * we need to do before processing the parameter file since we
653 * need to know whether to use the dim=2 or dim=3 instantiation
654 * of the main classes.
655 *
656 * @param file_name[in] The file name from which dimension is read
657 */
658unsigned int
659get_dimension(const std::string &file_name);
660
661/**
662 * @brief Extract the maximum value between the number of boundary conditions
663 * and the number of manifolds from the file. This value is linked to the
664 * "number" string defined in the simulation parameter file.
665 * It provides an estimate for the amount of parameters or manifolds and is
666 * used to determine the size of the vectors that will store boundary conditions
667 * and manifold data. This feature will need to be monitored extensively in the
668 * future.
669 *
670 * @param[in] file_name The file name from which the number of boundary
671 * conditions is read
672 *
673 * @param[in] require_subsection_size If true, the file must contain at least
674 * one "number" entry and an exception is raised otherwise. Solvers for which no
675 * variable size subsection is mandatory, such as the DEM solvers whose boundary
676 * conditions are declared with a "number of boundary conditions" entry, set
677 * this to false. A file without any "number" entry then yields a size of zero.
678 *
679 * @return The maximum number of boundary conditions or manifolds.
680 */
681int
682get_max_subsection_size(const std::string &file_name,
683 const bool require_subsection_size = true);
684
685/**
686 * @brief Return the name of an enumerator, e.g. to derive the default value
687 * string of a parameter entry from the in-class default of its enum member.
688 *
689 * This is only valid for parameters whose accepted strings are exactly the
690 * enumerator identifiers (e.g. "bdf1" for TimeSteppingMethod::bdf1).
691 *
692 * @note Patterns::Tools::Convert<EnumType> is not used, because it treats
693 * enums as bit-flag sets: for a non-zero value, it also returns the name of
694 * the zero-valued enumerator (e.g. "pspg_supg| gls" for gls).
695 *
696 * @tparam EnumType Enumeration type.
697 *
698 * @param[in] value Enumerator whose name is returned.
699 *
700 * @return The identifier of @p value.
701 */
702template <typename EnumType>
703 requires std::is_enum_v<EnumType>
704inline std::string
705enum_to_string(const EnumType value)
706{
707 const std::string_view name = magic_enum::enum_name(value);
708 Assert(!name.empty(), ExcInternalError());
709 return std::string(name);
710}
711
712/**
713 * @brief Return the enumerator whose identifier is @p name, e.g. to parse the
714 * value of a parameter entry into its enum member. This is the inverse of
715 * enum_to_string().
716 *
717 * This is only valid for parameters whose accepted strings are exactly the
718 * enumerator identifiers (e.g. "bdf1" for TimeSteppingMethod::bdf1). The
719 * comparison is case-sensitive.
720 *
721 * @note Patterns::Tools::Convert<EnumType> is not used, because it treats
722 * enums as bit-flag sets (see enum_to_string()).
723 *
724 * @tparam EnumType Enumeration type.
725 *
726 * @param[in] name Identifier of the enumerator.
727 *
728 * @return The enumerator of @p EnumType named @p name. An exception is thrown
729 * if @p EnumType has no enumerator named @p name.
730 */
731template <typename EnumType>
732 requires std::is_enum_v<EnumType>
733inline EnumType
734string_to_enum(const std::string &name)
735{
736 const std::optional<EnumType> value = magic_enum::enum_cast<EnumType>(name);
737 if (!value.has_value())
738 {
739 std::string choices;
740 for (const std::string_view choice : magic_enum::enum_names<EnumType>())
741 {
742 if (!choices.empty())
743 choices += "|";
744 choices += choice;
745 }
746 AssertThrow(false,
747 ExcMessage(
748 "Invalid value \"" + name + "\" for " +
749 std::string(magic_enum::enum_type_name<EnumType>()) +
750 ". The choices are <" + choices + ">."));
751 }
752 return *value;
753}
754
755/**
756 * @brief Deprecated strings of an enum parameter, each paired with the
757 * enumerator it stands for. These are the values that were accepted before the
758 * parameter strings were made identical to the enumerator identifiers (e.g.
759 * "extra verbose" for Verbosity::extra_verbose). They remain accepted, but
760 * using one of them raises a deprecation warning.
761 *
762 * @tparam EnumType Enumeration type.
763 */
764template <typename EnumType>
765using DeprecatedEnumNames = std::vector<std::pair<std::string, EnumType>>;
766
767/**
768 * @brief Print a warning stating that a deprecated value was given to a
769 * parameter, along with the value which replaces it. The warning is only
770 * printed by the first MPI process.
771 *
772 * @param[in] parameter_name Name of the parameter in the parameter file.
773 *
774 * @param[in] deprecated_value Deprecated value which was given.
775 *
776 * @param[in] new_value Value which replaces @p deprecated_value.
777 */
778void
779warn_deprecated_parameter_value(const std::string &parameter_name,
780 const std::string &deprecated_value,
781 const std::string &new_value);
782
783/**
784 * @brief Return the selection string (e.g. "quiet|verbose|extra_verbose") of
785 * an enum parameter, to be given to Patterns::Selection. The choices returned
786 * in the selection string are the enumerator identifiers (meaning, the names
787 * in the enum converted into strings) followed by the
788 * deprecated strings which are still accepted.
789 *
790 * @tparam EnumType Enumeration type.
791 *
792 * @param[in] deprecated_names Deprecated strings which remain accepted.
793 *
794 * @param[in] allowed_values Enumerators (e.g. the enum values, for example
795 * quiet, verbose and extra_verbose) accepted by the parameter. If empty,
796 * all the enumerators (meaning all possible values) of @p EnumType are accepted.
797 * This is necessary because some enums contain internal enumerators which are
798 * not user choices (for example, the periodic_neighbor value of the boundary
799 * condition types, which the parser assigns to the boundary matching a
800 * periodic boundary).
801 *
802 * @return The choices separated by "|".
803 */
804template <typename EnumType>
805 requires std::is_enum_v<EnumType>
806inline std::string
808 const std::vector<EnumType> &allowed_values = {})
809{
810 const auto is_allowed = [&allowed_values](const EnumType value) {
811 return allowed_values.empty() ||
812 std::find(allowed_values.begin(), allowed_values.end(), value) !=
813 allowed_values.end();
814 };
815
816 std::string selection;
817 const auto add_choice = [&selection](const std::string_view choice) {
818 if (!selection.empty())
819 selection += "|";
820 selection += choice;
821 };
822
823 if (allowed_values.empty())
824 for (const std::string_view name : magic_enum::enum_names<EnumType>())
825 add_choice(name);
826 else
827 for (const EnumType value : allowed_values)
828 add_choice(enum_to_string(value));
829
830 for (const auto &[deprecated_name, value] : deprecated_names)
831 if (is_allowed(value))
832 add_choice(deprecated_name);
833
834 return selection;
835}
836
837/**
838 * @brief Return the sentence listing the choices of an enum parameter (e.g.
839 * "Choices are <quiet|verbose|extra_verbose>."), to be used in the description
840 * of the parameter entry. The choices are the enumerator identifiers, in the
841 * order of the enumeration. The deprecated strings which are still accepted are
842 * deliberately not listed.
843 *
844 * @tparam EnumType Enumeration type.
845 *
846 * @param[in] allowed_values Enumerators accepted by the parameter. If empty,
847 * all the enumerators of @p EnumType are accepted (see enum_to_selection()).
848 *
849 * @return The sentence listing the choices, separated by "|".
850 */
851template <typename EnumType>
852 requires std::is_enum_v<EnumType>
853inline std::string
854enum_to_choices(const std::vector<EnumType> &allowed_values = {})
855{
856 return "Choices are <" + enum_to_selection<EnumType>({}, allowed_values) +
857 ">.";
858}
859
860/**
861 * @brief Declare a parameter entry whose value is an enumerator. The default
862 * value, the accepted values and the choices listed in the description are all
863 * derived from the enumeration, so that they cannot differ from one another.
864 *
865 * The entry is declared with enum_to_string() of @p default_value as default
866 * value, a Patterns::Selection built with enum_to_selection() as pattern and
867 * @p description followed by enum_to_choices() as documentation.
868 *
869 * @tparam EnumType Enumeration type.
870 *
871 * @param[in,out] prm Parameter handler in which the entry is declared.
872 *
873 * @param[in] entry_name Name of the parameter in the parameter file.
874 *
875 * @param[in] default_value Default enumerator of the parameter.
876 *
877 * @param[in] description Description of the parameter, without the list of its
878 * choices, which is appended to it. It should end with a period.
879 *
880 * @param[in] deprecated_names Deprecated strings which remain accepted.
881 *
882 * @param[in] allowed_values Enumerators accepted by the parameter. If empty,
883 * all the enumerators of @p EnumType are accepted (see enum_to_selection()).
884 */
885template <typename EnumType>
886 requires std::is_enum_v<EnumType>
887inline void
888declare_enum_entry(ParameterHandler &prm,
889 const std::string &entry_name,
890 const EnumType default_value,
891 const std::string &description,
892 const DeprecatedEnumNames<EnumType> &deprecated_names = {},
893 const std::vector<EnumType> &allowed_values = {})
894{
895 prm.declare_entry(
896 entry_name,
897 enum_to_string(default_value),
898 Patterns::Selection(
899 enum_to_selection<EnumType>(deprecated_names, allowed_values)),
900 description + " " + enum_to_choices<EnumType>(allowed_values));
901}
902
903/**
904 * @brief Return the enumerator designated by @p name, which is either the
905 * identifier of the enumerator or one of the deprecated strings of the
906 * parameter. In the latter case, a deprecation warning is printed.
907 *
908 * @tparam EnumType Enumeration type.
909 *
910 * @param[in] parameter_value Value of the parameter.
911 *
912 * @param[in] deprecated_names Deprecated strings which remain accepted.
913 *
914 * @param[in] parameter_name Name of the parameter in the parameter file, used
915 * in the deprecation warning.
916 *
917 * @return The enumerator of @p EnumType designated by @p name. An exception is
918 * thrown if @p name is neither an enumerator nor a deprecated string.
919 */
920template <typename EnumType>
921 requires std::is_enum_v<EnumType>
922inline EnumType
923string_to_enum(const std::string &name,
924 const DeprecatedEnumNames<EnumType> &deprecated_names,
925 const std::string &parameter_name)
926{
927 for (const auto &[deprecated_name, value] : deprecated_names)
928 if (name == deprecated_name)
929 {
930 warn_deprecated_parameter_value(parameter_name,
931 deprecated_name,
932 enum_to_string(value));
933 return value;
934 }
935 return string_to_enum<EnumType>(name);
936}
937
938/**
939 * @brief Return the tensor corresponding to the @p value_string. If the
940 * dimension correspondence of the @p value_string is not equivalent to
941 * @p spacedim (either 2 or 3), an exception will be thrown. The delimiter
942 * separating the elements of the @p value_string is a comma (",").
943 *
944 * @remark The function is used to construct Point<spacedim> objects.
945 *
946 * @tparam spacedim Number of spatial dimensions (2D or 3D).
947 *
948 * @param[in] value_string A string in the parameter file corresponding to a
949 * given tensor.
950 *
951 * @return A Tensor<1,spacedim> corresponding to the @p value_string in the
952 * parameter file.
953 */
954template <int spacedim>
955inline Tensor<1, spacedim>
956value_string_to_tensor(const std::string &value_string)
957{
958 std::vector<std::string> vector_of_string(
959 Utilities::split_string_list(value_string));
960 std::vector<double> vector_of_double =
961 Utilities::string_to_double(vector_of_string);
962
963 Assert(vector_of_double.size() == 3 || vector_of_double.size() == 2,
964 ExcMessage("Invalid string: " + value_string +
965 ". This should be a two or three dimensional vector "
966 "or point."));
967
968 Tensor<1, spacedim> output_tensor;
969 for (int i = 0; i < spacedim; ++i)
970 output_tensor[i] = vector_of_double[i];
971
972 return output_tensor;
973}
974
975/**
976 * @brief Computes equivalent cell diameter by comparing the area to a disk (2D)
977 * or the volume to a sphere (3D).
978 *
979 * @tparam dim Number of spatial dimensions (2D or 3D).
980 *
981 * @param[in] cell_measure Area (2D) or volume (3D) of the cell.
982 *
983 * @param[in] fe_degree Polynomial degree of the shape function.
984 *
985 * @return Cell diameter value.
986 */
987template <int dim>
988inline double
989compute_cell_diameter(const double cell_measure, const unsigned int fe_degree)
990{
991 double h;
992 if constexpr (dim == 2)
993 h = std::sqrt(4. * cell_measure / numbers::PI) / fe_degree;
994 else if constexpr (dim == 3)
995 h = std::cbrt(6. * cell_measure / numbers::PI) / fe_degree;
996 else
997 Assert(
998 false,
999 ExcMessage(std::string(
1000 "'dim' should have a value of either 2 or 3. Only 2D and 3D simulations "
1001 "are supported.")));
1002 return h;
1003}
1004
1005/**
1006 * @brief Computes the area (2D) or volume (3D) of the cell by integrating 1
1007 * over the cell, by summing JxW values (quadrature weights) returned by the
1008 * FEValues object.
1009 *
1010 * @tparam dim Number of spatial dimensions (2D or 3D).
1011 *
1012 * @param[in] JxW_values Vector of mapped quadrature weights.
1013 *
1014 * @return Area (2D) volume (3D) of the cell.
1015 */
1016inline double
1017compute_cell_measure_with_JxW(const std::vector<double> &JxW_values)
1018{
1019 double cell_measure = 0;
1020 for (const double &JxW : JxW_values)
1021 cell_measure += JxW;
1022 return cell_measure;
1023}
1024
1025/**
1026 * @brief Identify minimum cell size. The cell size corresponds to the diameter
1027 * of a disk (2D) or sphere (3D) of equivalent area (2D) or volume (3D).
1028 *
1029 * @tparam dim Number of spatial dimensions (2D or 3D).
1030 *
1031 * @param[in] mapping Interface for transformation from the reference (unit)
1032 * cell to the real cell.
1033 *
1034 * @param[in] dof_handler Describes the layout of DoFs and the type of FE.
1035 *
1036 * @param[in] cell_quadrature Local cell quadrature information.
1037 *
1038 * @param[in] mpi_communicator Allows communication between cores.
1039 *
1040 * @return Smallest cell size value.
1041 */
1042template <int dim>
1043inline double
1044identify_minimum_cell_size(const Mapping<dim> &mapping,
1045 const DoFHandler<dim> &dof_handler,
1046 const Quadrature<dim> &cell_quadrature,
1047 const MPI_Comm &mpi_communicator)
1048{
1049 // Initialize FEValues for interface PDE-based reinitialization
1050 FEValues<dim> fe_values(mapping,
1051 dof_handler.get_fe(),
1052 cell_quadrature,
1053 update_JxW_values);
1054
1055 // Initialize cell diameter
1056 double h = DBL_MAX;
1057
1058 // Element degree
1059 const unsigned int degree = fe_values.get_fe().degree;
1060
1061 for (const auto &cell : dof_handler.active_cell_iterators())
1062 {
1063 if (cell->is_locally_owned())
1064 {
1065 fe_values.reinit(cell);
1066
1067 // Compute cell diameter
1068 double cell_measure =
1069 compute_cell_measure_with_JxW(fe_values.get_JxW_values());
1070 double h_local = compute_cell_diameter<dim>(cell_measure, degree);
1071
1072 // Update cell diameter to minimum value
1073 h = std::min(h, h_local);
1074 }
1075 }
1076
1077 // Get the minimum between all processes
1078 h = Utilities::MPI::min(h, mpi_communicator);
1079
1080 return h;
1081}
1082
1083/**
1084 * @brief Calculate the penalty factor for the SIPG method for the case when two
1085 * cells are of different sizes. A harmonic mean is used to calculate an average
1086 * cell extent.
1087 *
1088 * @param[in] fe_degree Finite element degree.
1089 * @param[in] cell_extent_here Distance of the here cell. The ratio between the
1090 * volume of the cell and the area of the face is generally used as a metric for
1091 * this distance.
1092 * @param[in] cell_extent_there Distance of the there cell. The ratio between
1093 * the volume of the cell and the area of the face is generally used as a metric
1094 * for this distance.
1095 * @return double
1096 */
1097
1098inline double
1099get_penalty_factor(const unsigned int fe_degree,
1100 const double cell_extent_here,
1101 const double cell_extent_there)
1102{
1103 return (fe_degree + 1) * (fe_degree + 1.) * 0.5 *
1104 (1. / cell_extent_here + 1. / cell_extent_there);
1105}
1106
1107/**
1108 * @brief Extract the keys from map object
1109 *
1110 * @tparam key Key of the map
1111 * @tparam val Value of the map. This template parameter is not used.
1112 * @param[in] map Map object from which the keys are extracted
1113 * @return keys Vector of keys from the map
1114 */
1115
1116template <typename key, typename val>
1117std::vector<key>
1118extract_keys_from_map(const std::map<key, val> &map)
1119{
1120 std::vector<key> keys;
1121 keys.reserve(map.size());
1122 for (const auto &pair : map)
1123 keys.push_back(pair.first);
1124 return keys;
1125}
1126
1127/**
1128 * @brief Extract the values from map object
1129 *
1130 * @tparam key Key of the map. This template parameter is not used.
1131 * @tparam val Value of the map.
1132 * @param[in] map Map object from which the keys are extracted
1133 * @return values Vector of values from the map
1134 */
1135
1136template <typename key, typename val>
1137std::vector<val>
1138extract_values_from_map(const std::map<key, val> &map)
1139{
1140 std::vector<val> values;
1141 values.reserve(map.size());
1142 for (const auto &pair : map)
1143 values.push_back(pair.second);
1144 return values;
1145}
1146
1147/**
1148 * @brief Concatenate words which are passed from the command line to a main function
1149 * into a single string in which the words are seperated by space.
1150 *
1151 * @param[in] argc number of arguments in C style.
1152 * @param[in] argv arguments themselves in C style.
1153 */
1154
1155std::string
1156concatenate_strings(const int argc, char **argv);
1157
1158/**
1159 * @brief Print the information of the deal.II and Lethe branches
1160 * used to run an application in the "git describe" format.
1161 *
1162 * @param[in] pcout Parallel output stream
1163 */
1164void
1165print_version_info(const ConditionalOStream &pcout);
1166
1167/**
1168 * @brief Parse the arguments given to the application
1169 *
1170 * @param[in] argc Number of arguments
1171 * @param[in] argv Array of strings representing the arguments
1172 * @return Tuple containing a map with the command line flags
1173 * and a boolean set to 1 for the specific flag; and a vector of
1174 * strings with the rest of the arguments that are not flags; in Lethe,
1175 * this corresponds to the parameter file given to the application.
1176 */
1177std::tuple<std::map<std::string, bool>, std::vector<std::string>>
1178parse_args(int argc, char **argv);
1179
1180/**
1181 * @brief Print the parameters given by the parameter file of the application
1182 *
1183 * @param[in] pcout Parallel output stream
1184 * @param[in] prm Object containing the parameters parsed from the parameter
1185 * file.
1186 * @param[in] file_name File name where the parameters will be written.
1187 */
1188void
1189print_parameters_to_output_file(const ConditionalOStream &pcout,
1190 const ParameterHandler &prm,
1191 const std::string &file_name);
1192
1193/**
1194 * @brief Identify escape sequences listed below and apply them to the string.
1195 * - "\n": Newline
1196 * - "\t": Horizontal tab
1197 * - "\r": Carriage return
1198 * - "\b": Backspace
1199 * - "\v": Vertical tab
1200 *
1201 * @param[in, out] s String to be modified if escape sequences are specified.
1202 */
1203void
1204interpret_escape_sequences(std::string &s);
1205
1206/**
1207 * @brief Print a user comment at the beginning of the simulation on the console
1208 * output.
1209 *
1210 * @param[in] pcout Parallel console output stream.
1211 * @param[in,out] prm ParameterHandler.
1212 * specified.
1213 */
1214void
1215print_comment_to_output_file(const ConditionalOStream &pcout,
1216 ParameterHandler &prm);
1217
1218/**
1219 * @brief Delete vtu and pvd files
1220 */
1221void
1222delete_vtu_and_pvd_files(const std::string &output_path);
1223
1224/**
1225 * @brief Converts point to angle (in radians) based on rotation axis
1226 * @param[in] point Point in cartesian coordinates
1227 * @param[in] center_of_rotation Center of rotation
1228 * @param[in] rotation_axis_direction Direction of rotation axis (x=0, y=1, z=2)
1229 *
1230 * @return Angle in the plane perpendicular to the rotation axis
1231 */
1232template <int dim>
1233inline double
1234point_to_angle(const Point<dim> &point,
1235 const Point<dim> &center_of_rotation = Point<dim>(),
1236 const unsigned int rotation_axis_direction = 2)
1237{
1238 if constexpr (dim == 3)
1239 {
1240 const unsigned int coord1 = (rotation_axis_direction + 1) % 3;
1241 const unsigned int coord2 = (rotation_axis_direction + 2) % 3;
1242
1243 return std::fmod(std::atan2(point[coord2] - center_of_rotation[coord2],
1244 point[coord1] - center_of_rotation[coord1]) +
1245 2 * numbers::PI,
1246 2 * numbers::PI);
1247 }
1248 else
1249 return std::fmod(std::atan2(point[1] - center_of_rotation[1],
1250 point[0] - center_of_rotation[0]) +
1251 2 * numbers::PI,
1252 2 * numbers::PI);
1253}
1254
1255/**
1256 * @brief Converts radius to point in cartesian coordinates based on rotation axis
1257 * @param[in] radius Radial distance
1258 * @param[in] angle_rad Angle (in radians)
1259 * @param[in] center_of_rotation Center of rotation
1260 * @param[in] rotation_axis_direction Direction of rotation axis (x=0, y=1, z=2)
1261 *
1262 * @return point Point in cartesian coordinates
1263 */
1264template <int dim>
1265inline Point<dim>
1266radius_to_point(const double radius,
1267 const double angle_rad,
1268 const Point<dim> &center_of_rotation = Point<dim>(),
1269 const unsigned int rotation_axis_direction = 2)
1270{
1271 Point<dim> point;
1272
1273 if constexpr (dim == 3)
1274 {
1275 const unsigned int coord1 = (rotation_axis_direction + 1) % 3;
1276 const unsigned int coord2 = (rotation_axis_direction + 2) % 3;
1277
1278 point[coord1] = radius * std::cos(angle_rad) + center_of_rotation[coord1];
1279 point[coord2] = radius * std::sin(angle_rad) + center_of_rotation[coord2];
1280 point[rotation_axis_direction] =
1281 center_of_rotation[rotation_axis_direction];
1282 }
1283 else
1284 {
1285 point[0] = radius * std::cos(angle_rad) + center_of_rotation[0];
1286 point[1] = radius * std::sin(angle_rad) + center_of_rotation[1];
1287 }
1288 return point;
1289}
1290
1291/**
1292 * @brief Creates a vector of random doubles between 0 and a maximum value using
1293 * a pseudo random seed.
1294 * @param[in,out] random_container Container in which the doubles are stored.
1295 * @param[in] number_of_elements Number of random doubles to generate.
1296 * @param[in] maximum_range Maximum value that the random double can have.
1297 * @param[in] prn_seed Pseudo random seed used to generate the random doubles.
1298 *
1299 */
1300
1301inline void
1302create_random_number_container(std::vector<double> &random_container,
1303 const unsigned int number_of_elements,
1304 const double maximum_range,
1305 const unsigned int prn_seed)
1306{
1307 for (unsigned int i = 0; i < number_of_elements; ++i)
1308 {
1309 srand(prn_seed * (i + 1));
1310 random_container.push_back((((double)rand()) / ((double)RAND_MAX)) *
1311 maximum_range);
1312 }
1313}
1314
1315/**
1316 * @brief Return the vector of size N of entry @entry_string. If the entry is
1317 * specified in the .prm file, then the changed value is returned, otherwise
1318 * the default value is returned. If the entry is not equivalent to a vector,
1319 * an error will be thrown.
1320 *
1321 * @tparam T The type of vector (int, unsigned int or double)
1322 * @param[in] prm A parameter handler which is currently used to parse the
1323 * simulation information.
1324 * @param[in] entry_string A declare string in the parameter file.
1325 *
1326 * @return A std::vector<double> corresponding to the entry_string in the prm file.
1327 */
1328template <typename T>
1329std::vector<T>
1330convert_string_to_vector(const ParameterHandler &prm,
1331 const std::string &entry_string)
1332{
1333 std::string full_str = prm.get(entry_string);
1334 std::vector<std::string> vector_of_string(
1335 Utilities::split_string_list(full_str));
1336 if constexpr (std::is_same_v<T, int>)
1337 {
1338 std::vector<T> vector = Utilities::string_to_int(vector_of_string);
1339 return vector;
1340 }
1341 if constexpr (std::is_same_v<T, double>)
1342 {
1343 std::vector<T> vector = Utilities::string_to_double(vector_of_string);
1344 return vector;
1345 }
1346 if constexpr (std::is_same_v<T, std::string>)
1347 {
1348 return vector_of_string;
1349 }
1350 if constexpr (std::is_same_v<T, types::boundary_id>)
1351 {
1352 std::vector<int> vector_int = Utilities::string_to_int(vector_of_string);
1353 std::vector<T> vector;
1354 for (const auto var_int : vector_int)
1355 {
1356 AssertThrow(
1357 var_int >= 0,
1358 ExcMessage(
1359 "You are trying to convert a negative integer to a boundary id. Lethe does not support negative boundary id."));
1360 vector.push_back(static_cast<types::boundary_id>(var_int));
1361 }
1362 return vector;
1363 }
1364
1365 AssertThrow(false,
1366 ExcMessage("Error: convert_string_to_vector only works for "
1367 "int, double and string types."));
1368
1369 return std::vector<T>();
1370}
1371
1372/**
1373 * @brief Operator overloading to enable using triangulation cells as map keys.
1374 */
1375
1376template <int dim>
1378{
1379 inline bool
1381 const typename Triangulation<dim>::active_cell_iterator &cell_1,
1382 const typename Triangulation<dim>::active_cell_iterator &cell_2) const
1383 {
1384 return cell_1->global_active_cell_index() <
1385 cell_2->global_active_cell_index();
1386 }
1387};
1388
1389/**
1390 * @brief Operator overloading to enable using particle iterators as map keys.
1391 */
1392
1393template <int dim>
1395{
1396 inline bool
1397 operator()(const Particles::ParticleIterator<dim> &particle_1,
1398 const Particles::ParticleIterator<dim> &particle_2)
1399 {
1400 return particle_1->id() < particle_2->id();
1401 }
1402};
1403
1404/**
1405 * @brief Operator overloading to enable using triangulation cells as map keys.
1406 */
1407using namespace dealii;
1408
1409template <int dim>
1411{
1412 inline bool
1414 const typename Triangulation<dim - 1, dim>::active_cell_iterator &cell_1,
1415 const typename Triangulation<dim - 1, dim>::active_cell_iterator &cell_2)
1416 const
1417 {
1418 return cell_1->global_active_cell_index() <
1419 cell_2->global_active_cell_index();
1420 }
1421};
1422
1423/**
1424 * @brief Hash functor to enable using cut-cell (embedded triangulation)
1425 * active cell iterators as keys of an unordered associative container, for
1426 * example std::unordered_map. Pairs with cut_cell_comparison, which orders
1427 * the same iterators for ordered associative containers.
1428 */
1429template <int dim>
1431{
1432 inline std::size_t
1433 operator()(const typename Triangulation<dim - 1, dim>::active_cell_iterator
1434 &cell) const
1435 {
1436 return std::hash<int>()(cell->global_active_cell_index());
1437 }
1438};
1439
1440/**
1441 * @brief Evaluates the values of a scalar field at remote points of the domain
1442 * from the mapping, the DoF handler and the solution field.
1443 *
1444 * @tparam dim Denotes the number of spatial dimensions.
1445 * @tparam VectorType Vector type of the solution vector.
1446 *
1447 * @param[in] mapping Mapping of the domain.
1448 * @param[in] dof_handler DoF handler associated to the solution field.
1449 * @param[in] solution_field Vector containing the solution field. For
1450 * distributed meshes, ghost elements must be updated.
1451 * @param[in] evaluation_points Vector of points where the values of the
1452 * solution field are to be evaluated.
1453 * @param[in,out] remote_point_evaluator Utilities::MPI::RemotePointEvaluation
1454 * object used to evaluate values of the variable of interest at given points
1455 * of the domain.
1456 * @param[in,out] evaluated_scalar_values Vector of evaluated scalar values.
1457 * @param[in] first_selected_component First component of the solution to select
1458 * if the solution field is a vector field. This is used to extract the correct
1459 * field when the solution vector contains multiple fields (e.g., velocity and
1460 * pressure are stored in a same solution vector).
1461 *
1462 * @remark If a given evaluation point is not within the simulated domain, an
1463 * exception is thrown.
1464 */
1465template <int dim, typename VectorType>
1466void
1468 const Mapping<dim> &mapping,
1469 const DoFHandler<dim> &dof_handler,
1470 const VectorType &solution_field,
1471 const std::vector<Point<dim>> &evaluation_points,
1472 Utilities::MPI::RemotePointEvaluation<dim> &remote_point_evaluator,
1473 std::vector<double> &evaluated_scalar_values,
1474 const unsigned int first_selected_component = 0);
1475
1476/**
1477 * @brief Evaluates the values of a vector field at remote points of the domain
1478 * from the mapping, the DoF handler and the solution field.
1479 *
1480 * @tparam n_component Number of components of the evaluated vector solution.
1481 * @tparam dim Denotes the number of spatial dimensions.
1482 * @tparam VectorType Vector type of the solution vector.
1483 *
1484 * @param[in] mapping Mapping of the domain.
1485 * @param[in] dof_handler DoF handler associated to the solution field.
1486 * @param[in] solution_field Vector containing the vector solution field.
1487 * @param[in] evaluation_points Vector of points where the values of the
1488 * solution field are to be evaluated.
1489 * @param[in,out] remote_point_evaluator Utilities::MPI::RemotePointEvaluation
1490 * object used to evaluate values of the variable of interest at given points
1491 * of the domain.
1492 * @param[in,out] evaluated_vector_values Vector of evaluated vector values.
1493 * @param[in] first_selected_component First component of the solution to
1494 * select. This is used to extract the correct fields when the solution vector
1495 * contains multiple fields (e.g., velocity and pressure are stored in a same
1496 * solution vector).
1497 *
1498 * @remark If a given evaluation point is not within the simulated domain, an
1499 * exception is thrown.
1500 */
1501template <int n_component, int dim, typename VectorType>
1502void
1504 const Mapping<dim> &mapping,
1505 const DoFHandler<dim> &dof_handler,
1506 const VectorType &solution_field,
1507 const std::vector<Point<dim>> &evaluation_points,
1508 Utilities::MPI::RemotePointEvaluation<dim> &remote_point_evaluator,
1509 std::vector<Tensor<1, dim, double>> &evaluated_vector_values,
1510 const unsigned int first_selected_component = 0);
1511
1512/**
1513 * @brief Checks that the evaluation points are within the simulated domain and
1514 * returns @p true if all points are within the domain.
1515 *
1516 * @tparam dim Denotes the number of spatial dimensions.
1517 *
1518 * @param[in] evaluation_points Vector of points where the values of the
1519 * solution field are to be evaluated.
1520 * @param[in] remote_point_evaluator RemotePointEvaluation object used to
1521 * evaluate values.
1522 *
1523 * @return @p true if all points are within the simulated domain.
1524 */
1525template <int dim>
1526inline bool
1528 const std::vector<Point<dim>> &evaluation_points,
1529 const Utilities::MPI::RemotePointEvaluation<dim, dim> &remote_point_evaluator)
1530{
1531 if (!remote_point_evaluator.all_points_found())
1532 {
1533 for (unsigned int i = 0; i < evaluation_points.size(); ++i)
1534 {
1535 AssertThrow(remote_point_evaluator.point_found(i),
1536 ExcMessage(
1537 "The point (" +
1538 Patterns::Tools::Convert<Point<dim>>::to_string(
1539 evaluation_points[i]) +
1540 ") is not defined within the simulated domain."));
1541 }
1542 }
1543
1544 return true;
1545}
1546
1547
1548#endif
A simple container for storing basic statistical values.
Definition utilities.h:56
double average
The average value of the dataset.
Definition utilities.h:81
double max
The maximum value in the dataset.
Definition utilities.h:75
statistics()
Default constructor.
Definition utilities.h:63
double min
The minimum value in the dataset.
Definition utilities.h:72
double total
The sum of all values in the dataset.
Definition utilities.h:78
void create_random_number_container(std::vector< double > &random_container, const unsigned int number_of_elements, const double maximum_range, const unsigned int prn_seed)
Creates a vector of random doubles between 0 and a maximum value using a pseudo random seed.
Definition utilities.h:1302
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
unsigned int get_dimension(const std::string &file_name)
Extract the dimension in which to run Lethe from the contents of the parameter file....
Definition utilities.cc:670
void deserialize_table(TableHandler &table, const std::string &filename, const MPI_Comm &mpi_communicator, const bool deserialize_on_rank_zero=true)
Loads a TableHandler from a file using Boost serialization.
Definition utilities.h:576
std::string get_last_value_of_parameter(const std::string &file_name, const std::string &parameter_name)
Retrieves the value of a specific parameter from an input file. Returns an empty string if the parame...
Definition utilities.cc:585
Tensor< 1, spacedim > value_string_to_tensor(const std::string &value_string)
Return the tensor corresponding to the value_string. If the dimension correspondence of the value_str...
Definition utilities.h:956
std::tuple< std::map< std::string, bool >, std::vector< std::string > > parse_args(int argc, char **argv)
Parse the arguments given to the application.
Definition utilities.cc:800
double compute_cell_measure_with_JxW(const std::vector< double > &JxW_values)
Computes the area (2D) or volume (3D) of the cell by integrating 1 over the cell, by summing JxW valu...
Definition utilities.h:1017
TableHandler make_table_scalars_tensors(const std::vector< T > &independent_values, const std::string &independent_column_name, const std::vector< Tensor< 1, dim > > &dependent_vector, const std::vector< std::string > &dependent_column_names, const unsigned int display_precision, const bool display_scientific_notation=false)
Generate a table from a vector of scalars (independent variable) and a vector of Tensor<1,...
Definition utilities.cc:59
void fill_string_vectors_from_file(std::map< std::string, std::vector< std::string > > &map, const std::string &file_name, const std::string &delimiter=" ")
Function that read a file that was build from a dealii table and create a map with the key being the ...
Definition utilities.cc:352
TableHandler make_table_tensors_scalars(const std::vector< Tensor< 1, dim > > &independent_vector, const std::vector< std::string > &independent_column_names, const std::vector< double > &dependent_values, const std::string &dependent_column_name, const unsigned int display_precision, const bool display_scientific_notation=false)
Generate a table from a vector of Tensor<1,dim> (independent variables) and a vector of scalars (depe...
Definition utilities.cc:189
double identify_minimum_cell_size(const Mapping< dim > &mapping, const DoFHandler< dim > &dof_handler, const Quadrature< dim > &cell_quadrature, const MPI_Comm &mpi_communicator)
Identify minimum cell size. The cell size corresponds to the diameter of a disk (2D) or sphere (3D) o...
Definition utilities.h:1044
std::vector< val > extract_values_from_map(const std::map< key, val > &map)
Extract the values from map object.
Definition utilities.h:1138
void create_output_folder(const std::string &dirname)
Creates the simulation output folder.
Definition utilities.cc:401
double point_to_angle(const Point< dim > &point, const Point< dim > &center_of_rotation=Point< dim >(), const unsigned int rotation_axis_direction=2)
Converts point to angle (in radians) based on rotation axis.
Definition utilities.h:1234
void evaluate_values_at_points(const Mapping< dim > &mapping, const DoFHandler< dim > &dof_handler, const VectorType &solution_field, const std::vector< Point< dim > > &evaluation_points, Utilities::MPI::RemotePointEvaluation< dim > &remote_point_evaluator, std::vector< double > &evaluated_scalar_values, const unsigned int first_selected_component=0)
Evaluates the values of a scalar field at remote points of the domain from the mapping,...
Definition utilities.cc:930
std::vector< std::pair< std::string, EnumType > > DeprecatedEnumNames
Deprecated strings of an enum parameter, each paired with the enumerator it stands for....
Definition utilities.h:765
std::string enum_to_string(const EnumType value)
Return the name of an enumerator, e.g. to derive the default value string of a parameter entry from t...
Definition utilities.h:705
TableHandler make_table_scalars_vectors(const std::vector< T > &independent_values, const std::string &independent_column_name, const std::vector< std::vector< double > > &dependent_vector, const std::vector< std::string > &dependent_column_names, const unsigned int display_precision, const bool display_scientific_notation=false)
Generate a table from a vector of scalars (independent variable) and a vector of vectors of scalars (...
Definition utilities.cc:24
void serialize_table(const TableHandler &table, const std::string &filename, const MPI_Comm &mpi_communicator, const bool serialize_on_rank_zero=true)
Serializes a TableHandler to a file using Boost serialization.
Definition utilities.h:547
void print_parameters_to_output_file(const ConditionalOStream &pcout, const ParameterHandler &prm, const std::string &file_name)
Print the parameters given by the parameter file of the application.
Definition utilities.cc:865
std::vector< T > convert_string_to_vector(const ParameterHandler &prm, const std::string &entry_string)
Return the vector of size N of entry @entry_string. If the entry is specified in the ....
Definition utilities.h:1330
void delete_output_folder(const std::string &dirname)
Delete the output folder and its content.
Definition utilities.cc:407
void delete_vtu_and_pvd_files(const std::string &output_path)
Delete vtu and pvd files.
Definition utilities.cc:917
bool points_are_in_domain(const std::vector< Point< dim > > &evaluation_points, const Utilities::MPI::RemotePointEvaluation< dim, dim > &remote_point_evaluator)
Checks that the evaluation points are within the simulated domain and returns true if all points are ...
Definition utilities.h:1527
void fill_vectors_from_file(std::map< std::string, std::vector< double > > &map, const std::string &file_name, const std::string &delimiter=" ")
function that read a file that was build from a dealii table and fill 2 vectors. The first vector con...
Definition utilities.cc:299
TableHandler make_table_tensors_tensors(const std::vector< Tensor< 1, dim > > &independent_vector, const std::vector< std::string > &independent_column_names, const std::vector< Tensor< 1, dim > > &dependent_vector, const std::vector< std::string > &dependent_column_names, const unsigned int display_precision, const bool display_scientific_notation=false)
Generate a table from a vector of Tensor<1,dim> (independent variables) and a vector of Tensor<1,...
Definition utilities.cc:147
int get_max_subsection_size(const std::string &file_name, const bool require_subsection_size=true)
Extract the maximum value between the number of boundary conditions and the number of manifolds from ...
Definition utilities.cc:736
void serialize_tables_vector(const std::vector< OutputStructTableHandler > &table_output_structs, const MPI_Comm mpi_communicator)
Serializes all the TableHandler objects in table_output_structs.
Definition utilities.h:602
EnumType string_to_enum(const std::string &name)
Return the enumerator whose identifier is name, e.g. to parse the value of a parameter entry into its...
Definition utilities.h:734
void print_version_info(const ConditionalOStream &pcout)
Print the information of the deal.II and Lethe branches used to run an application in the "git descri...
Definition utilities.cc:775
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
double calculate_point_property(const double phase, const double property0, const double property1)
Calculate the equivalent properties for a given phase. Method called in quadrature points loops in CL...
Definition utilities.h:307
constexpr int sgn(const T val) noexcept
Retrieve the sign of a value.
Definition utilities.h:344
T clip(const T &n, const T &lower, const T &upper)
Clip a property between a lower and a higher value.
Definition utilities.h:361
double compute_cell_diameter(const double cell_measure, const unsigned int fe_degree)
Computes equivalent cell diameter by comparing the area to a disk (2D) or the volume to a sphere (3D)...
Definition utilities.h:989
std::string concatenate_strings(const int argc, char **argv)
Concatenate words which are passed from the command line to a main function into a single string in w...
Definition utilities.cc:758
void add_statistics_to_table_handler(const std::string &variable, const statistics &stats, TableHandler &table)
Add statistical values to a TableHandler.
Definition utilities.h:97
std::vector< key > extract_keys_from_map(const std::map< key, val > &map)
Extract the keys from map object.
Definition utilities.h:1118
std::string enum_to_selection(const DeprecatedEnumNames< EnumType > &deprecated_names={}, const std::vector< EnumType > &allowed_values={})
Return the selection string (e.g. "quiet|verbose|extra_verbose") of an enum parameter,...
Definition utilities.h:807
void warn_deprecated_parameter_value(const std::string &parameter_name, const std::string &deprecated_value, const std::string &new_value)
Print a warning stating that a deprecated value was given to a parameter, along with the value which ...
Definition utilities.cc:839
double calculate_point_property_cahn_hilliard(const double phase_cahn_hilliard, const double property0, const double property1)
Calculate the equivalent property for a given phase.
Definition utilities.h:380
void interpret_escape_sequences(std::string &s)
Identify escape sequences listed below and apply them to the string.
Definition utilities.cc:892
double get_penalty_factor(const unsigned int fe_degree, const double cell_extent_here, const double cell_extent_there)
Calculate the penalty factor for the SIPG method for the case when two cells are of different sizes....
Definition utilities.h:1099
std::string enum_to_choices(const std::vector< EnumType > &allowed_values={})
Return the sentence listing the choices of an enum parameter (e.g. "Choices are <quiet|verbose|extra_...
Definition utilities.h:854
void declare_enum_entry(ParameterHandler &prm, const std::string &entry_name, const EnumType default_value, const std::string &description, const DeprecatedEnumNames< EnumType > &deprecated_names={}, const std::vector< EnumType > &allowed_values={})
Declare a parameter entry whose value is an enumerator. The default value, the accepted values and th...
Definition utilities.h:888
void print_comment_to_output_file(const ConditionalOStream &pcout, ParameterHandler &prm)
Print a user comment at the beginning of the simulation on the console output.
Definition utilities.cc:902
void fill_table_from_file(TableHandler &table, const std::string &file_name, const std::string &delimiter=" ")
Reads a file generated by a deal.II TableHandler and fills a TableHandler with its data.
Definition utilities.cc:253
Point< dim > radius_to_point(const double radius, const double angle_rad, const Point< dim > &center_of_rotation=Point< dim >(), const unsigned int rotation_axis_direction=2)
Converts radius to point in cartesian coordinates based on rotation axis.
Definition utilities.h:1266
void deserialize_tables_vector(std::vector< OutputStructTableHandler > &table_output_structs, const MPI_Comm mpi_communicator)
Deserializes all the TableHandler objects in table_output_structs.
Definition utilities.h:624
@ phase_cahn_hilliard
Phase order scalar field from Cahn Hilliard.
@ phase
Phase indicator scalar field from CLS.
@ T
Particle temperature.
Operator overloading to enable using triangulation cells as map keys.
Definition utilities.h:1378
bool operator()(const typename Triangulation< dim >::active_cell_iterator &cell_1, const typename Triangulation< dim >::active_cell_iterator &cell_2) const
Definition utilities.h:1380
bool operator()(const typename Triangulation< dim - 1, dim >::active_cell_iterator &cell_1, const typename Triangulation< dim - 1, dim >::active_cell_iterator &cell_2) const
Definition utilities.h:1413
Hash functor to enable using cut-cell (embedded triangulation) active cell iterators as keys of an un...
Definition utilities.h:1431
std::size_t operator()(const typename Triangulation< dim - 1, dim >::active_cell_iterator &cell) const
Definition utilities.h:1433
Operator overloading to enable using particle iterators as map keys.
Definition utilities.h:1395
bool operator()(const Particles::ParticleIterator< dim > &particle_1, const Particles::ParticleIterator< dim > &particle_2)
Definition utilities.h:1397
GlobalVectorType VectorType