oomph_utilities.h
Go to the documentation of this file.
1// LIC// ====================================================================
2// LIC// This file forms part of oomph-lib, the object-oriented,
3// LIC// multi-physics finite-element library, available
4// LIC// at http://www.oomph-lib.org.
5// LIC//
6// LIC// Copyright (C) 2006-2025 Matthias Heil and Andrew Hazel
7// LIC//
8// LIC// This library is free software; you can redistribute it and/or
9// LIC// modify it under the terms of the GNU Lesser General Public
10// LIC// License as published by the Free Software Foundation; either
11// LIC// version 2.1 of the License, or (at your option) any later version.
12// LIC//
13// LIC// This library is distributed in the hope that it will be useful,
14// LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
15// LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16// LIC// Lesser General Public License for more details.
17// LIC//
18// LIC// You should have received a copy of the GNU Lesser General Public
19// LIC// License along with this library; if not, write to the Free Software
20// LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21// LIC// 02110-1301 USA.
22// LIC//
23// LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
24// LIC//
25// LIC//====================================================================
26// A header containing useful utility classes, functions and constants
27
28// Include guard to prevent multiple inclusions of the header
29#ifndef OOMPH_UTILITIES_HEADER
30#define OOMPH_UTILITIES_HEADER
31
32// Config header
33#ifdef HAVE_CONFIG_H
34#include <oomph-lib-config.h>
35#endif
36
37
38#ifdef OOMPH_HAS_MPI
39// mpi headers
40#include "mpi.h"
41#endif
42
43// Standard libray headers
44#include <string>
45#include <sstream>
46#include <fstream>
47#include <cmath>
48#include <map>
49#include <ctime>
50#include <complex>
51
52// oomph-lib headers
53#include "Vector.h"
54#include "oomph_definitions.h"
55#include "communicator.h"
56
57/* // Header for cxx-prettyprint: A C++ Container Pretty-Printer. If the */
58/* // standard in use is older than C++11 then use a special older version of */
59/* // the header. Header is from here: */
60/* // http://louisdx.github.io/cxx-prettyprint/ */
61/* #if __cplusplus <= 199711L */
62/* #include "prettyprint98.h" */
63/* #else */
64/* #include "prettyprint.h" */
65/* #endif */
66
67// Header for name demangling
68#include <cxxabi.h>
69
70namespace oomph
71{
72 //======start_of_ANSIEscapeCode_namespace=================
73 /// Contains an enumeration of the ANSI escape codes used for
74 /// colouring text (when piped to the command line). Adapted from
75 /// the guide on:
76 /// https://stackoverflow.com/questions/2616906/how-do-i-output-
77 /// coloured-text-to-a-linux-terminal?utm_medium=organic&utm_source=
78 /// google_rich_qa&utm_campaign=google_rich_qa
79 /// Here, \033 is the ESC character, ASCII 27. It is followed by [,
80 /// then zero or more numbers separated by ;, and finally the letter
81 /// m. The numbers describe the colour and format to switch to from
82 /// that point onwards.
83 //====================================================================
84 namespace ANSIEscapeCode
85 {
86 /// Function to change text effect. NOTE: This assumes the user
87 /// knows what they're doing/assigning; no error checking done here...
88 extern void set_text_effect(std::string text_effect);
89
90 /// Variable to decide on effects
91 extern std::string Text_effect;
92
93 /// The code for each type of colour
94 extern std::string Black;
95 extern std::string Red;
96 extern std::string Green;
97 extern std::string Yellow;
98 extern std::string Blue;
99 extern std::string Magenta;
100 extern std::string Cyan;
101 extern std::string Reset;
102 } // namespace ANSIEscapeCode
103
104 //=====================================================================
105 /// Namespace for debugging helpers. Currently only contains a
106 /// function to prett-ify file name and line numbers (in red) to use
107 /// when debugging. Makes it easy to identify where a std::cout
108 /// statement was called.
109 //=====================================================================
110 namespace DebugHelpers
111 {
112 /// Return the concaternation of the initials of the input
113 /// file name and line number. The make_new_line flag indicates
114 /// whether the string starts on a new line or not
115 extern std::string debug_string(const std::string& filename,
116 const int& line_number,
117 const std::string& message,
118 const bool& shorten = false,
119 const bool& start_on_new_line = true);
120
121 // NOTE: Although we define the OOMPH_DEBUG macro inside DebugHelpers but it
122 // has global visibility because it's a macro.
123#define OOMPH_DEBUG(msg) \
124 oomph_info << DebugHelpers::debug_string( \
125 __FILE__, __LINE__, msg, false, true) \
126 << std::flush;
127
128 } // namespace DebugHelpers
129
130 // Forward declaration needed for second invariant helper
131 template<class TYPE>
132 class DenseMatrix;
133
134 //=====================================================================
135 /// Helper namespace containing function that computes second invariant
136 /// of tensor
137 //=====================================================================
138 namespace SecondInvariantHelper
139 {
140 /// Compute second invariant of tensor
141 extern double second_invariant(const DenseMatrix<double>& tensor);
142
143 } // namespace SecondInvariantHelper
144
145
146 //==============================================
147 /// Namespace for error messages for broken
148 /// copy constructors and assignment operators
149 //==============================================
150 namespace BrokenCopy
151 {
152 /// Issue error message and terminate execution
153 extern void broken_assign(const std::string& class_name);
154
155 /// Issue error message and terminate execution
156 extern void broken_copy(const std::string& class_name);
157
158 } // namespace BrokenCopy
159
160 //========================================
161 /// Namespace for mathematical constants
162 ///
163 //=======================================
164 namespace MathematicalConstants
165 {
166 /// 50 digits from maple
167 const double Pi = 3.1415926535897932384626433832795028841971693993751;
168
169 /// The imaginary unit
170 const std::complex<double> I(0.0, 1.0);
171 } // namespace MathematicalConstants
172
173
174 //================================================================
175 /// Function-type-object to perform absolute comparison of objects.
176 /// Apparently this inlines better
177 //================================================================
178 template<class T>
179 class AbsCmp
180 {
181 public:
182 /// Comparison. Are the values identical or not?
183 bool operator()(const T& x, const T& y) const
184 {
185 return std::abs(x) < std::abs(y);
186 }
187 };
188
189
190 // =================================================================
191 /// Conversion functions for easily making strings (e.g. for filenames - to
192 /// avoid stack smashing problems with cstrings and long filenames).
193 // =================================================================
194 namespace StringConversion
195 {
196 /// Conversion function that should work for anything with
197 /// operator<< defined (at least all basic types).
198 template<class T>
199 std::string to_string(T object, unsigned float_precision = 8)
200 {
201 std::stringstream ss;
202 ss.precision(float_precision);
203 ss << object;
204 return ss.str();
205 }
206
207 /// Convert a string to lower case (outputs a copy).
208 std::string to_lower(const std::string& input);
209
210 /// Convert a string to upper case (outputs a copy).
211 std::string to_upper(const std::string& input);
212
213 /// Split a string, s, into a vector of strings where ever there is
214 /// an instance of delimiter (i.e. is delimiter is " " will give a list of
215 /// words). Note that multiple delimiters in a row will give empty
216 /// strings.
217 void split_string(const std::string& s,
218 char delim,
220
221 /// Split a string, s, into a vector of strings where ever there is
222 /// an instance of delimiter (i.e. is delimiter is " " will give a list of
223 /// words). Note that multiple delimiters in a row will give empty
224 /// strings. Return by value.
225 Vector<std::string> split_string(const std::string& s, char delim);
226
227 } // namespace StringConversion
228
229
230 namespace TypeNames
231 {
232 /// Get the type name of an object. Only for use in debugging, do
233 /// not write real code using this function as it is implementation
234 /// dependant!
235 template<class T>
236 std::string get_type_name(T& obj)
237 {
238 using namespace StringConversion;
239
240 int status;
241 std::string typestr =
242 to_string(abi::__cxa_demangle(typeid(obj).name(), 0, 0, &status));
243
244 // Throw if there was an error
245 if (status != 0)
246 {
247 std::string err = "Error code " + to_string(status) +
248 " in demangler, see documentation of "
249 "abi::__cxa_demangle for the meaning";
250 throw OomphLibError(
252 }
253
254 return typestr;
255 }
256
257 /// Get the type name of an object from a pointer to the object (we
258 /// usually want the type of the object itself not the pointer because the
259 /// type of the pointer may be a base class). Only for use in debugging,
260 /// do not write real code using this function as it is implementation
261 /// dependant!
262 template<class T>
263 std::string get_type_name(T* obj)
264 {
265 return get_type_name(*obj);
266 }
267
268 } // namespace TypeNames
269
270 //////////////////////////////////////////////////////////////////
271 //////////////////////////////////////////////////////////////////
272 //////////////////////////////////////////////////////////////////
273
274
275 //====================================================================
276 /// Namespace for global (cumulative) timings
277 //====================================================================
278 namespace CumulativeTimings
279 {
280 /// (Re-)start i-th timer
281 extern void start(const unsigned& i);
282
283 /// Halt i-th timer
284 extern void halt(const unsigned& i);
285
286 /// Reset i-th timer
287 extern void reset(const unsigned& i);
288
289 /// Reset all timers
290 extern void reset();
291
292 /// Report time accumulated by i-th timer
293 extern double cumulative_time(const unsigned& i);
294
295 /// Set number of timings that can be recorded in parallel
296 extern void set_ntimers(const unsigned& ntimers);
297
298 /// Cumulative timings
299 extern Vector<clock_t> Timing;
300
301 /// Start times of active timers
302 extern Vector<clock_t> Start_time;
303
304 } // namespace CumulativeTimings
305
306
307 // ============================================================
308 // Automatically checked casting functions (from boost)
309 // ============================================================
310
311 /// Runtime checked dynamic cast. This is the safe but slightly slower
312 /// cast. Use it in any of these cases:
313 /// - You aren't entirely sure the cast is always safe.
314 /// - You have strange inheritance structures (e.g. the "Diamond of Death" in
315 /// element inheritance).
316 /// - Efficiency is not critical.
317 /// Note that if you just want to check if a pointer can be converted to
318 /// some type you will need to use a plain dynamic_cast. Adapted from
319 /// polymorphic_cast in boost/cast.hpp, see
320 /// http://www.boost.org/doc/libs/1_52_0/libs/conversion/cast.htm for more
321 /// details.
322 template<class Target, class Source>
324 {
325 Target tmp = dynamic_cast<Target>(x);
326#ifdef PARANOID
327 if (tmp == 0)
328 {
329 throw OomphLibError(
331 }
332#endif
333 return tmp;
334 }
335
336 /// Checked static cast. Only use this cast if ALL of these are true:
337 /// - You are sure that the cast will always succeed.
338 /// - You aren't using any strange inheritance structures (e.g. the "Diamond
339 /// of Death" in element inheritance, if you aren't sure just try compiling).
340 /// - You need efficiency.
341 /// Adapted from polymorphic_downcast in boost/cast.hpp, See
342 /// http://www.boost.org/doc/libs/1_52_0/libs/conversion/cast.htm for more
343 /// details.
344 template<class Target, class Source>
346 {
347#ifdef PARANOID
348 // Check that the cast will work as expected.
349 if (dynamic_cast<Target>(x) != x)
350 {
351 throw OomphLibError(
353 }
354#endif
355 return static_cast<Target>(x);
356 }
357
358 //////////////////////////////////////////////////////////////////
359 //////////////////////////////////////////////////////////////////
360 //////////////////////////////////////////////////////////////////
361
362 //====================================================================
363 /// Timer
364 //====================================================================
365 class Timer
366 {
367 public:
368 /// Constructor: Specify number of timers
369 Timer(const unsigned& n_timer)
370 {
372 }
373
374 /// (Re-)start i-th timer
375 void start(const unsigned& i)
376 {
377 Start_time[i] = clock();
378 }
379
380 /// Halt i-th timer
381 void halt(const unsigned& i)
382 {
383 Timing[i] += clock() - Start_time[i];
384 }
385
386 /// Report time accumulated by i-th timer
387 double cumulative_time(const unsigned& i)
388 {
389 return double(Timing[i]) / CLOCKS_PER_SEC;
390 }
391
392 /// Reset i-th timer
393 void reset(const unsigned& i)
394 {
395 Timing[i] = clock_t(0.0);
396 }
397
398 /// Reset all timers
399 void reset()
400 {
401 unsigned n = Timing.size();
402 for (unsigned i = 0; i < n; i++)
403 {
404 Timing[i] = clock_t(0.0);
405 }
406 }
407
408 /// Set number of timings that can be recorded in parallel
409 void set_ntimers(const unsigned& ntimers)
410 {
411 Timing.resize(ntimers, clock_t(0.0));
412 Start_time.resize(ntimers, clock_t(0.0));
413 }
414
415 private:
416 /// Cumulative timings
418
419 /// Start times of active timers
421 };
422
423
424 //====================================================================
425 /// Collection of data structures for storing information about
426 /// linear solves. Currently only contains storage for the
427 /// iteration counts and the linear solver time.
428 //====================================================================
430 {
431 public:
432 /// Constructor. Initialised the Iterations_and_times vector of
433 /// vector of pairs.
435
436 /// Set up a new vector of pairs for a new time step.
438 {
439 // For each new time step, we have a new vector consisting of pairs of
440 // unsigned (for the iteration) and double (for the timing results).
442 }
443
445 {
446 Iterations_and_times.pop_back();
448 }
449
450 /// Add a new iteration and time pair.
452 double prec_setup_time,
453 double linear_solver_time)
454 {
455#ifdef PARANOID
456 if (Iterations_and_times.size() == 0)
457 {
458 std::ostringstream error_message;
459 error_message << "Iterations_and_times is empty. "
460 << "Call setup_new_time_step()\n";
461 throw OomphLibError(error_message.str(),
464 }
465#endif
470 Iterations_and_times.back().push_back(tmp_iter_time_vec);
471 }
472
473 /// The number of time steps
474 unsigned current_ntime_step() const
475 {
476 return Iterations_and_times.size();
477 }
478
479 /// The number of Newton steps.
480 unsigned current_nnewton_step() const
481 {
482 return Iterations_and_times.back().size();
483 }
484
485 /// Accessor function for the iteration and times.
490
491 /// Accessor function for the iteration and times (const version).
496
497 private:
498 /// Storage for number of iterations during Newton steps
500 };
501
502 //====================================================================
503 /// Information for documentation of results:
504 /// Directory and file number to enable output
505 /// in the form RESLT/filename11.dat, say.
506 /// Documentation can be switched on and off.
507 //====================================================================
509 {
510 public:
511 /// Constructor. Default settings: Current directory, step `0',
512 /// label="", full documentation enabled and output directory is
513 /// required to exist when set_directory() is called.
515 : Directory("."),
516 Doc_flag(true),
517 Number(0),
518 Label(""),
520 {
521 }
522
523 /// Constructor with specific directory.
524 DocInfo(const std::string& directory)
526 Doc_flag(true),
527 Number(0),
528 Label(""),
530 {
531 }
532
533 /// Output directory
534 std::string directory() const
535 {
536 return Directory;
537 }
538
539 /// Set output directory (we try to open a file in it
540 /// to see if the directory exists -- if it doesn't we'll
541 /// issue a warning -- or, if directory_must_exist()==true,
542 /// throw and OomphLibError
543 void set_directory(const std::string& directory);
544
545 /// Enable documentation
547 {
548 Doc_flag = true;
549 }
550
551 /// Disable documentation
553 {
554 Doc_flag = false;
555 }
556
557 /// Are we documenting?
558 bool is_doc_enabled() const
559 {
560 return Doc_flag;
561 }
562
563 /// Number used (e.g.) for labeling output files
564 unsigned& number()
565 {
566 return Number;
567 }
568
569 /// Number used (e.g.) for labeling output files. Const version.
570 unsigned number() const
571 {
572 return Number;
573 }
574
575 /// Get number as a string (useful to completely avoid C-strings).
576 std::string number_as_string() const
577 {
579 }
580
581 /// String used (e.g.) for labeling output files
582 std::string& label()
583 {
584 return Label;
585 }
586
587 /// String used (e.g.) for labeling output files. Const version.
588 std::string label() const
589 {
590 return Label;
591 }
592
593 /// Call to throw an error if directory does not exist
598
599 /// Call to issue a warning if the directory does not exists
604
605 private:
606 /// Directory name
607 std::string Directory;
608
609 /// Doc or don't?
611
612 /// Number to label output file, say
613 unsigned Number;
614
615 /// String to label output file, say
616 std::string Label;
617
618 /// Boolean flag to decide response if an output
619 /// directory doesn't exist: If true, we terminate
620 /// code execution by throwing an OomphLibError rather than
621 /// just issuing a warning.
623 };
624
625
626 //====================================================================
627 // Namespace for command line arguments
628 //====================================================================
629 namespace CommandLineArgs
630 {
631 /// Structure to store information on a command line argument
632 template<class T>
633 struct ArgInfo
634 {
635 /// Proper constructor
636 ArgInfo(const bool& is_set, T* arg_pt, const std::string& doc)
637 {
638 this->is_set = is_set;
639 this->arg_pt = arg_pt;
640 this->doc = doc;
641 }
642
643 /// Default constructor. We need this to be able to store these things in
644 /// maps.
646 {
647 this->is_set = false;
648 this->arg_pt = 0;
649 this->doc = "";
650 }
651
652 // /// Assignment operator. We need this to be able to store these things
653 // in
654 // /// maps.
655 // void operator=(const ArgInfo& that)
656 // {
657 // this->is_set = that.is_set;
658 // this->arg_pt = that.arg_pt;
659 // this->doc = that.doc;
660 // }
661
662 /// Has this argument been set?
663 bool is_set;
664
665 /// The place to put the argument's value when it is set
667
668 /// Information about what the argument does
669 std::string doc;
670 };
671
672 // Number of arguments + 1
673 extern int Argc;
674
675 // Arguments themselves
676 extern char** Argv;
677
678 /// Map to indicate an input flag as having been set
679 extern std::map<std::string, ArgInfo<bool>> Specified_command_line_flag;
680
681 /// Map to associate an input flag with a double -- specified via pointer
682 extern std::map<std::string, ArgInfo<double>>
684
685 /// Map to associate an input flag with an int -- specified via pointer
686 extern std::map<std::string, ArgInfo<int>> Specified_command_line_int_pt;
687
688 /// Map to associate an input flag with an unsigned -- specified via pointer
689 extern std::map<std::string, ArgInfo<unsigned>>
691
692 /// Map to associate an input flag with a string -- specified via pointer
693 extern std::map<std::string, ArgInfo<std::string>>
695
696 // Set values
697 extern void setup(int argc, char** argv);
698
699 // Doc the command line arguments
700 extern void output();
701
702 /// Specify possible argument-free command line flag
703 extern void specify_command_line_flag(
704 const std::string& command_line_flag,
705 const std::string& documentation = "Undocumented");
706
707 /// Specify possible command line flag that specifies a double,
708 /// accessed via pointer
709 extern void specify_command_line_flag(
710 const std::string& command_line_flag,
711 double* arg_pt,
712 const std::string& documentation = "Undocumented");
713
714 /// Specify possible command line flag that specifies an int,
715 /// accessed via pointer
716 extern void specify_command_line_flag(
717 const std::string& command_line_flag,
718 int* arg_pt,
719 const std::string& documentation = "Undocumented");
720
721 /// Specify possible command line flag that specifies an unsigned,
722 /// accessed via pointer
723 extern void specify_command_line_flag(
724 const std::string& command_line_flag,
725 unsigned* arg_pt,
726 const std::string& documentation = "Undocumented");
727
728 /// Specify possible command line flag that specifies a string,
729 /// accessed via pointer
730 extern void specify_command_line_flag(
731 const std::string& command_line_flag,
732 std::string* arg_pt,
733 const std::string& documentation = "Undocumented");
734
735 /// Check if specified flag has been set (the associated
736 /// value will have been assigned directly)
737 extern bool command_line_flag_has_been_set(const std::string& flag);
738
739 /// Document the values of all flags (specified or not)
740 extern void doc_all_flags(
741 std::ostream& outstream = *oomph_info.stream_pt());
742
743 /// Document specified command line flags
744 extern void doc_specified_flags();
745
746 /// Document available command line flags
747 extern void doc_available_flags();
748
749 /// Helper function to check if command line index is legal
750 extern void check_arg_index(const int& argc, const int& arg_index);
751
752 /// Parse command line, check for recognised flags and assign
753 /// associated values
754 extern void parse_and_assign(
755 int argc, char* argv[], const bool& throw_on_unrecognised_args = false);
756
757 /// Parse previously specified command line, check for
758 /// recognised flags and assign associated values
759 extern void parse_and_assign(
760 const bool& throw_on_unrecognised_args = false);
761
762 } // namespace CommandLineArgs
763
764 // forward declaration of OomphCommunicator class
765 class OomphCommunicator;
766
767#ifdef OOMPH_HAS_MPI
768 //========================================================================
769 /// MPI output modifier: Precedes every output by
770 /// specification of the processor ID. Output can be restricted
771 /// to a single processor.
772 //========================================================================
774 {
775 private:
776 /// Rank of single processor that produces output (only used
777 /// if Output_from_single_processor=true
778 unsigned Output_rank;
779
780 /// Boolean to control if output is performed only on a single
781 /// processor (default: false)
783
784 /// Communicator
786
787 public:
788 /// Constructor -- initialise flags for output from all processors
790
791 /// Return pointer to communicator
796
797 /// Precede the output by the processor ID but output everything
798 virtual bool operator()(std::ostream& stream);
799
800 /// Switch to ensure output is only produced from a single
801 /// processor (default: Master node, i.e. rank 0)
807
808
809 /// Switch to ensure output is only produced from a single
810 /// processor (default: Master node, i.e. rank 0)
815 };
816
817
818 //========================================================================
819 /// Single (global) instantiation of the mpi output modifier
820 //========================================================================
821 extern MPIOutputModifier oomph_mpi_output;
822
823 //=== Forward DenseMatrix class
824 template<class T>
825 class DenseMatrix;
826
827 // forward declaration of oomph-communicator class
828 // class OomphCommunicator;
829
830#endif
831
832
833 //======================================================================
834 /// MPI_Helpers class contains static helper methods to support MPI
835 /// within oomph-lib. The methods init(...) and finalize() initialize and
836 /// finalize MPI in oomph-lib and manage the oomph-libs global communicator
837 /// communicator_pt().
838 /// NOTE: This class encapsulates static helper methods and instances of it
839 /// CANNOT be instantiated.
840 //=====================================================================
842 {
843 public:
844 /// initialise mpi (oomph-libs equivalent of MPI_Init(...))
845 /// Initialises MPI and creates the global oomph-lib communicator.
846 /// If optional boolean flag is set to false, we use
847 /// MPI_COMM_WORLD itself as oomph-lib's communicator. Defaults to true.
848 static void init(int argc,
849 char** argv,
850 const bool& make_duplicate_of_mpi_comm_world = true);
851
852 /// finalize mpi (oomph-lib equivalent of MPI_Finalize())
853 /// Deletes the global oomph-lib communicator and finalizes MPI.
854 static void finalize();
855
856 /// access to global communicator. This is the oomph-lib equivalent of
857 /// MPI_COMM_WORLD
859
860 /// return true if MPI has been initialised
862 {
864 }
865
866 private:
867 /// private default constructor definition (to prevent instances of
868 /// the class being instantiated)
870
871 /// private copy constructor definition (to prevent instances of
872 /// the class being instantiated)
874
875 /// Bool set to true if MPI has been initialised
877
878 /// the global communicator
880 };
881
882
883 //====================================================================
884 // Namespace for flagging up obsolete parts of the code
885 //====================================================================
886 namespace ObsoleteCode
887 {
888 // Flag up obsolete parts of the code
889 extern bool FlagObsoleteCode;
890
891 // Output warning message
892 extern void obsolete();
893
894 // Output specified warning message
895 extern void obsolete(const std::string& message);
896
897 } // namespace ObsoleteCode
898
899 //====================================================================
900 // Namespace for tecplot stuff
901 //====================================================================
902 namespace TecplotNames
903 {
904 // Tecplot colours
905 extern Vector<std::string> colour;
906
907 // Setup tecplot colours namespace
908 extern void setup();
909
910 } // namespace TecplotNames
911
912
913#ifdef LEAK_CHECK
914
915 //====================================================================
916 // Namespace for leak check: Keep a running count of all instantiated
917 // objects -- add your own if you want to...
918 //====================================================================
919 namespace LeakCheckNames
920 {
921 extern long QuadTree_build;
922 extern long OcTree_build;
923 extern long QuadTreeForest_build;
924 extern long OcTreeForest_build;
925 extern long RefineableQElement<2> _build;
926 extern long RefineableQElement<3> _build;
927 extern long MacroElement_build;
928 extern long HangInfo_build;
929 extern long Node_build;
930 extern long GeomReference_build;
932 extern long AlgebraicNode_build;
933
934 // Reset counters
935 extern void reset();
936
937 // Doc counters
938 extern void doc();
939 } // namespace LeakCheckNames
940
941#endif
942
943 //====================================================================
944 // Namespace for pause() command
945 //====================================================================
946 namespace PauseFlags
947 {
948 // Flag to enable pausing code
949 extern bool PauseFlag;
950
951 } // namespace PauseFlags
952
953 /// Pause and dump out message
954 void pause(std::string message);
955
956
957 //=============================================================================
958 /// Helper for recording execution time.
959 //=============================================================================
960 namespace TimingHelpers
961 {
962 /// returns the time in seconds after some point in past
963 double timer();
964
965 /// Returns a nicely formatted string from an input time in seconds;
966 /// the format depends on the size of time, e.g.:
967 /// 86510 will be printed as 1d 1m:50
968 /// 3710 will be printed as 1h:01:50
969 /// 700 will be printed as 11m:40
970 /// 59.15 will be printed as 59.2s
971 std::string convert_secs_to_formatted_string(const double& time_in_sec);
972
973 } // end of namespace TimingHelpers
974
975
976 ////////////////////////////////////////////////////////////////////
977 ////////////////////////////////////////////////////////////////////
978 ////////////////////////////////////////////////////////////////////
979
980
981 //===============================================================
982 /// Namespace with helper functions to assess total memory usage
983 /// on the fly using system() -- details are very machine specific! This just
984 /// provides the overall machinery with default settings for
985 /// our own (linux machines). Uses the system command
986 /// to spawn a command that computes the total memory usage
987 /// on the machine where this is called. [Disclaimer: works
988 /// on my machine(s) -- no guarantees for any other platform;
989 /// Linux or not. MH]
990 //===============================================================
991 namespace MemoryUsage
992 {
993 /// Boolean to suppress synchronisation of doc memory
994 /// usage on processors (via mpi barriers). True (i.e. sync is
995 /// is suppressed by default because not all processors may
996 /// execute the reach the relevant doc memory usage statements
997 /// causing the code to hang).
999
1000 /// String containing system command that obtains memory usage
1001 /// of all processes.
1002 /// Default assignment for Linux. [Disclaimer: works on my machine(s) --
1003 /// no guarantees for any other platform; Linux or not. MH]
1004 extern std::string My_memory_usage_system_string;
1005
1006 /// Bool allowing quick bypassing of ALL operations related
1007 /// to memory usage monitoring -- this allows the code to remain
1008 /// "instrumented" without incurring the heavy penalties associated
1009 /// with the system calls and i/o. Default setting: false.
1011
1012 /// String containing name of file in which we document
1013 /// my memory usage -- you may want to change this to allow different
1014 /// processors to write to separate files (especially in mpi
1015 /// context). Note that file is appended to
1016 /// so it ought to be emptied (either manually or by calling
1017 /// helper function empty_memory_usage_file()
1018 extern std::string My_memory_usage_filename;
1019
1020 /// Function to empty file that records my memory usage in
1021 /// file whose name is specified by My_memory_usage_filename.
1023
1024#ifdef OOMPH_HAS_UNISTDH
1025
1026 /// Doc my memory usage, prepended by string (which allows
1027 /// identification from where the function is called, say) that records
1028 /// memory usage in file whose name is specified by
1029 /// My_memory_usage_filename. Data is appended to that file; wipe it with
1030 /// empty_my_memory_usage_file(). Note: This requires getpid() which is
1031 /// defined in unistd.h so if you don't have that we won't build that
1032 /// function!
1033 void doc_my_memory_usage(const std::string& prefix_string = 0);
1034
1035#endif
1036
1037 /// String containing system command that obtains total memory usage.
1038 /// Default assignment for Linux. [Disclaimer: works on my machine(s) --
1039 /// no guarantees for any other platform; Linux or not. MH]
1040 extern std::string Total_memory_usage_system_string;
1041
1042 /// String containing name of file in which we document total
1043 /// memory usage -- you may want to change this to allow different
1044 /// processors to write to separate files (especially in mpi
1045 /// context). Note that file is appended to
1046 /// so it ought to be emptied (either manually or by calling
1047 /// helper function empty_memory_usage_file()
1048 extern std::string Total_memory_usage_filename;
1049
1050 /// Function to empty file that records total memory usage in
1051 /// file whose name is specified by Total_memory_usage_filename.
1053
1054 /// Doc total memory usage, prepended by string (which allows
1055 /// identification from where the function is called, say) that records
1056 /// mem usage in file whose name is specified by
1057 /// Total_memory_usage_filename. Data is appended to that file; wipe it with
1058 /// empty_memory_usage_file().
1059 void doc_total_memory_usage(const std::string& prefix_string = "");
1060
1061 /// Function to empty file that records total and local memory usage
1062 /// in appropriate files
1064
1065 /// Doc total and local memory usage, prepended by string (which
1066 /// allows identification from where the function is called, say)
1067 void doc_memory_usage(const std::string& prefix_string = "");
1068
1069 /// String containing system command that runs "top" (or equivalent)
1070 /// "indefinitely" and writes to file specified in Top_output_filename.
1071 /// Default assignment for Linux. [Disclaimer: works on my machine(s) --
1072 /// no guarantees for any other platform; Linux or not. MH]
1073 extern std::string Top_system_string;
1074
1075 /// String containing name of file in which we document "continuous"
1076 /// output from "top" (or equivalent)-- you may want to change this to
1077 /// allow different processors to write to separate files (especially in mpi
1078 /// context). Note that file is appended to
1079 /// so it ought to be emptied (either manually or by calling
1080 /// helper function empty_top_file()
1081 extern std::string Top_output_filename;
1082
1083 /// Function to empty file that records continuous output from top in
1084 /// file whose name is specified by Top_output_filename
1085 void empty_top_file();
1086
1087 /// Start running top continuously and output (append) into
1088 /// file specified by Top_output_filename. Wipe that file with
1089 /// empty_top_file() first if you wish. Note that this is again
1090 /// quite Linux specific and unlikely to work on other operating systems.
1091 /// Insert optional comment into output file before starting.
1092 void run_continous_top(const std::string& comment = "");
1093
1094 /// Stop running top continuously. Note that this is
1095 /// again quite Linux specific and unlikely to work on other operating
1096 /// systems.
1097 /// Insert optional comment into output file before stopping.
1098 void stop_continous_top(const std::string& comment = "");
1099
1100 /// Insert comment into running continuous top output
1101 void insert_comment_to_continous_top(const std::string& comment);
1102
1103 } // end of namespace MemoryUsage
1104
1105
1106 ////////////////////////////////////////////////////////////////
1107 ////////////////////////////////////////////////////////////////
1108 ////////////////////////////////////////////////////////////////
1109
1110 // Forward decl.
1111 class Problem;
1112 template<class T>
1113 class DenseMatrix;
1114
1115 /// Function base class for exact solutions/initial conditions/boundary
1116 /// conditions. This is needed so that we can have solutions that depend
1117 /// on problem parameters with resorting to global variables.
1119 {
1120 public:
1121 // Some typedefs first:
1122
1123 /// General function of space and time which returns a double.
1124 typedef double (*TimeSpaceToDoubleFctPt)(const double& t,
1125 const Vector<double>& x);
1126
1127 /// General function of space and time which returns a vector of doubles.
1129 const double& t, const Vector<double>& x);
1130
1131 /// General function of time, space and a value vector which returns a
1132 /// vector of doubles.
1134 const double& t, const Vector<double>& x, const Vector<double>& u);
1135
1136 /// Virtual destructor
1138
1139 /// Call the function.
1140 virtual Vector<double> operator()(const double& t,
1141 const Vector<double>& x) const = 0;
1142
1143 /// Call the derivative function.
1144 virtual Vector<double> derivative(const double& t,
1145 const Vector<double>& x,
1146 const Vector<double>& u) const = 0;
1147
1148 /// The derivatives of the derivative function with respect to u (note
1149 /// that this is not quite the jacobian of the residuals for an ODE
1150 /// problem defined by this solution: you also need the time derivative
1151 /// part there). Broken virtual function because not often needed.
1152 virtual void jacobian(const double& t,
1153 const Vector<double>& x,
1154 const Vector<double>& u,
1156 {
1157 std::string err = "No Jacobian function implemented";
1158 throw OomphLibError(
1160 }
1161
1162 /// Is a jacobian function implemented?
1163 virtual bool have_jacobian() const
1164 {
1165 return false;
1166 }
1167
1168 /// Overload to grab data from the problem.
1169 virtual void initialise_from_problem(const Problem* problem_pt) {}
1170 };
1171
1172
1173 /// Function class for a simple function with no external parameters (just
1174 /// stores a function pointer, only needed for compatability).
1176 {
1177 // This could easily be extended to take
1178 // FiniteElement::UnsteadyExactSolutionFctPt function (i.e. functions
1179 // where the output is placed into a given vector rather than returned)
1180 // as well--just add the appropriate storage pointers and constructors.
1181
1182 public:
1183 // Constructors:
1184
1186 {
1187 Solution_fpt = 0;
1188 Derivative_fpt = 0;
1189 }
1190
1196
1203
1204 virtual ~SolutionFunctor() {}
1205
1207 {
1208 Solution_fpt = that.Solution_fpt;
1209 Derivative_fpt = that.Derivative_fpt;
1210 }
1211
1213 {
1214 this->Solution_fpt = that.Solution_fpt;
1215 this->Derivative_fpt = that.Derivative_fpt;
1216 }
1217
1218 /// Call the function.
1219 virtual Vector<double> operator()(const double& t,
1220 const Vector<double>& x) const
1221 {
1222#ifdef PARANOID
1223 if (Solution_fpt == 0)
1224 {
1225 std::string err = "Solution_fpt is null!";
1226 throw OomphLibError(
1228 }
1229#endif
1230 return Solution_fpt(t, x);
1231 }
1232
1233 /// Call the derivative function.
1234 virtual Vector<double> derivative(const double& t,
1235 const Vector<double>& x,
1236 const Vector<double>& u) const
1237 {
1238#ifdef PARANOID
1239 if (Derivative_fpt == 0)
1240 {
1241 std::string err = "Derivative_fpt is null!";
1242 throw OomphLibError(
1244 }
1245#endif
1246 return Derivative_fpt(t, x, u);
1247 }
1248
1249 /// Storage for solution
1251
1252 /// Storage for derivative
1254 };
1255
1256
1257} // namespace oomph
1258#endif
static char t char * s
Definition cfortran.h:568
cstr elem_len * i
Definition cfortran.h:603
char t
Definition cfortran.h:568
Function-type-object to perform absolute comparison of objects. Apparently this inlines better.
bool operator()(const T &x, const T &y) const
Comparison. Are the values identical or not?
Information for documentation of results: Directory and file number to enable output in the form RESL...
std::string & label()
String used (e.g.) for labeling output files.
std::string label() const
String used (e.g.) for labeling output files. Const version.
unsigned Number
Number to label output file, say.
void enable_doc()
Enable documentation.
bool Doc_flag
Doc or don't?
unsigned number() const
Number used (e.g.) for labeling output files. Const version.
bool is_doc_enabled() const
Are we documenting?
bool Directory_must_exist
Boolean flag to decide response if an output directory doesn't exist: If true, we terminate code exec...
void disable_doc()
Disable documentation.
void disable_error_if_directory_does_not_exist()
Call to issue a warning if the directory does not exists.
std::string directory() const
Output directory.
std::string Directory
Directory name.
void set_directory(const std::string &directory)
Set output directory (we try to open a file in it to see if the directory exists – if it doesn't we'l...
unsigned & number()
Number used (e.g.) for labeling output files.
void enable_error_if_directory_does_not_exist()
Call to throw an error if directory does not exist.
DocInfo(const std::string &directory)
Constructor with specific directory.
std::string number_as_string() const
Get number as a string (useful to completely avoid C-strings).
std::string Label
String to label output file, say.
DocInfo()
Constructor. Default settings: Current directory, step ‘0’, label="", full documentation enabled and ...
Collection of data structures for storing information about linear solves. Currently only contains st...
void setup_new_time_step()
Set up a new vector of pairs for a new time step.
Vector< Vector< Vector< double > > > Iterations_and_times
Storage for number of iterations during Newton steps.
unsigned current_nnewton_step() const
The number of Newton steps.
DocLinearSolverInfo()
Constructor. Initialised the Iterations_and_times vector of vector of pairs.
Vector< Vector< Vector< double > > > & iterations_and_times()
Accessor function for the iteration and times.
void add_iteration_and_time(unsigned iter, double prec_setup_time, double linear_solver_time)
Add a new iteration and time pair.
Vector< Vector< Vector< double > > > iterations_and_times() const
Accessor function for the iteration and times (const version).
unsigned current_ntime_step() const
The number of time steps.
double size() const
Calculate the size of the element (length, area, volume,...) in Eulerian computational coordinates....
Definition elements.cc:4320
MPI output modifier: Precedes every output by specification of the processor ID. Output can be restri...
MPIOutputModifier()
Constructor – initialise flags for output from all processors.
void restrict_output_to_single_processor(const unsigned &output_rank=0)
Switch to ensure output is only produced from a single processor (default: Master node,...
OomphCommunicator *& communicator_pt()
Return pointer to communicator.
OomphCommunicator * Communicator_pt
Communicator.
virtual bool operator()(std::ostream &stream)
Precede the output by the processor ID but output everything.
bool Output_from_single_processor
Boolean to control if output is performed only on a single processor (default: false)
unsigned Output_rank
Rank of single processor that produces output (only used if Output_from_single_processor=true.
void allow_output_from_all_processors()
Switch to ensure output is only produced from a single processor (default: Master node,...
MPI_Helpers class contains static helper methods to support MPI within oomph-lib. The methods init(....
static void finalize()
finalize mpi (oomph-lib equivalent of MPI_Finalize()) Deletes the global oomph-lib communicator and f...
static void init(int argc, char **argv, const bool &make_duplicate_of_mpi_comm_world=true)
initialise mpi (oomph-libs equivalent of MPI_Init(...)) Initialises MPI and creates the global oomph-...
static OomphCommunicator * Communicator_pt
the global communicator
static bool mpi_has_been_initialised()
return true if MPI has been initialised
static bool MPI_has_been_initialised
Bool set to true if MPI has been initialised.
static OomphCommunicator * communicator_pt()
access to global communicator. This is the oomph-lib equivalent of MPI_COMM_WORLD
MPI_Helpers(const MPI_Helpers &)
private copy constructor definition (to prevent instances of the class being instantiated)
MPI_Helpers()
private default constructor definition (to prevent instances of the class being instantiated)
An oomph-lib wrapper to the MPI_Comm communicator object. Just contains an MPI_Comm object (which is ...
std::ostream *& stream_pt()
Access function for the stream pointer.
An OomphLibError object which should be thrown when an run-time error is encountered....
A base class that contains a single virtual member function: The () operator that may be used to modi...
////////////////////////////////////////////////////////////////// //////////////////////////////////...
Definition problem.h:154
Function base class for exact solutions/initial conditions/boundary conditions. This is needed so tha...
virtual Vector< double > operator()(const double &t, const Vector< double > &x) const =0
Call the function.
virtual void initialise_from_problem(const Problem *problem_pt)
Overload to grab data from the problem.
Vector< double >(* TimeSpaceValueToDoubleVectFctPt)(const double &t, const Vector< double > &x, const Vector< double > &u)
General function of time, space and a value vector which returns a vector of doubles.
virtual void jacobian(const double &t, const Vector< double > &x, const Vector< double > &u, DenseMatrix< double > &jacobian) const
The derivatives of the derivative function with respect to u (note that this is not quite the jacobia...
virtual ~SolutionFunctorBase()
Virtual destructor.
double(* TimeSpaceToDoubleFctPt)(const double &t, const Vector< double > &x)
General function of space and time which returns a double.
virtual Vector< double > derivative(const double &t, const Vector< double > &x, const Vector< double > &u) const =0
Call the derivative function.
Vector< double >(* TimeSpaceToDoubleVectFctPt)(const double &t, const Vector< double > &x)
General function of space and time which returns a vector of doubles.
virtual bool have_jacobian() const
Is a jacobian function implemented?
Function class for a simple function with no external parameters (just stores a function pointer,...
void operator=(const SolutionFunctor &that)
TimeSpaceValueToDoubleVectFctPt Derivative_fpt
Storage for derivative.
virtual Vector< double > operator()(const double &t, const Vector< double > &x) const
Call the function.
SolutionFunctor(TimeSpaceToDoubleVectFctPt solution_fpt, TimeSpaceValueToDoubleVectFctPt derivative_fpt)
TimeSpaceToDoubleVectFctPt Solution_fpt
Storage for solution.
virtual Vector< double > derivative(const double &t, const Vector< double > &x, const Vector< double > &u) const
Call the derivative function.
SolutionFunctor(const SolutionFunctor &that)
SolutionFunctor(TimeSpaceToDoubleVectFctPt solution_fpt)
TAdvectionDiffusionReactionElement<NREAGENT,DIM,NNODE_1D> elements are isoparametric triangular DIM-d...
Vector< clock_t > Timing
Cumulative timings.
double cumulative_time(const unsigned &i)
Report time accumulated by i-th timer.
void set_ntimers(const unsigned &ntimers)
Set number of timings that can be recorded in parallel.
Timer(const unsigned &n_timer)
Constructor: Specify number of timers.
Vector< clock_t > Start_time
Start times of active timers.
void reset(const unsigned &i)
Reset i-th timer.
void reset()
Reset all timers.
void start(const unsigned &i)
(Re-)start i-th timer
void halt(const unsigned &i)
Halt i-th timer.
A slight extension to the standard template vector class so that we can include "graceful" array rang...
Definition Vector.h:58
void set_text_effect(std::string text_effect)
Function to change text effect. NOTE: This assumes the user knows what they're doing/assigning; no er...
std::string Text_effect
Variable to decide on effects.
std::string Black
The code for each type of colour.
void broken_assign(const std::string &class_name)
Issue error message and terminate execution.
void broken_copy(const std::string &class_name)
Issue error message and terminate execution.
void setup(int argc, char **argv)
Set values.
void doc_available_flags()
Document available command line flags.
std::map< std::string, ArgInfo< bool > > Specified_command_line_flag
Map to indicate an input flag as having been set.
char ** Argv
Arguments themselves.
bool command_line_flag_has_been_set(const std::string &flag)
Check if command line flag has been set (value will have been assigned directly).
void specify_command_line_flag(const std::string &command_line_flag, const std::string &doc)
Specify possible argument-free command line flag.
void check_arg_index(const int &argc, const int &arg_index)
Helper function to check if command line index is legal.
void doc_all_flags(std::ostream &outstream)
Document the values of all flags (specified or not).
std::map< std::string, ArgInfo< std::string > > Specified_command_line_string_pt
Map to associate an input flag with a string – specified via pointer.
std::map< std::string, ArgInfo< int > > Specified_command_line_int_pt
Map to associate an input flag with an int – specified via pointer.
void parse_and_assign(int argc, char *argv[], const bool &throw_on_unrecognised_args)
Parse command line, check for recognised flags and assign associated values.
std::map< std::string, ArgInfo< double > > Specified_command_line_double_pt
Map to associate an input flag with a double – specified via pointer.
int Argc
Number of arguments + 1.
void output()
Doc the command line arguments.
std::map< std::string, ArgInfo< unsigned > > Specified_command_line_unsigned_pt
Map to associate an input flag with an unsigned – specified via pointer.
void doc_specified_flags()
Document specified command line flags.
void reset()
Reset all timers.
double cumulative_time(const unsigned &i)
Report time accumulated by i-th timer.
void set_ntimers(const unsigned &ntimers)
Set number of timings that can be recorded in parallel.
Vector< clock_t > Timing
Cumulative timings.
void halt(const unsigned &i)
Halt i-th timer.
Vector< clock_t > Start_time
Start times of active timers.
void start(const unsigned &i)
(Re-)start i-th timer
std::string debug_string(const std::string &filename, const int &line_number, const std::string &message, const bool &shorten, const bool &start_on_new_line)
Return the concaternation of the initials of the input file name and line number. The make_new_line f...
long AlgebraicNodeNodeUpdateInfo_build
long RefineableQElement< 2 > _build
const std::complex< double > I(0.0, 1.0)
The imaginary unit.
const double Pi
50 digits from maple
void empty_top_file()
Function to empty file that records continuous output from top in file whose name is specified by Top...
std::string Top_output_filename
String containing name of file in which we document "continuous" output from "top" (or equivalent)– y...
bool Bypass_all_memory_usage_monitoring
Bool allowing quick bypassing of ALL operations related to memory usage monitoring – this allows the ...
void doc_total_memory_usage(const std::string &prefix_string)
Doc total memory usage, prepended by string (which allows identification from where the function is c...
void insert_comment_to_continous_top(const std::string &comment)
Insert comment into running continuous top output.
void doc_my_memory_usage(const std::string &prefix_string)
Doc my memory usage, prepended by string (which allows identification from where the function is call...
void empty_memory_usage_files()
Function to empty file that records total and local memory usage in appropriate files.
void run_continous_top(const std::string &comment)
Start running top continuously and output (append) into file specified by Top_output_filename....
std::string Top_system_string
String containing system command that runs "top" (or equivalent) "indefinitely" and writes to file sp...
void stop_continous_top(const std::string &comment)
Stop running top continuously. Note that this is again quite Linux specific and unlikely to work on o...
bool Suppress_mpi_synchronisation
Boolean to suppress synchronisation of doc memory usage on processors (via mpi barriers)....
void empty_total_memory_usage_file()
Function to empty file that records total memory usage in file whose name is specified by Total_memor...
std::string Total_memory_usage_system_string
String containing system command that obtains total memory usage. Default assignment for linux....
void doc_memory_usage(const std::string &prefix_string)
Doc total and local memory usage, prepended by string (which allows identification from where the fun...
std::string My_memory_usage_filename
String containing name of file in which we document my memory usage – you may want to change this to ...
void empty_my_memory_usage_file()
Function to empty file that records my memory usage in file whose name is specified by My_memory_usag...
std::string My_memory_usage_system_string
String containing system command that obtains memory usage of all processes. Default assignment for l...
std::string Total_memory_usage_filename
String containing name of file in which we document total memory usage – you may want to change this ...
void obsolete()
Output warning message.
bool FlagObsoleteCode
Flag up obsolete parts of the code.
bool PauseFlag
Flag to enable pausing code – pause the code by default.
double second_invariant(const DenseMatrix< double > &tensor)
Compute second invariant of tensor.
void split_string(const std::string &s, char delim, Vector< std::string > &elems)
Split a string, s, into a vector of strings where ever there is an instance of delimiter (i....
std::string to_string(T object, unsigned float_precision=8)
Conversion function that should work for anything with operator<< defined (at least all basic types).
std::string to_lower(const std::string &input)
Convert a string to lower case (outputs a copy).
std::string to_upper(const std::string &input)
Convert a string to upper case (outputs a copy).
Vector< std::string > colour
Tecplot colours.
void setup()
Setup namespace.
double timer()
returns the time in seconds after some point in past
std::string convert_secs_to_formatted_string(const double &time_in_sec)
Returns a nicely formatted string from an input time in seconds; the format depends on the size of ti...
std::string get_type_name(T &obj)
Get the type name of an object. Only for use in debugging, do not write real code using this function...
DRAIG: Change all instances of (SPATIAL_DIM) to (DIM-1).
Target checked_static_cast(Source *x)
Checked static cast. Only use this cast if ALL of these are true:
void pause(std::string message)
Pause and display message.
Target checked_dynamic_cast(Source *x)
Runtime checked dynamic cast. This is the safe but slightly slower cast. Use it in any of these cases...
MPIOutputModifier oomph_mpi_output
Single (global) instantiation of the mpi output modifier.
OomphInfo oomph_info
Single (global) instantiation of the OomphInfo object – this is used throughout the library as a "rep...
Structure to store information on a command line argument.
ArgInfo()
Default constructor. We need this to be able to store these things in maps.
T * arg_pt
The place to put the argument's value when it is set.
std::string doc
Information about what the argument does.
ArgInfo(const bool &is_set, T *arg_pt, const std::string &doc)
Proper constructor.
bool is_set
Has this argument been set?