diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..0b7a604382 --- /dev/null +++ b/.clang-format @@ -0,0 +1,171 @@ +# +# The clang-format (Clang 6) style file used by deal.II. +# + +AccessModifierOffset: -2 + +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true + +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false + +AlwaysBreakAfterReturnType: All +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true + +BinPackArguments: false +BinPackParameters: false + +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterExternBlock: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: true + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false + +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializers: BeforeComma +BreakStringLiterals: false + +ColumnLimit: 80 + +CompactNamespaces: false + +ConstructorInitializerIndentWidth: 2 + +ContinuationIndentWidth: 2 + +Cpp11BracedListStyle: true + +DerivePointerAlignment: false + +FixNamespaceComments: true + +IncludeBlocks: Regroup +IncludeCategories: +# config.h must always be first: + - Regex: "deal.II/base/config.h" + Priority: -1 +# deal.II folders in sorted order: + - Regex: "deal.II/algorithms/.*\\.h" + Priority: 110 + - Regex: "deal.II/base/.*\\.h" + Priority: 120 + - Regex: "deal.II/boost_adaptors/.*\\.h" + Priority: 125 + - Regex: "deal.II/differentiation/.*\\.h" + Priority: 130 + - Regex: "deal.II/distributed/.*\\.h" + Priority: 140 + - Regex: "deal.II/dofs/.*\\.h" + Priority: 150 + - Regex: "deal.II/fe/.*\\.h" + Priority: 160 + - Regex: "deal.II/gmsh/.*\\.h" + Priority: 170 + - Regex: "deal.II/grid/.*\\.h" + Priority: 180 + - Regex: "deal.II/hp/.*\\.h" + Priority: 190 + - Regex: "deal.II/integrators/.*\\.h" + Priority: 200 + - Regex: "deal.II/lac/.*\\.h" + Priority: 210 + - Regex: "deal.II/matrix_free/.*\\.h" + Priority: 220 + - Regex: "deal.II/meshworker/.*\\.h" + Priority: 230 + - Regex: "deal.II/multigrid/.*\\.h" + Priority: 240 + - Regex: "deal.II/non_matching/.*\\.h" + Priority: 250 + - Regex: "deal.II/numerics/.*\\.h" + Priority: 260 + - Regex: "deal.II/opencascade/.*\\.h" + Priority: 270 + - Regex: "deal.II/optimization/.*\\.h" + Priority: 280 + - Regex: "deal.II/particles/.*\\.h" + Priority: 290 + - Regex: "deal.II/physics/.*\\.h" + Priority: 300 + - Regex: "deal.II/sundials/.*\\.h" + Priority: 310 +# put boost right after deal: + - Regex: "" + Priority: 500 +# try to group PETSc headers: + - Regex: "" + Priority: 1000 +# try to catch all third party headers and put them after deal.II but before +# standard headers: + - Regex: "<.*\\.(h|hpp|hxx)>" + Priority: 2000 +# match all standard headers. Things like '#include ' should be +# surrounded by #ifdef checks (which will not be merged by clang-format) so they +# should not be caught here + - Regex: "<[a-z_]+>" + Priority: 100000 + +IndentCaseLabels: true +IndentPPDirectives: AfterHash +IndentWidth: 2 + +IndentWrappedFunctionNames: false + +KeepEmptyLinesAtTheStartOfBlocks: false + +Language: Cpp + +MaxEmptyLinesToKeep: 3 + +NamespaceIndentation: All + +PenaltyBreakBeforeFirstCallParameter: 90 + +PointerAlignment: Right + +ReflowComments: true +CommentPragmas: '( \| |\*--|
  • |@ref | @p |@param |@name |@returns |@warning |@ingroup |@author |@date |@related |@relates |@relatesalso |@deprecated |@image |@return |@brief |@attention |@copydoc |@addtogroup |@todo |@tparam |@see |@note |@skip |@skipline |@until |@line |@dontinclude |@include)' + +SortIncludes: true +SortUsingDeclarations: true + +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +SpacesInSquareBrackets: false + +Standard: Cpp11 + +TabWidth: 2 + +UseTab: Never diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..5b4e0fd778 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,9 @@ +# Settings file automatically used by clang-tidy +# +# See ./contrib/utilities/run_clang_tidy.sh for details + +# We disable performance-inefficient-string-concatenation because we don't care about "a"+to_string(5)+... + +Checks: "-*,cppcoreguidelines-pro-type-static-cast-downcast,google-readability-casting,modernize-*,-modernize-pass-by-value,-modernize-raw-string-literal,-modernize-use-auto,-modernize-use-override,-modernize-use-default-member-init,-modernize-use-transparent-functors,use-emplace,mpi-*,performance-*,-performance-inefficient-string-concatenation" + +WarningsAsErrors: '*' diff --git a/applications/cylinder/cylinder.cc b/applications/cylinder/cylinder.cc index 9136a0190b..3edf5735e8 100644 --- a/applications/cylinder/cylinder.cc +++ b/applications/cylinder/cylinder.cc @@ -1,19 +1,26 @@ #include "glsNS.h" template -class VonKarmanNavierStokes : public GLSNavierStokesSolver { +class VonKarmanNavierStokes : public GLSNavierStokesSolver +{ public: VonKarmanNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void run(); - void runTest(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + run(); + void + runTest(); }; -template void VonKarmanNavierStokes::run() { +template +void +VonKarmanNavierStokes::run() +{ this->read_mesh(); - Point circleCenter(8, 8); + Point circleCenter(8, 8); static const SphericalManifold boundary(circleCenter); this->triangulation.set_all_manifold_ids_on_boundary(0, 0); this->triangulation.set_manifold(0, boundary); @@ -22,22 +29,26 @@ template void VonKarmanNavierStokes::run() { this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - this->finish_time_step(); - } + while (this->simulationControl.integrate()) + { + printTime(this->pcout, this->simulationControl); + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + this->finish_time_step(); + } } -template void VonKarmanNavierStokes::runTest() { +template +void +VonKarmanNavierStokes::runTest() +{ GridIn grid_in; grid_in.attach_triangulation(this->triangulation); std::ifstream input_file(this->nsparam.mesh.fileName); grid_in.read_msh(input_file); - Point circleCenter(8, 8); + Point circleCenter(8, 8); static const SphericalManifold boundary(circleCenter); this->triangulation.set_all_manifold_ids_on_boundary(0, 0); this->triangulation.set_manifold(0, boundary); @@ -46,61 +57,71 @@ template void VonKarmanNavierStokes::runTest() { this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - this->refine_mesh(); - this->finish_time_step(); - for (unsigned int i = 0; i < this->forces_.size(); ++i) { - this->pcout << " fx : " << this->forces_[i][0] << std::endl; + while (this->simulationControl.integrate()) + { + printTime(this->pcout, this->simulationControl); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + this->refine_mesh(); + this->finish_time_step(); + for (unsigned int i = 0; i < this->forces_.size(); ++i) + { + this->pcout << " fx : " << this->forces_[i][0] << std::endl; + } } - } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> nsparam; - nsparam.declare(prm); - // Parsing of the file - prm.parse_input(argv[1]); - nsparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> nsparam; + nsparam.declare(prm); + // Parsing of the file + prm.parse_input(argv[1]); + nsparam.parse(prm); - VonKarmanNavierStokes<2> problem_2d(nsparam, - nsparam.femParameters.velocityOrder, - nsparam.femParameters.pressureOrder); - if (nsparam.test.enabled) - problem_2d.runTest(); - else - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + VonKarmanNavierStokes<2> problem_2d(nsparam, + nsparam.femParameters.velocityOrder, + nsparam.femParameters.pressureOrder); + if (nsparam.test.enabled) + problem_2d.runTest(); + else + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/initial_conditions/initial_conditions.cc b/applications/initial_conditions/initial_conditions.cc index f2538a45eb..5a5ebae571 100644 --- a/applications/initial_conditions/initial_conditions.cc +++ b/applications/initial_conditions/initial_conditions.cc @@ -1,16 +1,23 @@ #include "glsNS.h" #include "parameters.h" -template class ExactInitialSolution : public Function { +template +class ExactInitialSolution : public Function +{ public: - ExactInitialSolution() : Function(2) {} - virtual void vector_value(const Point &p, Vector &values) const; + ExactInitialSolution() + : Function(2) + {} + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void ExactInitialSolution::vector_value(const Point &p, - Vector &values) const { - double x = p[0]; - double y = p[1]; +void +ExactInitialSolution::vector_value(const Point &p, + Vector & values) const +{ + double x = p[0]; + double y = p[1]; values(0) = x; values(1) = y; if (dim == 3) @@ -18,17 +25,24 @@ void ExactInitialSolution::vector_value(const Point &p, } template -class InitialConditionsNavierStokes : public GLSNavierStokesSolver { +class InitialConditionsNavierStokes : public GLSNavierStokesSolver +{ public: InitialConditionsNavierStokes(NavierStokesSolverParameters nsparam, const unsigned int degreeVelocity, const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void runTest(); - void run(); + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + runTest(); + void + run(); }; -template void InitialConditionsNavierStokes::run() { +template +void +InitialConditionsNavierStokes::run() +{ this->read_mesh(); this->setup_dofs(); this->forcing_function = new NoForce; @@ -36,71 +50,89 @@ template void InitialConditionsNavierStokes::run() { this->nsparam.restartParameters.restart); } -template void InitialConditionsNavierStokes::runTest() { +template +void +InitialConditionsNavierStokes::runTest() +{ const int initialSize = this->nsparam.mesh.initialRefinement; this->make_cube_grid(initialSize); this->setup_dofs(); this->exact_solution = new ExactInitialSolution; this->set_initial_condition(Parameters::L2projection); double error_L2projection = this->calculate_L2_error(); - if (error_L2projection < 1e-9) { - this->pcout << "The L2projection initial condition is OK" << std::endl; - } else { - throw "L2projection initial condition error"; - } + if (error_L2projection < 1e-9) + { + this->pcout << "The L2projection initial condition is OK" << std::endl; + } + else + { + throw "L2projection initial condition error"; + } this->set_initial_condition(Parameters::nodal); double error_nodal = this->calculate_L2_error(); - if (error_nodal < 1e-9) { - this->pcout << "The nodal initial condition is OK" << std::endl; - } else { - throw "Nodal initial condition error"; - } + if (error_nodal < 1e-9) + { + this->pcout << "The nodal initial condition is OK" << std::endl; + } + else + { + throw "Nodal initial condition error"; + } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> nsparam; - nsparam.declare(prm); - // Parsing of the file - prm.parse_input(argv[1]); - nsparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> nsparam; + nsparam.declare(prm); + // Parsing of the file + prm.parse_input(argv[1]); + nsparam.parse(prm); - InitialConditionsNavierStokes<2> problem_2d( - nsparam, nsparam.femParameters.velocityOrder, + InitialConditionsNavierStokes<2> problem_2d( + nsparam, + nsparam.femParameters.velocityOrder, nsparam.femParameters.pressureOrder); - if (nsparam.test.enabled) - problem_2d.runTest(); - else - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + if (nsparam.test.enabled) + problem_2d.runTest(); + else + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/mms2d/mms2d.cc b/applications/mms2d/mms2d.cc index a425830c9c..61ec7fb776 100644 --- a/applications/mms2d/mms2d.cc +++ b/applications/mms2d/mms2d.cc @@ -1,96 +1,115 @@ #include "glsNS.h" #include "parameters.h" -template class MMSNavierStokes : public GLSNavierStokesSolver { +template +class MMSNavierStokes : public GLSNavierStokesSolver +{ public: MMSNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void run(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + run(); }; -template void MMSNavierStokes::run() { +template +void +MMSNavierStokes::run() +{ std::vector ErrorLog; std::vector wallTime; this->read_mesh(); this->setup_dofs(); - this->exact_solution = new ExactSolutionMMS; + this->exact_solution = new ExactSolutionMMS; this->forcing_function = new MMSSineForcingFunction; Timer timer; this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - timer.start(); - if (this->simulationControl.getIter() != 1) - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); + while (this->simulationControl.integrate()) { - double L2Error = this->calculate_L2_error(); - this->pcout << "L2Error U is : " - << std::setprecision( + printTime(this->pcout, this->simulationControl); + timer.start(); + if (this->simulationControl.getIter() != 1) + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + { + double L2Error = this->calculate_L2_error(); + this->pcout << "L2Error U is : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << L2Error << std::endl; - ErrorLog.push_back(L2Error); - wallTime.push_back((timer.wall_time())); + << L2Error << std::endl; + ErrorLog.push_back(L2Error); + wallTime.push_back((timer.wall_time())); + } + this->finish_time_step(); } - this->finish_time_step(); - } - if (this->this_mpi_process == 0) { - assert(wallTime.size() == ErrorLog.size()); - const int initialSize = this->nsparam.mesh.initialRefinement; - std::ofstream output_file("./L2Error-2D.dat"); - for (unsigned int i = 0; i < ErrorLog.size(); ++i) { - output_file << i + initialSize << " " << ErrorLog[i] << " " << wallTime[i] - << std::endl; + if (this->this_mpi_process == 0) + { + assert(wallTime.size() == ErrorLog.size()); + const int initialSize = this->nsparam.mesh.initialRefinement; + std::ofstream output_file("./L2Error-2D.dat"); + for (unsigned int i = 0; i < ErrorLog.size(); ++i) + { + output_file << i + initialSize << " " << ErrorLog[i] << " " + << wallTime[i] << std::endl; + } + output_file.close(); } - output_file.close(); - } } -int main(int argc, char *argv[]) { - try { - if (argc < 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc < 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - prm.parse_input(argv[1]); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + prm.parse_input(argv[1]); + NSparam.parse(prm); - MMSNavierStokes<2> problem_2d(NSparam, NSparam.femParameters.velocityOrder, - NSparam.femParameters.pressureOrder); - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + MMSNavierStokes<2> problem_2d(NSparam, + NSparam.femParameters.velocityOrder, + NSparam.femParameters.pressureOrder); + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/mms2d_unstructured/mms2d_unstructured.cc b/applications/mms2d_unstructured/mms2d_unstructured.cc index 7cb71b8896..8d235a087f 100644 --- a/applications/mms2d_unstructured/mms2d_unstructured.cc +++ b/applications/mms2d_unstructured/mms2d_unstructured.cc @@ -1,97 +1,116 @@ #include "glsNS.h" template -class MMSUnstructuredNavierStokes : public GLSNavierStokesSolver { +class MMSUnstructuredNavierStokes : public GLSNavierStokesSolver +{ public: MMSUnstructuredNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void runMMSUnstructured(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + runMMSUnstructured(); private: std::vector wallTime_; }; -template void MMSUnstructuredNavierStokes::runMMSUnstructured() { +template +void +MMSUnstructuredNavierStokes::runMMSUnstructured() +{ std::vector ErrorLog; std::vector wallTime; this->read_mesh(); this->setup_dofs(); - this->exact_solution = new ExactSolutionMMS; + this->exact_solution = new ExactSolutionMMS; this->forcing_function = new MMSSineForcingFunction; Timer timer; this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - timer.start(); - if (this->simulationControl.getIter() != 1) - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); + while (this->simulationControl.integrate()) { - double L2Error = this->calculate_L2_error(); - this->pcout << "L2Error U is : " - << std::setprecision( + printTime(this->pcout, this->simulationControl); + timer.start(); + if (this->simulationControl.getIter() != 1) + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + { + double L2Error = this->calculate_L2_error(); + this->pcout << "L2Error U is : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << L2Error << std::endl; - ErrorLog.push_back(L2Error); - wallTime.push_back((timer.wall_time())); + << L2Error << std::endl; + ErrorLog.push_back(L2Error); + wallTime.push_back((timer.wall_time())); + } + this->finish_time_step(); } - this->finish_time_step(); - } - if (this->this_mpi_process == 0) { - assert(wallTime.size() == ErrorLog.size()); - std::ofstream output_file("./L2Error-2D.dat"); - for (unsigned int i = 0; i < ErrorLog.size(); ++i) { - output_file << i << " " << ErrorLog[i] << " " << wallTime[i] << std::endl; + if (this->this_mpi_process == 0) + { + assert(wallTime.size() == ErrorLog.size()); + std::ofstream output_file("./L2Error-2D.dat"); + for (unsigned int i = 0; i < ErrorLog.size(); ++i) + { + output_file << i << " " << ErrorLog[i] << " " << wallTime[i] + << std::endl; + } + output_file.close(); } - output_file.close(); - } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - prm.parse_input(argv[1]); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + prm.parse_input(argv[1]); + NSparam.parse(prm); - MMSUnstructuredNavierStokes<2> problem_2d( - NSparam, NSparam.femParameters.velocityOrder, + MMSUnstructuredNavierStokes<2> problem_2d( + NSparam, + NSparam.femParameters.velocityOrder, NSparam.femParameters.pressureOrder); - problem_2d.runMMSUnstructured(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + problem_2d.runMMSUnstructured(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/mms3d/mms3d.cc b/applications/mms3d/mms3d.cc index 8232fb00c3..9f2d4847d2 100644 --- a/applications/mms3d/mms3d.cc +++ b/applications/mms3d/mms3d.cc @@ -1,119 +1,146 @@ #include "glsNS.h" -template class ExactSolutionMMS3D : public Function { +template +class ExactSolutionMMS3D : public Function +{ public: - ExactSolutionMMS3D() : Function(3) {} - virtual void vector_value(const Point &p, Vector &values) const; + ExactSolutionMMS3D() + : Function(3) + {} + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void ExactSolutionMMS3D::vector_value(const Point &p, - Vector &values) const { +void +ExactSolutionMMS3D::vector_value(const Point &p, + Vector & values) const +{ const double a = M_PI; - double x = p[0]; - double y = p[1]; + double x = p[0]; + double y = p[1]; const double z = p[2]; - values(0) = sin(a * x) * sin(a * x) * cos(a * y) * sin(a * y) * cos(a * z) * - sin(a * z); - values(1) = cos(a * x) * sin(a * x) * sin(a * y) * sin(a * y) * cos(a * z) * - sin(a * z); + values(0) = + sin(a * x) * sin(a * x) * cos(a * y) * sin(a * y) * cos(a * z) * sin(a * z); + values(1) = + cos(a * x) * sin(a * x) * sin(a * y) * sin(a * y) * cos(a * z) * sin(a * z); values(2) = -2 * cos(a * x) * sin(a * x) * cos(a * y) * sin(a * y) * sin(a * z) * sin(a * z); } -template class MMS3DNavierStokes : public GLSNavierStokesSolver { +template +class MMS3DNavierStokes : public GLSNavierStokesSolver +{ public: MMS3DNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void runMMS_3D(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + runMMS_3D(); }; -template void MMS3DNavierStokes::runMMS_3D() { +template +void +MMS3DNavierStokes::runMMS_3D() +{ std::vector ErrorLog; std::vector wallTime; - const int initialSize = this->nsparam.mesh.initialRefinement; + const int initialSize = this->nsparam.mesh.initialRefinement; this->read_mesh(); this->setup_dofs(); - this->exact_solution = new ExactSolutionMMS3D; + this->exact_solution = new ExactSolutionMMS3D; this->forcing_function = new MMS3DSineForcingFunction; Timer timer; this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - timer.start(); - if (this->simulationControl.getIter() != 1) { - this->refine_mesh(); - } - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); + while (this->simulationControl.integrate()) { - double L2Error = this->calculate_L2_error(); - this->pcout << "L2Error U is : " - << std::setprecision( + printTime(this->pcout, this->simulationControl); + timer.start(); + if (this->simulationControl.getIter() != 1) + { + this->refine_mesh(); + } + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + { + double L2Error = this->calculate_L2_error(); + this->pcout << "L2Error U is : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << L2Error << std::endl; - ErrorLog.push_back(L2Error); - wallTime.push_back((timer.wall_time())); + << L2Error << std::endl; + ErrorLog.push_back(L2Error); + wallTime.push_back((timer.wall_time())); + } + this->finish_time_step(); } - this->finish_time_step(); - } - if (this->this_mpi_process == 0) { - assert(wallTime.size() == ErrorLog.size()); - std::ofstream output_file("./L2Error-3D.dat"); - for (unsigned int i = 0; i < ErrorLog.size(); ++i) { - output_file << i + initialSize << " " << ErrorLog[i] << " " << wallTime[i] - << std::endl; + if (this->this_mpi_process == 0) + { + assert(wallTime.size() == ErrorLog.size()); + std::ofstream output_file("./L2Error-3D.dat"); + for (unsigned int i = 0; i < ErrorLog.size(); ++i) + { + output_file << i + initialSize << " " << ErrorLog[i] << " " + << wallTime[i] << std::endl; + } + output_file.close(); } - output_file.close(); - } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<3> NSparam; - NSparam.declare(prm); - // Parsing of the file - prm.parse_input(argv[1]); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<3> NSparam; + NSparam.declare(prm); + // Parsing of the file + prm.parse_input(argv[1]); + NSparam.parse(prm); - MMS3DNavierStokes<3> problem(NSparam, NSparam.femParameters.velocityOrder, - NSparam.femParameters.pressureOrder); - problem.runMMS_3D(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + MMS3DNavierStokes<3> problem(NSparam, + NSparam.femParameters.velocityOrder, + NSparam.femParameters.pressureOrder); + problem.runMMS_3D(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/poiseuille/poiseuille.cc b/applications/poiseuille/poiseuille.cc index 0f7f751684..e9edb737e3 100644 --- a/applications/poiseuille/poiseuille.cc +++ b/applications/poiseuille/poiseuille.cc @@ -1,116 +1,146 @@ -#include "glsNS.h" #include -template class ConstantXForce : public Function { +#include "glsNS.h" + +template +class ConstantXForce : public Function +{ public: - ConstantXForce() : Function(3){}; - virtual void vector_value(const Point &p, Vector &values) const; + ConstantXForce() + : Function(3){}; + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void ConstantXForce::vector_value(const Point & /*p*/, - Vector &values) const { +void +ConstantXForce::vector_value(const Point & /*p*/, + Vector &values) const +{ assert(dim == 2); values(0) = 1.; values(1) = 0.; } -template class ExactSolutionPoiseuille : public Function { +template +class ExactSolutionPoiseuille : public Function +{ public: - ExactSolutionPoiseuille() : Function(3) {} - virtual void vector_value(const Point &p, Vector &values) const; + ExactSolutionPoiseuille() + : Function(3) + {} + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void ExactSolutionPoiseuille::vector_value(const Point &p, - Vector &values) const { +void +ExactSolutionPoiseuille::vector_value(const Point &p, + Vector & values) const +{ assert(dim == 2); - const double H = 1.; - const double G = 1.; + const double H = 1.; + const double G = 1.; const double mu = 1.; // double x = p[0]; - double y = p[1]; + double y = p[1]; values(0) = 0.5 * G / mu * (y) * (H - y); values(1) = 0.; } template -class PeriodicPoiseuille : public GLSNavierStokesSolver { +class PeriodicPoiseuille : public GLSNavierStokesSolver +{ public: PeriodicPoiseuille(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void run(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + run(); }; -template void PeriodicPoiseuille::run() { +template +void +PeriodicPoiseuille::run() +{ this->read_mesh(); this->setup_dofs(); this->forcing_function = new ConstantXForce; - this->exact_solution = new ExactSolutionPoiseuille; + this->exact_solution = new ExactSolutionPoiseuille; ConvergenceTable table; this->set_initial_condition(this->nsparam.initialCondition->type); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - if (this->simulationControl.getIter() != 1) - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - table.add_value("cells", this->triangulation.n_global_active_cells()); - const double error = this->calculate_L2_error(); - table.add_value("error", error); - this->finish_time_step(); - } + while (this->simulationControl.integrate()) + { + printTime(this->pcout, this->simulationControl); + if (this->simulationControl.getIter() != 1) + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + table.add_value("cells", this->triangulation.n_global_active_cells()); + const double error = this->calculate_L2_error(); + table.add_value("error", error); + this->finish_time_step(); + } table.omit_column_from_convergence_rate_evaluation("cells"); table.evaluate_all_convergence_rates(ConvergenceTable::reduction_rate_log2); table.set_scientific("error", true); - if (this->this_mpi_process == 0) { - table.write_text(std::cout); - } + if (this->this_mpi_process == 0) + { + table.write_text(std::cout); + } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> nsparam; - nsparam.declare(prm); - // Parsing of the file - prm.parse_input(argv[1]); - nsparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> nsparam; + nsparam.declare(prm); + // Parsing of the file + prm.parse_input(argv[1]); + nsparam.parse(prm); - PeriodicPoiseuille<2> problem_2d(nsparam, - nsparam.femParameters.velocityOrder, - nsparam.femParameters.pressureOrder); - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + PeriodicPoiseuille<2> problem_2d(nsparam, + nsparam.femParameters.velocityOrder, + nsparam.femParameters.pressureOrder); + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/taylorcouette/taylorcouette.cc b/applications/taylorcouette/taylorcouette.cc index 48e0faca22..a7ca300b46 100644 --- a/applications/taylorcouette/taylorcouette.cc +++ b/applications/taylorcouette/taylorcouette.cc @@ -1,49 +1,64 @@ -#include "glsNS.h" #include -template class ExactSolutionTaylorCouette : public Function { +#include "glsNS.h" + +template +class ExactSolutionTaylorCouette : public Function +{ public: - ExactSolutionTaylorCouette() : Function(3) { + ExactSolutionTaylorCouette() + : Function(3) + { eta_ = 0.25; - ri_ = 0.25; + ri_ = 0.25; } - virtual void vector_value(const Point &p, Vector &values) const; + virtual void + vector_value(const Point &p, Vector &values) const; private: double eta_; double ri_ = 0.25; }; template -void ExactSolutionTaylorCouette::vector_value( - const Point &p, Vector &values) const { - double x = p[0]; - double y = p[1]; - double r = std::sqrt(x * x + y * y); - double theta = std::atan2(y, x); - double A = -(eta_ * eta_) / (1. - eta_ * eta_); - double B = ri_ * ri_ / (1. - eta_ * eta_); +void +ExactSolutionTaylorCouette::vector_value(const Point &p, + Vector & values) const +{ + double x = p[0]; + double y = p[1]; + double r = std::sqrt(x * x + y * y); + double theta = std::atan2(y, x); + double A = -(eta_ * eta_) / (1. - eta_ * eta_); + double B = ri_ * ri_ / (1. - eta_ * eta_); double utheta = A * r + B / r; - values(0) = -std::sin(theta) * utheta; - values(1) = std::cos(theta) * utheta; - values(2) = 0.; + values(0) = -std::sin(theta) * utheta; + values(1) = std::cos(theta) * utheta; + values(2) = 0.; } template -class TaylorCouetteNavierStokes : public GLSNavierStokesSolver { +class TaylorCouetteNavierStokes : public GLSNavierStokesSolver +{ public: TaylorCouetteNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure); - void run(); + const unsigned int degreeVelocity, + const unsigned int degreePressure); + void + run(); }; template TaylorCouetteNavierStokes::TaylorCouetteNavierStokes( - NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} + NavierStokesSolverParameters nsparam, + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) +{} -template void TaylorCouetteNavierStokes::run() { +template +void +TaylorCouetteNavierStokes::run() +{ Point circleCenter; if (dim == 2) circleCenter = Point(0, 0); @@ -51,76 +66,90 @@ template void TaylorCouetteNavierStokes::run() { this->setup_dofs(); this->forcing_function = new NoForce; - this->exact_solution = new ExactSolutionTaylorCouette; + this->exact_solution = new ExactSolutionTaylorCouette; ConvergenceTable table; this->iterate(this->simulationControl.firstIter()); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - if (this->simulationControl.firstIter()) { - this->iterate(this->simulationControl.firstIter()); - } else { - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - } - this->postprocess(); - table.add_value("cells", this->triangulation.n_global_active_cells()); + while (this->simulationControl.integrate()) + { + printTime(this->pcout, this->simulationControl); + if (this->simulationControl.firstIter()) + { + this->iterate(this->simulationControl.firstIter()); + } + else + { + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + } + this->postprocess(); + table.add_value("cells", this->triangulation.n_global_active_cells()); - const double error = this->calculate_L2_error(); - table.add_value("error", error); + const double error = this->calculate_L2_error(); + table.add_value("error", error); - this->finish_time_step(); - } + this->finish_time_step(); + } table.omit_column_from_convergence_rate_evaluation("cells"); table.evaluate_all_convergence_rates(ConvergenceTable::reduction_rate_log2); table.set_scientific("error", true); - if (this->this_mpi_process == 0) { - table.write_text(std::cout); - } + if (this->this_mpi_process == 0) + { + table.write_text(std::cout); + } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - // Parsing of the file - prm.parse_input(argv[1]); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + // Parsing of the file + prm.parse_input(argv[1]); + NSparam.parse(prm); - TaylorCouetteNavierStokes<2> problem_2d( - NSparam, NSparam.femParameters.velocityOrder, + TaylorCouetteNavierStokes<2> problem_2d( + NSparam, + NSparam.femParameters.velocityOrder, NSparam.femParameters.pressureOrder); - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/taylorcouette_unstructured/taylorcouette_unstructured.cc b/applications/taylorcouette_unstructured/taylorcouette_unstructured.cc index bd4028f593..df719ba6f1 100644 --- a/applications/taylorcouette_unstructured/taylorcouette_unstructured.cc +++ b/applications/taylorcouette_unstructured/taylorcouette_unstructured.cc @@ -1,40 +1,50 @@ -#include "glsNS.h" #include -template class ExactSolutionTaylorCouette : public Function { +#include "glsNS.h" + +template +class ExactSolutionTaylorCouette : public Function +{ public: - ExactSolutionTaylorCouette() : Function(3) { + ExactSolutionTaylorCouette() + : Function(3) + { eta_ = 0.25; - ri_ = 0.25; + ri_ = 0.25; } - virtual void vector_value(const Point &p, Vector &values) const; + virtual void + vector_value(const Point &p, Vector &values) const; private: double eta_; double ri_ = 0.25; }; template -void ExactSolutionTaylorCouette::vector_value( - const Point &p, Vector &values) const { - double x = p[0]; - double y = p[1]; - double r = std::sqrt(x * x + y * y); - double theta = std::atan2(y, x); - double A = -(eta_ * eta_) / (1. - eta_ * eta_); - double B = ri_ * ri_ / (1. - eta_ * eta_); +void +ExactSolutionTaylorCouette::vector_value(const Point &p, + Vector & values) const +{ + double x = p[0]; + double y = p[1]; + double r = std::sqrt(x * x + y * y); + double theta = std::atan2(y, x); + double A = -(eta_ * eta_) / (1. - eta_ * eta_); + double B = ri_ * ri_ / (1. - eta_ * eta_); double utheta = A * r + B / r; - values(0) = -std::sin(theta) * utheta; - values(1) = std::cos(theta) * utheta; - values(2) = 0.; + values(0) = -std::sin(theta) * utheta; + values(1) = std::cos(theta) * utheta; + values(2) = 0.; } template -class TaylorCouetteNavierStokes : public GLSNavierStokesSolver { +class TaylorCouetteNavierStokes : public GLSNavierStokesSolver +{ public: TaylorCouetteNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure); - void run(); + const unsigned int degreeVelocity, + const unsigned int degreePressure); + void + run(); private: std::vector wallTime_; @@ -42,11 +52,16 @@ class TaylorCouetteNavierStokes : public GLSNavierStokesSolver { template TaylorCouetteNavierStokes::TaylorCouetteNavierStokes( - NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} + NavierStokesSolverParameters nsparam, + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) +{} -template void TaylorCouetteNavierStokes::run() { +template +void +TaylorCouetteNavierStokes::run() +{ Point circleCenter; if (dim == 2) @@ -62,74 +77,88 @@ template void TaylorCouetteNavierStokes::run() { this->setup_dofs(); this->forcing_function = new NoForce; - this->exact_solution = new ExactSolutionTaylorCouette; + this->exact_solution = new ExactSolutionTaylorCouette; ConvergenceTable table; this->iterate(this->simulationControl.firstIter()); - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - if (this->simulationControl.firstIter()) { - this->iterate(this->simulationControl.firstIter()); - } else { - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); + while (this->simulationControl.integrate()) + { + printTime(this->pcout, this->simulationControl); + if (this->simulationControl.firstIter()) + { + this->iterate(this->simulationControl.firstIter()); + } + else + { + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + } + this->postprocess(); + table.add_value("cells", this->triangulation.n_global_active_cells()); + + const double error = this->calculate_L2_error(); + table.add_value("error", error); + + this->finish_time_step(); } - this->postprocess(); - table.add_value("cells", this->triangulation.n_global_active_cells()); - - const double error = this->calculate_L2_error(); - table.add_value("error", error); - - this->finish_time_step(); - } table.omit_column_from_convergence_rate_evaluation("cells"); table.evaluate_all_convergence_rates(ConvergenceTable::reduction_rate_log2); table.set_scientific("error", true); - if (this->this_mpi_process == 0) { - table.write_text(std::cout); - } + if (this->this_mpi_process == 0) + { + table.write_text(std::cout); + } } -int main(int argc, char *argv[]) { - try { - if (argc != 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc != 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - prm.parse_input(argv[1]); - NSparam.parse(prm); - - TaylorCouetteNavierStokes<2> problem_2d( - NSparam, NSparam.femParameters.velocityOrder, + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + prm.parse_input(argv[1]); + NSparam.parse(prm); + + TaylorCouetteNavierStokes<2> problem_2d( + NSparam, + NSparam.femParameters.velocityOrder, NSparam.femParameters.pressureOrder); - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/tg_vortex/tg_vortex.cc b/applications/tg_vortex/tg_vortex.cc index b3109e9666..4db28df6ae 100644 --- a/applications/tg_vortex/tg_vortex.cc +++ b/applications/tg_vortex/tg_vortex.cc @@ -1,11 +1,17 @@ #include "glsNS.h" #include "parameters.h" -template class ExactSolutionTGV : public Function { +template +class ExactSolutionTGV : public Function +{ public: ExactSolutionTGV(double p_viscosity, double p_time) - : Function(dim + 1), viscosity(p_viscosity), time(p_time) {} - virtual void vector_value(const Point &p, Vector &values) const; + : Function(dim + 1) + , viscosity(p_viscosity) + , time(p_time) + {} + virtual void + vector_value(const Point &p, Vector &values) const; private: double viscosity; @@ -13,26 +19,35 @@ template class ExactSolutionTGV : public Function { }; template -void ExactSolutionTGV::vector_value(const Point &p, - Vector &values) const { +void +ExactSolutionTGV::vector_value(const Point &p, + Vector & values) const +{ assert(dim == 2); - double x = p[0]; - double y = p[1]; + double x = p[0]; + double y = p[1]; double factor = std::exp(-2. * viscosity * time); - values(0) = cos(x) * sin(y) * factor; - values(1) = -sin(x) * cos(y) * factor; + values(0) = cos(x) * sin(y) * factor; + values(1) = -sin(x) * cos(y) * factor; } -template class TaylorGreenVortex : public GLSNavierStokesSolver { +template +class TaylorGreenVortex : public GLSNavierStokesSolver +{ public: TaylorGreenVortex(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void run2DTGV(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + run2DTGV(); }; -template void TaylorGreenVortex::run2DTGV() { +template +void +TaylorGreenVortex::run2DTGV() +{ std::vector ke_values; std::vector timeTaken; std::vector enstrophy_values; @@ -40,107 +55,120 @@ template void TaylorGreenVortex::run2DTGV() { this->setup_dofs(); this->forcing_function = new NoForce; this->exact_solution = - new ExactSolutionTGV(this->nsparam.physicalProperties.viscosity, 0.); + new ExactSolutionTGV(this->nsparam.physicalProperties.viscosity, 0.); this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); Timer timer; - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - timer.start(); - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - + while (this->simulationControl.integrate()) { - delete this->exact_solution; - this->exact_solution = + printTime(this->pcout, this->simulationControl); + timer.start(); + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + + { + delete this->exact_solution; + this->exact_solution = new ExactSolutionTGV(this->nsparam.physicalProperties.viscosity, this->simulationControl.getTime()); - double error = this->calculate_L2_error() / - std::exp(-2 * this->nsparam.physicalProperties.viscosity * - this->simulationControl.getTime()); - this->pcout << "L2 error : " - << std::setprecision( + double error = + this->calculate_L2_error() / + std::exp(-2 * this->nsparam.physicalProperties.viscosity * + this->simulationControl.getTime()); + this->pcout << "L2 error : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << error << std::endl; - double kE = this->calculate_average_KE(); - this->pcout << "Kinetic energy : " - << std::setprecision( + << error << std::endl; + double kE = this->calculate_average_KE(); + this->pcout << "Kinetic energy : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << kE << std::endl; - ke_values.push_back(kE); - timeTaken.push_back((this->simulationControl.getTime())); - double enstrophy = this->calculate_average_enstrophy(); - this->pcout << "Enstrophy : " - << std::setprecision( + << kE << std::endl; + ke_values.push_back(kE); + timeTaken.push_back((this->simulationControl.getTime())); + double enstrophy = this->calculate_average_enstrophy(); + this->pcout << "Enstrophy : " + << std::setprecision( this->nsparam.analyticalSolution.errorPrecision) - << enstrophy << std::endl; - enstrophy_values.push_back(enstrophy); - } - - this->finish_time_step(); - } - if (this->this_mpi_process == 0) { - assert(timeTaken.size() == ke_values.size()); - std::ofstream output_file("./KE-2D.dat"); - for (unsigned int i = 0; i < ke_values.size(); ++i) { + << enstrophy << std::endl; + enstrophy_values.push_back(enstrophy); + } - output_file << timeTaken[i] << " " << ke_values[i] << std::endl; + this->finish_time_step(); } - output_file.close(); - } - if (this->this_mpi_process == 0) { - assert(timeTaken.size() == enstrophy_values.size()); - std::ofstream output_file("./Enstrophy-2D.dat"); - for (unsigned int i = 0; i < enstrophy_values.size(); ++i) { - - output_file << timeTaken[i] << " " << enstrophy_values[i] << std::endl; + if (this->this_mpi_process == 0) + { + assert(timeTaken.size() == ke_values.size()); + std::ofstream output_file("./KE-2D.dat"); + for (unsigned int i = 0; i < ke_values.size(); ++i) + { + output_file << timeTaken[i] << " " << ke_values[i] << std::endl; + } + output_file.close(); + } + if (this->this_mpi_process == 0) + { + assert(timeTaken.size() == enstrophy_values.size()); + std::ofstream output_file("./Enstrophy-2D.dat"); + for (unsigned int i = 0; i < enstrophy_values.size(); ++i) + { + output_file << timeTaken[i] << " " << enstrophy_values[i] + << std::endl; + } + output_file.close(); } - output_file.close(); - } } -int main(int argc, char *argv[]) { - try { - if (argc < 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc < 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - prm.parse_input(argv[1]); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + prm.parse_input(argv[1]); + NSparam.parse(prm); - TaylorGreenVortex<2> problem_2d(NSparam, - NSparam.femParameters.velocityOrder, - NSparam.femParameters.pressureOrder); - problem_2d.run2DTGV(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + TaylorGreenVortex<2> problem_2d(NSparam, + NSparam.femParameters.velocityOrder, + NSparam.femParameters.pressureOrder); + problem_2d.run2DTGV(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/applications/tg_vortex_3d/tg_vortex_3d.cc b/applications/tg_vortex_3d/tg_vortex_3d.cc index 2df2431cb7..cbd3800830 100644 --- a/applications/tg_vortex_3d/tg_vortex_3d.cc +++ b/applications/tg_vortex_3d/tg_vortex_3d.cc @@ -1,22 +1,27 @@ #include "glsNS.h" #include "parameters.h" -template class TaylorGreenVortex : public GLSNavierStokesSolver { +template +class TaylorGreenVortex : public GLSNavierStokesSolver +{ public: TaylorGreenVortex(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) { - if (this->nsparam.restartParameters.restart && - this->this_mpi_process == 0) { - read_ke(); - read_enstrophy(); - if (enstrophy_values.size() != ke_values.size()) { - throw std::runtime_error("Unalligned KE and enstrophy files"); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + { + if (this->nsparam.restartParameters.restart && this->this_mpi_process == 0) + { + read_ke(); + read_enstrophy(); + if (enstrophy_values.size() != ke_values.size()) + { + throw std::runtime_error("Unalligned KE and enstrophy files"); + } } - } } - void run3DTGV(); + void + run3DTGV(); private: std::vector time; @@ -24,51 +29,66 @@ template class TaylorGreenVortex : public GLSNavierStokesSolver { std::vector enstrophy_values; // Read previously stored values of enstrophy and Ke - void read_enstrophy(); - void read_ke(); + void + read_enstrophy(); + void + read_ke(); }; -template void TaylorGreenVortex::read_ke() { +template +void +TaylorGreenVortex::read_ke() +{ std::ifstream input("./KE.dat"); - if (!input) { - throw("Unable to open file"); - } + if (!input) + { + throw("Unable to open file"); + } std::string buffer; std::getline(input, buffer); std::string lineData; - while (getline(input, lineData)) { - double t, ke; - std::vector row; - std::stringstream lineStream(lineData); - lineStream >> t; - lineStream >> ke; - time.push_back(t); - ke_values.push_back(ke); - } + while (getline(input, lineData)) + { + double t, ke; + std::vector row; + std::stringstream lineStream(lineData); + lineStream >> t; + lineStream >> ke; + time.push_back(t); + ke_values.push_back(ke); + } } -template void TaylorGreenVortex::read_enstrophy() { +template +void +TaylorGreenVortex::read_enstrophy() +{ std::ifstream input("./enstrophy.dat"); - if (!input) { - throw("Unable to open file"); - } + if (!input) + { + throw("Unable to open file"); + } std::string buffer; std::getline(input, buffer); std::string lineData; - while (getline(input, lineData)) { - double t, ke; - std::vector row; - std::stringstream lineStream(lineData); - lineStream >> t; - lineStream >> ke; - enstrophy_values.push_back(ke); - } + while (getline(input, lineData)) + { + double t, ke; + std::vector row; + std::stringstream lineStream(lineData); + lineStream >> t; + lineStream >> ke; + enstrophy_values.push_back(ke); + } } // 3D TGV case -template void TaylorGreenVortex::run3DTGV() { +template +void +TaylorGreenVortex::run3DTGV() +{ const int initialSize = this->nsparam.mesh.initialRefinement; GridGenerator::hyper_cube(this->triangulation, 0, 2. * M_PI, true); this->set_periodicity(); @@ -78,95 +98,106 @@ template void TaylorGreenVortex::run3DTGV() { this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - double kE = this->calculate_average_KE(); + double kE = this->calculate_average_KE(); double enstrophy = this->calculate_average_enstrophy(); - if (this->this_mpi_process == 0 && !this->nsparam.restartParameters.restart) { - time.push_back(0.); - ke_values.push_back(kE); - enstrophy_values.push_back(enstrophy); - } + if (this->this_mpi_process == 0 && !this->nsparam.restartParameters.restart) + { + time.push_back(0.); + ke_values.push_back(kE); + enstrophy_values.push_back(enstrophy); + } Timer timer; - while (this->simulationControl.integrate()) { - printTime(this->pcout, this->simulationControl); - timer.start(); - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - - // Post-processing for Kinetic enegery and Enstrophy + while (this->simulationControl.integrate()) { - double kE = this->calculate_average_KE(); - double enstrophy = this->calculate_average_enstrophy(); - if (this->this_mpi_process == 0) { - time.push_back((this->simulationControl.getTime())); - ke_values.push_back(kE); - enstrophy_values.push_back(enstrophy); + printTime(this->pcout, this->simulationControl); + timer.start(); + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); - this->pcout << "Kinetic energy : " << kE << std::endl; - { - std::ofstream output_file("./KE.dat"); - output_file << "Time Kinetic_Energy" << std::endl; - for (unsigned int i = 0; i < ke_values.size(); ++i) - output_file << std::setprecision(12) << time[i] << " " - << std::setprecision(12) << ke_values[i] << std::endl; - output_file.close(); - } + // Post-processing for Kinetic enegery and Enstrophy + { + double kE = this->calculate_average_KE(); + double enstrophy = this->calculate_average_enstrophy(); + if (this->this_mpi_process == 0) + { + time.push_back((this->simulationControl.getTime())); + ke_values.push_back(kE); + enstrophy_values.push_back(enstrophy); - this->pcout << "Enstrophy : " << enstrophy << std::endl; - { - std::ofstream output_file("./enstrophy.dat"); - output_file << "Time Enstrophy" << std::endl; - for (unsigned int i = 0; i < enstrophy_values.size(); ++i) - output_file << std::setprecision(12) << time[i] << " " - << std::setprecision(12) << enstrophy_values[i] - << std::endl; - output_file.close(); - } + this->pcout << "Kinetic energy : " << kE << std::endl; + { + std::ofstream output_file("./KE.dat"); + output_file << "Time Kinetic_Energy" << std::endl; + for (unsigned int i = 0; i < ke_values.size(); ++i) + output_file << std::setprecision(12) << time[i] << " " + << std::setprecision(12) << ke_values[i] + << std::endl; + output_file.close(); + } + + this->pcout << "Enstrophy : " << enstrophy << std::endl; + { + std::ofstream output_file("./enstrophy.dat"); + output_file << "Time Enstrophy" << std::endl; + for (unsigned int i = 0; i < enstrophy_values.size(); ++i) + output_file << std::setprecision(12) << time[i] << " " + << std::setprecision(12) << enstrophy_values[i] + << std::endl; + output_file.close(); + } + } } + this->finish_time_step(); } - this->finish_time_step(); - } } -int main(int argc, char *argv[]) { - try { - if (argc < 2) { - std::cout << "Usage:" << argv[0] << " input_file" << std::endl; - std::exit(1); - } - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + if (argc < 2) + { + std::cout << "Usage:" << argv[0] << " input_file" << std::endl; + std::exit(1); + } + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<3> NSparam; - NSparam.declare(prm); - prm.parse_input(argv[1]); - NSparam.parse(prm); - TaylorGreenVortex<3> problem_3d(NSparam, - NSparam.femParameters.velocityOrder, - NSparam.femParameters.pressureOrder); - problem_3d.run3DTGV(); - - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + ParameterHandler prm; + NavierStokesSolverParameters<3> NSparam; + NSparam.declare(prm); + prm.parse_input(argv[1]); + NSparam.parse(prm); + TaylorGreenVortex<3> problem_3d(NSparam, + NSparam.femParameters.velocityOrder, + NSparam.femParameters.pressureOrder); + problem_3d.run3DTGV(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/contrib/.clang-format b/contrib/.clang-format new file mode 100644 index 0000000000..184bb9fa58 --- /dev/null +++ b/contrib/.clang-format @@ -0,0 +1,6 @@ +# +# The clang-format (Clang 6) style file used by deal.II. +# This directory shall not be formatted. +# + +DisableFormat: true diff --git a/parameters/.clang-format b/parameters/.clang-format new file mode 100644 index 0000000000..184bb9fa58 --- /dev/null +++ b/parameters/.clang-format @@ -0,0 +1,6 @@ +# +# The clang-format (Clang 6) style file used by deal.II. +# This directory shall not be formatted. +# + +DisableFormat: true diff --git a/src/bdf.cc b/src/bdf.cc index 2ab6d6cb0c..8e58b6ab79 100644 --- a/src/bdf.cc +++ b/src/bdf.cc @@ -1,47 +1,55 @@ #include "bdf.h" -Vector delta(unsigned int p, unsigned int n, unsigned int j, - Vector times) { - if (j == 0) { - Vector arr(p + 1); - arr = 0.; - arr[n] = 1; - return arr; - } else { - Vector delta_1 = delta(p, n, j - 1, times); - Vector delta_2 = delta(p, n + 1, j - 1, times); - Vector delta_sol(p + 1); - for (unsigned int i_del = 0; i_del < p + 1; ++i_del) - delta_sol[i_del] = +Vector +delta(unsigned int p, unsigned int n, unsigned int j, Vector times) +{ + if (j == 0) + { + Vector arr(p + 1); + arr = 0.; + arr[n] = 1; + return arr; + } + else + { + Vector delta_1 = delta(p, n, j - 1, times); + Vector delta_2 = delta(p, n + 1, j - 1, times); + Vector delta_sol(p + 1); + for (unsigned int i_del = 0; i_del < p + 1; ++i_del) + delta_sol[i_del] = (delta_1[i_del] - delta_2[i_del]) / (times[n] - times[n + j]); - return delta_sol; - } + return delta_sol; + } } -Vector bdf_coefficients(unsigned int p, std::vector dt) { +Vector +bdf_coefficients(unsigned int p, std::vector dt) +{ // There should be at least p+1 time steps assert(dt.size() >= p + 1); // Create a time table for the bdf formula Vector times(p + 1); - for (unsigned int i = 0; i < p + 1; ++i) { - times[i] = 0.; - for (unsigned int j = 0; j < i; ++j) - times[i] -= dt[j]; - } + for (unsigned int i = 0; i < p + 1; ++i) + { + times[i] = 0.; + for (unsigned int j = 0; j < i; ++j) + times[i] -= dt[j]; + } // The alphas are the bdf coefficients Vector alpha(p + 1); alpha = 0; - for (unsigned int j = 1; j < p + 1; ++j) { - double factor = 1.; - for (unsigned int i = 1; i < j; ++i) - factor *= times[0] - times[i]; + for (unsigned int j = 1; j < p + 1; ++j) + { + double factor = 1.; + for (unsigned int i = 1; i < j; ++i) + factor *= times[0] - times[i]; - Vector term(p + 1); - term.equ(factor, delta(p, 0, j, times)); - alpha += term; - } + Vector term(p + 1); + term.equ(factor, delta(p, 0, j, times)); + alpha += term; + } return alpha; } diff --git a/src/bdf.h b/src/bdf.h index 3f3bfa2622..456da03a1d 100644 --- a/src/bdf.h +++ b/src/bdf.h @@ -21,6 +21,7 @@ #define LETHE_BDF_H #include + #include using namespace dealii; @@ -31,8 +32,9 @@ using namespace dealii; * The formulas are derived analytically, but the coefficients * Could also be determined through recursion on the fly. */ -Vector bdf_coefficients(unsigned int order, std::vector dt); -Vector delta(unsigned int order, unsigned int n, unsigned int j, - Vector times); +Vector +bdf_coefficients(unsigned int order, std::vector dt); +Vector +delta(unsigned int order, unsigned int n, unsigned int j, Vector times); #endif diff --git a/src/boundaryconditions.cc b/src/boundaryconditions.cc index 1a42868aa2..e4b1064fca 100644 --- a/src/boundaryconditions.cc +++ b/src/boundaryconditions.cc @@ -19,9 +19,10 @@ #include "boundaryconditions.h" -namespace BoundaryConditions { -extern template class NSBoundaryConditions<2>; -extern template class NSBoundaryConditions<3>; +namespace BoundaryConditions +{ + extern template class NSBoundaryConditions<2>; + extern template class NSBoundaryConditions<3>; } // namespace BoundaryConditions // extern template class PeriodicBoundaryValues<2>; diff --git a/src/boundaryconditions.h b/src/boundaryconditions.h index e8540e646c..956e4a48dc 100644 --- a/src/boundaryconditions.h +++ b/src/boundaryconditions.h @@ -25,204 +25,266 @@ using namespace dealii; -namespace BoundaryConditions { -enum BoundaryType { noslip, slip, function, periodic }; - -template class BoundaryFunction { -public: - // Velocity components - Functions::ParsedFunction u; - Functions::ParsedFunction v; - Functions::ParsedFunction w; - - // Point for the center of rotation - Point cor; -}; - -template class NSBoundaryConditions { -public: - // ID of boundary condition - std::vector id; - - // List of boundary type for each number - std::vector type; - - // Functions for (u,v,w) for all boundaries - BoundaryFunction *bcFunctions; - - // Number of boundary conditions - unsigned int size; - unsigned int max_size; +namespace BoundaryConditions +{ + enum BoundaryType + { + noslip, + slip, + function, + periodic + }; - // Periodic boundary condition matching - std::vector periodic_id; - std::vector periodic_direction; + template + class BoundaryFunction + { + public: + // Velocity components + Functions::ParsedFunction u; + Functions::ParsedFunction v; + Functions::ParsedFunction w; + + // Point for the center of rotation + Point cor; + }; - void parse_boundary(ParameterHandler &prm, unsigned int i_bc); - void declareDefaultEntry(ParameterHandler &prm, unsigned int i_bc); - void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); - void createDefaultNoSlip(); -}; + template + class NSBoundaryConditions + { + public: + // ID of boundary condition + std::vector id; + + // List of boundary type for each number + std::vector type; + + // Functions for (u,v,w) for all boundaries + BoundaryFunction *bcFunctions; + + // Number of boundary conditions + unsigned int size; + unsigned int max_size; + + // Periodic boundary condition matching + std::vector periodic_id; + std::vector periodic_direction; + + void + parse_boundary(ParameterHandler &prm, unsigned int i_bc); + void + declareDefaultEntry(ParameterHandler &prm, unsigned int i_bc); + void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + void + createDefaultNoSlip(); + }; -template void NSBoundaryConditions::createDefaultNoSlip() { - id.resize(1); - id[0] = 0; - type.resize(1); - type[0] = noslip; - size = 1; -} + template + void + NSBoundaryConditions::createDefaultNoSlip() + { + id.resize(1); + id[0] = 0; + type.resize(1); + type[0] = noslip; + size = 1; + } -template -void NSBoundaryConditions::declareDefaultEntry(ParameterHandler &prm, - unsigned int i_bc) { - prm.declare_entry("type", "noslip", - Patterns::Selection("noslip|slip|function|periodic"), - "Type of boundary conditoin" - "Choices are ."); - - prm.declare_entry("id", Utilities::int_to_string(i_bc, 2), - Patterns::Integer(), "Mesh id for boundary conditions"); - - prm.declare_entry("periodic_id", "0", Patterns::Integer(), - "Mesh id for periodic face matching"); - - prm.declare_entry("periodic_direction", "0", Patterns::Integer(), - "Direction for periodic boundary condition"); - - prm.enter_subsection("u"); - bcFunctions[i_bc].u.declare_parameters(prm, 1); - prm.set("Function expression", "0"); - prm.leave_subsection(); - - prm.enter_subsection("v"); - bcFunctions[i_bc].v.declare_parameters(prm, 1); - prm.set("Function expression", "0"); - prm.leave_subsection(); - - prm.enter_subsection("w"); - bcFunctions[i_bc].w.declare_parameters(prm, 1); - prm.set("Function expression", "0"); - prm.leave_subsection(); - - prm.enter_subsection("cor"); - prm.declare_entry("x", "0", Patterns::Double(), "X COR"); - prm.declare_entry("y", "0", Patterns::Double(), "Y COR"); - prm.declare_entry("z", "0", Patterns::Double(), "Z COR"); - prm.leave_subsection(); -} + template + void + NSBoundaryConditions::declareDefaultEntry(ParameterHandler &prm, + unsigned int i_bc) + { + prm.declare_entry("type", + "noslip", + Patterns::Selection("noslip|slip|function|periodic"), + "Type of boundary conditoin" + "Choices are ."); + + prm.declare_entry("id", + Utilities::int_to_string(i_bc, 2), + Patterns::Integer(), + "Mesh id for boundary conditions"); + + prm.declare_entry("periodic_id", + "0", + Patterns::Integer(), + "Mesh id for periodic face matching"); + + prm.declare_entry("periodic_direction", + "0", + Patterns::Integer(), + "Direction for periodic boundary condition"); -template -void NSBoundaryConditions::parse_boundary(ParameterHandler &prm, - unsigned int i_bc) { - const std::string op = prm.get("type"); - if (op == "noslip") - type[i_bc] = noslip; - if (op == "slip") - type[i_bc] = slip; - if (op == "function") { - type[i_bc] = function; prm.enter_subsection("u"); - bcFunctions[i_bc].u.parse_parameters(prm); + bcFunctions[i_bc].u.declare_parameters(prm, 1); + prm.set("Function expression", "0"); prm.leave_subsection(); prm.enter_subsection("v"); - bcFunctions[i_bc].v.parse_parameters(prm); + bcFunctions[i_bc].v.declare_parameters(prm, 1); + prm.set("Function expression", "0"); prm.leave_subsection(); prm.enter_subsection("w"); - bcFunctions[i_bc].w.parse_parameters(prm); + bcFunctions[i_bc].w.declare_parameters(prm, 1); + prm.set("Function expression", "0"); prm.leave_subsection(); prm.enter_subsection("cor"); - bcFunctions[i_bc].cor[0] = prm.get_double("x"); - bcFunctions[i_bc].cor[1] = prm.get_double("y"); - if (dim == 3) - bcFunctions[i_bc].cor[2] = prm.get_double("z"); + prm.declare_entry("x", "0", Patterns::Double(), "X COR"); + prm.declare_entry("y", "0", Patterns::Double(), "Y COR"); + prm.declare_entry("z", "0", Patterns::Double(), "Z COR"); prm.leave_subsection(); } - if (op == "periodic") { - type[i_bc] = periodic; - periodic_id[i_bc] = prm.get_integer("periodic_id"); - periodic_direction[i_bc] = prm.get_integer("periodic_direction"); - } - - id[i_bc] = prm.get_integer("id"); -} - -template -void NSBoundaryConditions::declare_parameters(ParameterHandler &prm) { - max_size = 4; - prm.enter_subsection("boundary conditions"); + template + void + NSBoundaryConditions::parse_boundary(ParameterHandler &prm, + unsigned int i_bc) { - prm.declare_entry("number", "0", Patterns::Integer(), - "Number of boundary conditions"); - id.resize(max_size); - periodic_id.resize(max_size); - periodic_direction.resize(max_size); - type.resize(max_size); - bcFunctions = new BoundaryFunction[max_size]; - - prm.enter_subsection("bc 0"); - { declareDefaultEntry(prm, 0); } - prm.leave_subsection(); - - prm.enter_subsection("bc 1"); - { declareDefaultEntry(prm, 1); } - prm.leave_subsection(); - - prm.enter_subsection("bc 2"); - { declareDefaultEntry(prm, 2); } - prm.leave_subsection(); - - prm.enter_subsection("bc 3"); - { declareDefaultEntry(prm, 3); } - prm.leave_subsection(); - - prm.enter_subsection("bc 3"); - { declareDefaultEntry(prm, 3); } - prm.leave_subsection(); + const std::string op = prm.get("type"); + if (op == "noslip") + type[i_bc] = noslip; + if (op == "slip") + type[i_bc] = slip; + if (op == "function") + { + type[i_bc] = function; + prm.enter_subsection("u"); + bcFunctions[i_bc].u.parse_parameters(prm); + prm.leave_subsection(); + + prm.enter_subsection("v"); + bcFunctions[i_bc].v.parse_parameters(prm); + prm.leave_subsection(); + + prm.enter_subsection("w"); + bcFunctions[i_bc].w.parse_parameters(prm); + prm.leave_subsection(); + + prm.enter_subsection("cor"); + bcFunctions[i_bc].cor[0] = prm.get_double("x"); + bcFunctions[i_bc].cor[1] = prm.get_double("y"); + if (dim == 3) + bcFunctions[i_bc].cor[2] = prm.get_double("z"); + prm.leave_subsection(); + } + if (op == "periodic") + { + type[i_bc] = periodic; + periodic_id[i_bc] = prm.get_integer("periodic_id"); + periodic_direction[i_bc] = prm.get_integer("periodic_direction"); + } + + id[i_bc] = prm.get_integer("id"); } - prm.leave_subsection(); -} -template -void NSBoundaryConditions::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("boundary conditions"); + template + void + NSBoundaryConditions::declare_parameters(ParameterHandler &prm) { - size = prm.get_integer("number"); - type.resize(size); - id.resize(size); - periodic_direction.resize(size); - periodic_id.resize(size); + max_size = 4; + + prm.enter_subsection("boundary conditions"); + { + prm.declare_entry("number", + "0", + Patterns::Integer(), + "Number of boundary conditions"); + id.resize(max_size); + periodic_id.resize(max_size); + periodic_direction.resize(max_size); + type.resize(max_size); + bcFunctions = new BoundaryFunction[max_size]; - if (size >= 1) { prm.enter_subsection("bc 0"); - { parse_boundary(prm, 0); } + { + declareDefaultEntry(prm, 0); + } prm.leave_subsection(); - } - if (size >= 2) { + prm.enter_subsection("bc 1"); - { parse_boundary(prm, 1); } + { + declareDefaultEntry(prm, 1); + } prm.leave_subsection(); - } - if (size >= 3) { + prm.enter_subsection("bc 2"); - { parse_boundary(prm, 2); } + { + declareDefaultEntry(prm, 2); + } prm.leave_subsection(); - } - if (size >= 4) { + prm.enter_subsection("bc 3"); - { parse_boundary(prm, 3); } + { + declareDefaultEntry(prm, 3); + } + prm.leave_subsection(); + + prm.enter_subsection("bc 3"); + { + declareDefaultEntry(prm, 3); + } prm.leave_subsection(); } + prm.leave_subsection(); + } + + template + void + NSBoundaryConditions::parse_parameters(ParameterHandler &prm) + { + prm.enter_subsection("boundary conditions"); + { + size = prm.get_integer("number"); + type.resize(size); + id.resize(size); + periodic_direction.resize(size); + periodic_id.resize(size); + + if (size >= 1) + { + prm.enter_subsection("bc 0"); + { + parse_boundary(prm, 0); + } + prm.leave_subsection(); + } + if (size >= 2) + { + prm.enter_subsection("bc 1"); + { + parse_boundary(prm, 1); + } + prm.leave_subsection(); + } + if (size >= 3) + { + prm.enter_subsection("bc 2"); + { + parse_boundary(prm, 2); + } + prm.leave_subsection(); + } + if (size >= 4) + { + prm.enter_subsection("bc 3"); + { + parse_boundary(prm, 3); + } + prm.leave_subsection(); + } + } + prm.leave_subsection(); } - prm.leave_subsection(); -} } // namespace BoundaryConditions -template class FunctionDefined : public Function { +template +class FunctionDefined : public Function +{ private: Functions::ParsedFunction *u; Functions::ParsedFunction *v; @@ -232,36 +294,53 @@ template class FunctionDefined : public Function { FunctionDefined(Functions::ParsedFunction *p_u, Functions::ParsedFunction *p_v, Functions::ParsedFunction *p_w) - : Function(dim + 1), u(p_u), v(p_v), w(p_w) {} - - virtual double value(const Point &p, const unsigned int component) const; + : Function(dim + 1) + , u(p_u) + , v(p_v) + , w(p_w) + {} + + virtual double + value(const Point &p, const unsigned int component) const; }; template -double FunctionDefined::value(const Point &p, - const unsigned int component) const { +double +FunctionDefined::value(const Point & p, + const unsigned int component) const +{ Assert(component < this->n_components, ExcIndexRange(component, 0, this->n_components)); - if (component == 0) { - return u->value(p); - } else if (component == 1) { - return v->value(p); - } else if (component == 2) { - return w->value(p); - } + if (component == 0) + { + return u->value(p); + } + else if (component == 1) + { + return v->value(p); + } + else if (component == 2) + { + return w->value(p); + } return 0.; } -template class PoiseuilleInlet : public Function { +template +class PoiseuilleInlet : public Function +{ public: - PoiseuilleInlet() : Function(dim + 1) { - y2_ = 1.; - y1_ = 0.; - dy_ = 0.5 * (y2_ + y1_); + PoiseuilleInlet() + : Function(dim + 1) + { + y2_ = 1.; + y1_ = 0.; + dy_ = 0.5 * (y2_ + y1_); vmax_ = 1. / dy_ / dy_; }; - virtual double value(const Point &p, const unsigned int component) const; + virtual double + value(const Point &p, const unsigned int component) const; private: double y2_; @@ -271,62 +350,88 @@ template class PoiseuilleInlet : public Function { }; template -double PoiseuilleInlet::value(const Point &p, - const unsigned int component) const { +double +PoiseuilleInlet::value(const Point & p, + const unsigned int component) const +{ Assert(component < this->n_components, ExcIndexRange(component, 0, this->n_components)); double y = p[1]; - if (component == 0) { - return vmax_ * (y - y1_) * (y2_ - y); - } else if (component == 1) + if (component == 0) + { + return vmax_ * (y - y1_) * (y2_ - y); + } + else if (component == 1) return 0.; return 0.; } -template class ConstantXInlet : public Function { +template +class ConstantXInlet : public Function +{ public: - ConstantXInlet() : Function(dim + 1) { value_ = 1.; }; + ConstantXInlet() + : Function(dim + 1) + { + value_ = 1.; + }; - virtual double value(const Point &p, const unsigned int component) const; + virtual double + value(const Point &p, const unsigned int component) const; private: double value_; }; template -double ConstantXInlet::value(const Point & /*p*/, - const unsigned int component) const { +double +ConstantXInlet::value(const Point & /*p*/, + const unsigned int component) const +{ Assert(component < this->n_components, ExcIndexRange(component, 0, this->n_components)); - if (component == 0) { - return value_; - } else if (component == 1) + if (component == 0) + { + return value_; + } + else if (component == 1) return 0.; return 0.; } -template class ConstantXSlip : public Function { +template +class ConstantXSlip : public Function +{ public: - ConstantXSlip() : Function(dim + 1) { value_ = 1.; }; + ConstantXSlip() + : Function(dim + 1) + { + value_ = 1.; + }; - virtual double value(const Point &p, const unsigned int component) const; + virtual double + value(const Point &p, const unsigned int component) const; private: double value_; }; template -double ConstantXSlip::value(const Point &p, - const unsigned int component) const { +double +ConstantXSlip::value(const Point & p, + const unsigned int component) const +{ Assert(component < this->n_components, ExcIndexRange(component, 0, this->n_components)); - if (component == 0) { - return value_; - } else if (component == 1) + if (component == 0) + { + return value_; + } + else if (component == 1) return 0.; return 0.; } diff --git a/src/exactsolutions.h b/src/exactsolutions.h index 48912a8f48..44061fdcc2 100644 --- a/src/exactsolutions.h +++ b/src/exactsolutions.h @@ -19,29 +19,37 @@ #include #include + #include using namespace dealii; #ifndef LETHE_EXACTSOLUTIONS_H -#define LETHE_EXACTSOLUTIONS_H +# define LETHE_EXACTSOLUTIONS_H -template class ExactSolutionMMS : public Function { +template +class ExactSolutionMMS : public Function +{ public: - ExactSolutionMMS() : Function(3) {} - virtual void vector_value(const Point &p, Vector &values) const; + ExactSolutionMMS() + : Function(3) + {} + virtual void + vector_value(const Point &p, Vector &values) const; private: double time; }; template -void ExactSolutionMMS::vector_value(const Point &p, - Vector &values) const { +void +ExactSolutionMMS::vector_value(const Point &p, + Vector & values) const +{ assert(dim == 2); const double a = M_PI; - double x = p[0]; - double y = p[1]; - values(0) = sin(a * x) * sin(a * x) * cos(a * y) * sin(a * y); - values(1) = -cos(a * x) * sin(a * x) * sin(a * y) * sin(a * y); + double x = p[0]; + double y = p[1]; + values(0) = sin(a * x) * sin(a * x) * cos(a * y) * sin(a * y); + values(1) = -cos(a * x) * sin(a * x) * sin(a * y) * sin(a * y); } #endif diff --git a/src/forcingfunctions.h b/src/forcingfunctions.h index b468aef00b..84937a7d0e 100644 --- a/src/forcingfunctions.h +++ b/src/forcingfunctions.h @@ -25,41 +25,51 @@ // Finally, this is as in previous programs: using namespace dealii; -template class MMSSineForcingFunction : public Function { +template +class MMSSineForcingFunction : public Function +{ public: - MMSSineForcingFunction() : Function(3){}; - virtual void vector_value(const Point &p, Vector &values) const; + MMSSineForcingFunction() + : Function(3){}; + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void MMSSineForcingFunction::vector_value(const Point &p, - Vector &values) const { +void +MMSSineForcingFunction::vector_value(const Point &p, + Vector & values) const +{ assert(dim == 2); const double a = M_PI; const double x = p[0]; const double y = p[1]; values(0) = - (2 * a * a * (-sin(a * x) * sin(a * x) + cos(a * x) * (cos(a * x))) * - sin(a * y) * cos(a * y) - - 4 * a * a * sin(a * x) * sin(a * x) * sin(a * y) * cos(a * y) - - 2.0 * x) * - (-1.) + - a * std::pow(sin(a * x), 3.) * std::pow(sin(a * y), 2.) * std::cos(a * x); + (2 * a * a * (-sin(a * x) * sin(a * x) + cos(a * x) * (cos(a * x))) * + sin(a * y) * cos(a * y) - + 4 * a * a * sin(a * x) * sin(a * x) * sin(a * y) * cos(a * y) - 2.0 * x) * + (-1.) + + a * std::pow(sin(a * x), 3.) * std::pow(sin(a * y), 2.) * std::cos(a * x); values(1) = - (2 * a * a * (sin(a * y) * (sin(a * y)) - cos(a * y) * cos(a * y)) * - sin(a * x) * cos(a * x) + - 4 * a * a * sin(a * x) * sin(a * y) * sin(a * y) * cos(a * x) - - 2.0 * y) * - (-1) + - a * std::pow(sin(a * x), 2.) * std::pow(sin(a * y), 3.) * std::cos(a * y); + (2 * a * a * (sin(a * y) * (sin(a * y)) - cos(a * y) * cos(a * y)) * + sin(a * x) * cos(a * x) + + 4 * a * a * sin(a * x) * sin(a * y) * sin(a * y) * cos(a * x) - 2.0 * y) * + (-1) + + a * std::pow(sin(a * x), 2.) * std::pow(sin(a * y), 3.) * std::cos(a * y); } -template class MMS3DSineForcingFunction : public Function { +template +class MMS3DSineForcingFunction : public Function +{ public: - MMS3DSineForcingFunction() : Function(3){}; - virtual void vector_value(const Point &p, Vector &values) const; + MMS3DSineForcingFunction() + : Function(3){}; + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void MMS3DSineForcingFunction::vector_value(const Point &p, - Vector &values) const { +void +MMS3DSineForcingFunction::vector_value(const Point &p, + Vector & values) const +{ assert(dim == 3); const double a = M_PI; @@ -90,14 +100,20 @@ void MMS3DSineForcingFunction::vector_value(const Point &p, // values(2) += 2*z; } -template class NoForce : public Function { +template +class NoForce : public Function +{ public: - NoForce() : Function(3){}; - virtual void vector_value(const Point &p, Vector &values) const; + NoForce() + : Function(3){}; + virtual void + vector_value(const Point &p, Vector &values) const; }; template -void NoForce::vector_value(const Point & /*p*/, - Vector &values) const { +void +NoForce::vector_value(const Point & /*p*/, + Vector &values) const +{ values(0) = 0.; values(1) = 0.; if (dim == 3) diff --git a/src/glsNS.h b/src/glsNS.h index ea19701b3e..16b62fa99a 100644 --- a/src/glsNS.h +++ b/src/glsNS.h @@ -110,44 +110,59 @@ using namespace dealii; * @author Bruno Blais, 2019 */ -template class GLSNavierStokesSolver { +template +class GLSNavierStokesSolver +{ public: GLSNavierStokesSolver(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure); + const unsigned int degreeVelocity, + const unsigned int degreePressure); ~GLSNavierStokesSolver(); protected: - void solve(); - void read_mesh(); - void refine_mesh(); - void setup_dofs(); - double calculate_L2_error(); - double calculate_average_KE(); - double calculate_average_enstrophy(); + void + solve(); + void + read_mesh(); + void + refine_mesh(); + void + setup_dofs(); + double + calculate_L2_error(); + double + calculate_average_KE(); + double + calculate_average_enstrophy(); void set_initial_condition(Parameters::InitialConditionType initial_condition_type, - bool restart = false); - void postprocess(); - void finish_time_step(); - void set_solution_vector(double value); - void set_periodicity(); - void iterate(bool firstIteration); + bool restart = false); + void + postprocess(); + void + finish_time_step(); + void + set_solution_vector(double value); + void + set_periodicity(); + void + iterate(bool firstIteration); - void make_cube_grid(int refinementLevel); + void + make_cube_grid(int refinementLevel); Function *exact_solution; Function *forcing_function; - MPI_Comm mpi_communicator; - const unsigned int n_mpi_processes; - const unsigned int this_mpi_process; + MPI_Comm mpi_communicator; + const unsigned int n_mpi_processes; + const unsigned int this_mpi_process; parallel::distributed::Triangulation triangulation; - ConditionalOStream pcout; + ConditionalOStream pcout; // Force analysis std::vector> forces_; - std::vector> torques_; + std::vector> torques_; // Solver parameters NavierStokesSolverParameters nsparam; @@ -157,74 +172,99 @@ template class GLSNavierStokesSolver { SimulationControl simulationControl; private: - template - void assembleGLS(const bool initial_step); + void + assembleGLS(const bool initial_step); - void newton_iteration(const bool is_initial_step); - void assemble_L2_projection(); - void set_nodal_values(); - void refine_mesh_Kelly(); - void refine_mesh_uniform(); + void + newton_iteration(const bool is_initial_step); + void + assemble_L2_projection(); + void + set_nodal_values(); + void + refine_mesh_Kelly(); + void + refine_mesh_uniform(); - void calculate_forces(); - void calculate_torques(); - double calculate_CFL(); + void + calculate_forces(); + void + calculate_torques(); + double + calculate_CFL(); - void assemble_system(const bool initial_step); - void assemble_rhs(const bool initial_step); + void + assemble_system(const bool initial_step); + void + assemble_rhs(const bool initial_step); /** * Interface for the solver for the linear system of equations */ - void solve_system(bool initial_step, double relative_residual, - double minimum_residual); // Interface function + void + solve_system(bool initial_step, + double relative_residual, + double minimum_residual); // Interface function /** * GMRES solver with ILU(N) preconditioning */ - void solve_system_GMRES(bool initial_step, double absolute_residual, - double relative_residual); + void + solve_system_GMRES(bool initial_step, + double absolute_residual, + double relative_residual); /** * BiCGStab solver with ILU(N) preconditioning */ - void solve_system_BiCGStab(bool initial_step, double absolute_residual, - double relative_residual); + void + solve_system_BiCGStab(bool initial_step, + double absolute_residual, + double relative_residual); /** * AMG preconditioner with ILU smoother and coarsener and GMRES final solver */ - void solve_system_AMG(bool initial_step, double absolute_residual, - double relative_residual); + void + solve_system_AMG(bool initial_step, + double absolute_residual, + double relative_residual); /** * Checkpointing writer of the solutions vector of the GLS solver */ - void write_checkpoint(); + void + write_checkpoint(); /** * Checkpointing reader of the solutions vector of the GLS solver */ - void read_checkpoint(); + void + read_checkpoint(); - void write_output_forces(); - void write_output_torques(); + void + write_output_forces(); + void + write_output_torques(); /** * Post-processing as parallel VTU files */ - void write_output_results(const std::string folder, - const std::string solutionName, - const unsigned int cycle, const double time); + void + write_output_results(const std::string folder, + const std::string solutionName, + const unsigned int cycle, + const double time); /** * Members */ DoFHandler dof_handler; - FESystem fe; + FESystem fe; IndexSet locally_owned_dofs; IndexSet locally_relevant_dofs; @@ -232,7 +272,7 @@ template class GLSNavierStokesSolver { AffineConstraints zero_constraints; AffineConstraints nonzero_constraints; - SparsityPattern sparsity_pattern; + SparsityPattern sparsity_pattern; TrilinosWrappers::SparseMatrix system_matrix; TrilinosWrappers::MPI::Vector present_solution; @@ -248,12 +288,12 @@ template class GLSNavierStokesSolver { // Finite element order used const unsigned int degreeVelocity_; const unsigned int degreePressure_; - unsigned int degreeQuadrature_; + unsigned int degreeQuadrature_; - double globalVolume_; - const bool SUPG = true; + double globalVolume_; + const bool SUPG = true; const double GLS_u_scale = 1; - PVDHandler pvdhandler; + PVDHandler pvdhandler; TimerOutput computing_timer; @@ -265,23 +305,28 @@ template class GLSNavierStokesSolver { // Constructor for class GLSNavierStokesSolver template GLSNavierStokesSolver::GLSNavierStokesSolver( - NavierStokesSolverParameters p_nsparam, - const unsigned int degreeVelocity, const unsigned int degreePressure) - : mpi_communicator(MPI_COMM_WORLD), - n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator)), - this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator)), - triangulation(mpi_communicator, - typename Triangulation::MeshSmoothing( - Triangulation::smoothing_on_refinement | - Triangulation::smoothing_on_coarsening)), - pcout(std::cout, - (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)), - nsparam(p_nsparam), dof_handler(triangulation), - fe(FE_Q(degreeVelocity), dim, FE_Q(degreePressure), 1), - degreeVelocity_(degreeVelocity), degreePressure_(degreePressure), - degreeQuadrature_(degreeVelocity + 1), - computing_timer(mpi_communicator, pcout, TimerOutput::summary, - TimerOutput::wall_times) { + NavierStokesSolverParameters p_nsparam, + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : mpi_communicator(MPI_COMM_WORLD) + , n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator)) + , this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator)) + , triangulation(mpi_communicator, + typename Triangulation::MeshSmoothing( + Triangulation::smoothing_on_refinement | + Triangulation::smoothing_on_coarsening)) + , pcout(std::cout, (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) + , nsparam(p_nsparam) + , dof_handler(triangulation) + , fe(FE_Q(degreeVelocity), dim, FE_Q(degreePressure), 1) + , degreeVelocity_(degreeVelocity) + , degreePressure_(degreePressure) + , degreeQuadrature_(degreeVelocity + 1) + , computing_timer(mpi_communicator, + pcout, + TimerOutput::summary, + TimerOutput::wall_times) +{ simulationControl = nsparam.simulationControl; // Overide default value of quadrature point if they are specified @@ -301,65 +346,88 @@ GLSNavierStokesSolver::GLSNavierStokesSolver( << " MPI rank(s)..." << std::endl; } -template GLSNavierStokesSolver::~GLSNavierStokesSolver() { - if (nsparam.forcesParameters.calculate_force) { - write_output_forces(); - } +template +GLSNavierStokesSolver::~GLSNavierStokesSolver() +{ + if (nsparam.forcesParameters.calculate_force) + { + write_output_forces(); + } - if (nsparam.forcesParameters.calculate_torque) { - write_output_torques(); - } + if (nsparam.forcesParameters.calculate_torque) + { + write_output_torques(); + } dof_handler.clear(); } template -void GLSNavierStokesSolver::make_cube_grid(int refinementLevel) { +void +GLSNavierStokesSolver::make_cube_grid(int refinementLevel) +{ GridGenerator::hyper_cube(triangulation, -1, 1); triangulation.refine_global(refinementLevel); } -template void GLSNavierStokesSolver::finish_time_step() { - if (simulationControl.getMethod() != Parameters::SimulationControl::steady) { - solution_m3 = solution_m2; - solution_m2 = solution_m1; - solution_m1 = present_solution; - const double CFL = calculate_CFL(); - simulationControl.setCFL(CFL); - } +template +void +GLSNavierStokesSolver::finish_time_step() +{ + if (simulationControl.getMethod() != Parameters::SimulationControl::steady) + { + solution_m3 = solution_m2; + solution_m2 = solution_m1; + solution_m1 = present_solution; + const double CFL = calculate_CFL(); + simulationControl.setCFL(CFL); + } if (nsparam.restartParameters.checkpoint && - simulationControl.getIter() % nsparam.restartParameters.frequency == 0) { - write_checkpoint(); - } + simulationControl.getIter() % nsparam.restartParameters.frequency == 0) + { + write_checkpoint(); + } - if (this->nsparam.timer.type == Parameters::Timer::iteration) { - this->computing_timer.print_summary(); - this->computing_timer.reset(); - } + if (this->nsparam.timer.type == Parameters::Timer::iteration) + { + this->computing_timer.print_summary(); + this->computing_timer.reset(); + } } template -void GLSNavierStokesSolver::set_solution_vector(double value) { +void +GLSNavierStokesSolver::set_solution_vector(double value) +{ present_solution = value; } -template void GLSNavierStokesSolver::set_periodicity() { +template +void +GLSNavierStokesSolver::set_periodicity() +{ // Setup parallelism for periodic boundary conditions - for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; ++i_bc) { - if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::periodic) { - std::vector::cell_iterator>> - periodicity_vector; - GridTools::collect_periodic_faces( - triangulation, nsparam.boundaryConditions.id[i_bc], - nsparam.boundaryConditions.periodic_id[i_bc], - nsparam.boundaryConditions.periodic_direction[i_bc], - periodicity_vector); - triangulation.add_periodicity(periodicity_vector); + for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; ++i_bc) + { + if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::periodic) + { + std::vector::cell_iterator>> + periodicity_vector; + GridTools::collect_periodic_faces( + triangulation, + nsparam.boundaryConditions.id[i_bc], + nsparam.boundaryConditions.periodic_id[i_bc], + nsparam.boundaryConditions.periodic_direction[i_bc], + periodicity_vector); + triangulation.add_periodicity(periodicity_vector); + } } - } } -template void GLSNavierStokesSolver::setup_dofs() { +template +void +GLSNavierStokesSolver::setup_dofs() +{ TimerOutput::Scope t(computing_timer, "setup_dofs"); system_matrix.clear(); @@ -370,7 +438,7 @@ template void GLSNavierStokesSolver::setup_dofs() { locally_owned_dofs = dof_handler.locally_owned_dofs(); DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); - const MappingQ mapping(degreeVelocity_, + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); FEValuesExtractors::Vector velocities(0); @@ -379,40 +447,53 @@ template void GLSNavierStokesSolver::setup_dofs() { nonzero_constraints.clear(); DoFTools::make_hanging_node_constraints(dof_handler, nonzero_constraints); - for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; - ++i_bc) { - if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::noslip) { - VectorTools::interpolate_boundary_values( - mapping, dof_handler, nsparam.boundaryConditions.id[i_bc], - ZeroFunction(dim + 1), nonzero_constraints, - fe.component_mask(velocities)); - } else if (nsparam.boundaryConditions.type[i_bc] == - BoundaryConditions::slip) { - std::set no_normal_flux_boundaries; - no_normal_flux_boundaries.insert(nsparam.boundaryConditions.id[i_bc]); - VectorTools::compute_no_normal_flux_constraints( - dof_handler, 0, no_normal_flux_boundaries, nonzero_constraints); - } else if (nsparam.boundaryConditions.type[i_bc] == - BoundaryConditions::function) { - VectorTools::interpolate_boundary_values( - mapping, dof_handler, nsparam.boundaryConditions.id[i_bc], - FunctionDefined( + for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; ++i_bc) + { + if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::noslip) + { + VectorTools::interpolate_boundary_values( + mapping, + dof_handler, + nsparam.boundaryConditions.id[i_bc], + ZeroFunction(dim + 1), + nonzero_constraints, + fe.component_mask(velocities)); + } + else if (nsparam.boundaryConditions.type[i_bc] == + BoundaryConditions::slip) + { + std::set no_normal_flux_boundaries; + no_normal_flux_boundaries.insert( + nsparam.boundaryConditions.id[i_bc]); + VectorTools::compute_no_normal_flux_constraints( + dof_handler, 0, no_normal_flux_boundaries, nonzero_constraints); + } + else if (nsparam.boundaryConditions.type[i_bc] == + BoundaryConditions::function) + { + VectorTools::interpolate_boundary_values( + mapping, + dof_handler, + nsparam.boundaryConditions.id[i_bc], + FunctionDefined( &nsparam.boundaryConditions.bcFunctions[i_bc].u, &nsparam.boundaryConditions.bcFunctions[i_bc].v, &nsparam.boundaryConditions.bcFunctions[i_bc].w), - nonzero_constraints, fe.component_mask(velocities)); - } - - else if (nsparam.boundaryConditions.type[i_bc] == - BoundaryConditions::periodic) { + nonzero_constraints, + fe.component_mask(velocities)); + } - DoFTools::make_periodicity_constraints>( - dof_handler, nsparam.boundaryConditions.id[i_bc], - nsparam.boundaryConditions.periodic_id[i_bc], - nsparam.boundaryConditions.periodic_direction[i_bc], - nonzero_constraints); + else if (nsparam.boundaryConditions.type[i_bc] == + BoundaryConditions::periodic) + { + DoFTools::make_periodicity_constraints>( + dof_handler, + nsparam.boundaryConditions.id[i_bc], + nsparam.boundaryConditions.periodic_id[i_bc], + nsparam.boundaryConditions.periodic_direction[i_bc], + nonzero_constraints); + } } - } } nonzero_constraints.close(); @@ -420,40 +501,52 @@ template void GLSNavierStokesSolver::setup_dofs() { zero_constraints.clear(); DoFTools::make_hanging_node_constraints(dof_handler, zero_constraints); - for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; - ++i_bc) { - if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::slip) { - std::set no_normal_flux_boundaries; - no_normal_flux_boundaries.insert(nsparam.boundaryConditions.id[i_bc]); - VectorTools::compute_no_normal_flux_constraints( - dof_handler, 0, no_normal_flux_boundaries, zero_constraints); - } else if (nsparam.boundaryConditions.type[i_bc] == - BoundaryConditions::periodic) { - - DoFTools::make_periodicity_constraints>( - dof_handler, nsparam.boundaryConditions.id[i_bc], - nsparam.boundaryConditions.periodic_id[i_bc], - nsparam.boundaryConditions.periodic_direction[i_bc], - zero_constraints); - } else // if(nsparam.boundaryConditions.boundaries[i_bc].type==Parameters::noslip - // || Parameters::function) + for (unsigned int i_bc = 0; i_bc < nsparam.boundaryConditions.size; ++i_bc) { - VectorTools::interpolate_boundary_values( - mapping, dof_handler, nsparam.boundaryConditions.id[i_bc], - ZeroFunction(dim + 1), zero_constraints, - fe.component_mask(velocities)); + if (nsparam.boundaryConditions.type[i_bc] == BoundaryConditions::slip) + { + std::set no_normal_flux_boundaries; + no_normal_flux_boundaries.insert( + nsparam.boundaryConditions.id[i_bc]); + VectorTools::compute_no_normal_flux_constraints( + dof_handler, 0, no_normal_flux_boundaries, zero_constraints); + } + else if (nsparam.boundaryConditions.type[i_bc] == + BoundaryConditions::periodic) + { + DoFTools::make_periodicity_constraints>( + dof_handler, + nsparam.boundaryConditions.id[i_bc], + nsparam.boundaryConditions.periodic_id[i_bc], + nsparam.boundaryConditions.periodic_direction[i_bc], + zero_constraints); + } + else // if(nsparam.boundaryConditions.boundaries[i_bc].type==Parameters::noslip + // || Parameters::function) + { + VectorTools::interpolate_boundary_values( + mapping, + dof_handler, + nsparam.boundaryConditions.id[i_bc], + ZeroFunction(dim + 1), + zero_constraints, + fe.component_mask(velocities)); + } } - } } zero_constraints.close(); - present_solution.reinit(locally_owned_dofs, locally_relevant_dofs, + present_solution.reinit(locally_owned_dofs, + locally_relevant_dofs, mpi_communicator); - solution_m1.reinit(locally_owned_dofs, locally_relevant_dofs, + solution_m1.reinit(locally_owned_dofs, + locally_relevant_dofs, mpi_communicator); - solution_m2.reinit(locally_owned_dofs, locally_relevant_dofs, + solution_m2.reinit(locally_owned_dofs, + locally_relevant_dofs, mpi_communicator); - solution_m3.reinit(locally_owned_dofs, locally_relevant_dofs, + solution_m3.reinit(locally_owned_dofs, + locally_relevant_dofs, mpi_communicator); newton_update.reinit(locally_owned_dofs, mpi_communicator); @@ -463,9 +556,13 @@ template void GLSNavierStokesSolver::setup_dofs() { DynamicSparsityPattern dsp(locally_relevant_dofs); DoFTools::make_sparsity_pattern(dof_handler, dsp, nonzero_constraints, false); SparsityTools::distribute_sparsity_pattern( - dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator, - locally_relevant_dofs); - system_matrix.reinit(locally_owned_dofs, locally_owned_dofs, dsp, + dsp, + dof_handler.n_locally_owned_dofs_per_processor(), + mpi_communicator, + locally_relevant_dofs); + system_matrix.reinit(locally_owned_dofs, + locally_owned_dofs, + dsp, mpi_communicator); globalVolume_ = GridTools::volume(triangulation); @@ -478,45 +575,49 @@ template void GLSNavierStokesSolver::setup_dofs() { } template -template -void GLSNavierStokesSolver::assembleGLS(const bool initial_step) { +void +GLSNavierStokesSolver::assembleGLS(const bool initial_step) +{ if (assemble_matrix) system_matrix = 0; system_rhs = 0; double viscosity_ = nsparam.physicalProperties.viscosity; - QGauss quadrature_formula(degreeQuadrature_); - const MappingQ mapping(degreeVelocity_, + QGauss quadrature_formula(degreeQuadrature_); + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_quadrature_points | - update_JxW_values | update_gradients | - update_hessians); - const unsigned int dofs_per_cell = fe.dofs_per_cell; - const unsigned int n_q_points = quadrature_formula.size(); + update_JxW_values | update_gradients | + update_hessians); + const unsigned int dofs_per_cell = fe.dofs_per_cell; + const unsigned int n_q_points = quadrature_formula.size(); const FEValuesExtractors::Vector velocities(0); const FEValuesExtractors::Scalar pressure(dim); - FullMatrix local_matrix(dofs_per_cell, dofs_per_cell); - Vector local_rhs(dofs_per_cell); + FullMatrix local_matrix(dofs_per_cell, dofs_per_cell); + Vector local_rhs(dofs_per_cell); std::vector> rhs_force(n_q_points, Vector(dim + 1)); std::vector local_dof_indices(dofs_per_cell); - std::vector> present_velocity_values(n_q_points); - std::vector> present_velocity_gradients(n_q_points); - std::vector present_pressure_values(n_q_points); - std::vector> present_pressure_gradients(n_q_points); - std::vector> present_velocity_laplacians(n_q_points); - std::vector> present_velocity_hess(n_q_points); + std::vector> present_velocity_values(n_q_points); + std::vector> present_velocity_gradients(n_q_points); + std::vector present_pressure_values(n_q_points); + std::vector> present_pressure_gradients(n_q_points); + std::vector> present_velocity_laplacians(n_q_points); + std::vector> present_velocity_hess(n_q_points); Tensor<1, dim> force; - std::vector div_phi_u(dofs_per_cell); + std::vector div_phi_u(dofs_per_cell); std::vector> phi_u(dofs_per_cell); std::vector> hess_phi_u(dofs_per_cell); std::vector> laplacian_phi_u(dofs_per_cell); std::vector> grad_phi_u(dofs_per_cell); - std::vector phi_p(dofs_per_cell); + std::vector phi_p(dofs_per_cell); std::vector> grad_phi_p(dofs_per_cell); // Get the BDF coefficients @@ -543,200 +644,225 @@ void GLSNavierStokesSolver::assembleGLS(const bool initial_step) { double h; typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - if (dim == 2) - h = std::sqrt(4. * cell->measure() / M_PI) / degreeVelocity_; - else if (dim == 3) - h = pow(6 * cell->measure() / M_PI, 1. / 3.) / degreeVelocity_; - - fe_values.reinit(cell); - local_matrix = 0; - - local_rhs = 0; - fe_values[velocities].get_function_values(evaluation_point, - present_velocity_values); - fe_values[velocities].get_function_gradients(evaluation_point, - present_velocity_gradients); - fe_values[pressure].get_function_values(evaluation_point, - present_pressure_values); - fe_values[pressure].get_function_gradients(evaluation_point, - present_pressure_gradients); - fe_values[velocities].get_function_laplacians( - evaluation_point, present_velocity_laplacians); - if (forcing_function) - forcing_function->vector_value_list(fe_values.get_quadrature_points(), - rhs_force); - - if (scheme != Parameters::SimulationControl::steady) - fe_values[velocities].get_function_values(solution_m1, - p1_velocity_values); - if (scheme == Parameters::SimulationControl::bdf2 || - scheme == Parameters::SimulationControl::bdf3) - fe_values[velocities].get_function_values(solution_m2, - p2_velocity_values); - if (scheme == Parameters::SimulationControl::bdf3) - fe_values[velocities].get_function_values(solution_m3, - p3_velocity_values); - - for (unsigned int q = 0; q < n_q_points; ++q) { - const double u_mag = - std::max(present_velocity_values[q].norm(), 1e-3 * GLS_u_scale); - double tau; - if (scheme == Parameters::SimulationControl::steady) - tau = 1. / std::sqrt(std::pow(2. * u_mag / h, 2) + - 9 * std::pow(4 * viscosity_ / (h * h), 2)); - else - tau = 1. / std::sqrt(std::pow(sdt, 2) + std::pow(2. * u_mag / h, 2) + - 9 * std::pow(4 * viscosity_ / (h * h), 2)); - - for (unsigned int k = 0; k < dofs_per_cell; ++k) { - div_phi_u[k] = fe_values[velocities].divergence(k, q); - grad_phi_u[k] = fe_values[velocities].gradient(k, q); - phi_u[k] = fe_values[velocities].value(k, q); - hess_phi_u[k] = fe_values[velocities].hessian(k, q); - phi_p[k] = fe_values[pressure].value(k, q); - grad_phi_p[k] = fe_values[pressure].gradient(k, q); - - for (int d = 0; d < dim; ++d) - laplacian_phi_u[k][d] = trace(hess_phi_u[k][d]); - } + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + if (dim == 2) + h = std::sqrt(4. * cell->measure() / M_PI) / degreeVelocity_; + else if (dim == 3) + h = pow(6 * cell->measure() / M_PI, 1. / 3.) / degreeVelocity_; + + fe_values.reinit(cell); + local_matrix = 0; + + local_rhs = 0; + fe_values[velocities].get_function_values(evaluation_point, + present_velocity_values); + fe_values[velocities].get_function_gradients( + evaluation_point, present_velocity_gradients); + fe_values[pressure].get_function_values(evaluation_point, + present_pressure_values); + fe_values[pressure].get_function_gradients( + evaluation_point, present_pressure_gradients); + fe_values[velocities].get_function_laplacians( + evaluation_point, present_velocity_laplacians); + if (forcing_function) + forcing_function->vector_value_list( + fe_values.get_quadrature_points(), rhs_force); + + if (scheme != Parameters::SimulationControl::steady) + fe_values[velocities].get_function_values(solution_m1, + p1_velocity_values); + if (scheme == Parameters::SimulationControl::bdf2 || + scheme == Parameters::SimulationControl::bdf3) + fe_values[velocities].get_function_values(solution_m2, + p2_velocity_values); + if (scheme == Parameters::SimulationControl::bdf3) + fe_values[velocities].get_function_values(solution_m3, + p3_velocity_values); + + for (unsigned int q = 0; q < n_q_points; ++q) + { + const double u_mag = + std::max(present_velocity_values[q].norm(), 1e-3 * GLS_u_scale); + double tau; + if (scheme == Parameters::SimulationControl::steady) + tau = 1. / std::sqrt(std::pow(2. * u_mag / h, 2) + + 9 * std::pow(4 * viscosity_ / (h * h), 2)); + else + tau = 1. / + std::sqrt(std::pow(sdt, 2) + std::pow(2. * u_mag / h, 2) + + 9 * std::pow(4 * viscosity_ / (h * h), 2)); + + for (unsigned int k = 0; k < dofs_per_cell; ++k) + { + div_phi_u[k] = fe_values[velocities].divergence(k, q); + grad_phi_u[k] = fe_values[velocities].gradient(k, q); + phi_u[k] = fe_values[velocities].value(k, q); + hess_phi_u[k] = fe_values[velocities].hessian(k, q); + phi_p[k] = fe_values[pressure].value(k, q); + grad_phi_p[k] = fe_values[pressure].gradient(k, q); + + for (int d = 0; d < dim; ++d) + laplacian_phi_u[k][d] = trace(hess_phi_u[k][d]); + } - // Establish the force vector - for (int i = 0; i < dim; ++i) { - const unsigned int component_i = - fe.system_to_component_index(i).first; - force[i] = rhs_force[q](component_i); - } + // Establish the force vector + for (int i = 0; i < dim; ++i) + { + const unsigned int component_i = + fe.system_to_component_index(i).first; + force[i] = rhs_force[q](component_i); + } - auto strong_residual = - present_velocity_gradients[q] * present_velocity_values[q] + - present_pressure_gradients[q] - - viscosity_ * present_velocity_laplacians[q] - force; - - if (scheme == Parameters::SimulationControl::bdf1) - strong_residual += alpha_bdf[0] * present_velocity_values[q] + - alpha_bdf[1] * p1_velocity_values[q]; - - if (scheme == Parameters::SimulationControl::bdf2) - strong_residual += alpha_bdf[0] * present_velocity_values[q] + - alpha_bdf[1] * p1_velocity_values[q] + - alpha_bdf[2] * p2_velocity_values[q]; - - if (scheme == Parameters::SimulationControl::bdf3) - strong_residual += alpha_bdf[0] * present_velocity_values[q] + - alpha_bdf[1] * p1_velocity_values[q] + - alpha_bdf[2] * p2_velocity_values[q] + - alpha_bdf[3] * p3_velocity_values[q]; - - if (assemble_matrix) { - for (unsigned int j = 0; j < dofs_per_cell; ++j) { - - auto strong_jac = (present_velocity_gradients[q] * phi_u[j] + - grad_phi_u[j] * present_velocity_values[q] + - grad_phi_p[j] - viscosity_ * laplacian_phi_u[j]); - - if (scheme == Parameters::SimulationControl::bdf1 || - scheme == Parameters::SimulationControl::bdf2 || - scheme == Parameters::SimulationControl::bdf3) - strong_jac += phi_u[j]; - - for (unsigned int i = 0; i < dofs_per_cell; ++i) { - local_matrix(i, j) += - (viscosity_ * scalar_product(grad_phi_u[j], grad_phi_u[i]) + - present_velocity_gradients[q] * phi_u[j] * phi_u[i] + - grad_phi_u[j] * present_velocity_values[q] * phi_u[i] - - div_phi_u[i] * phi_p[j] + phi_p[i] * div_phi_u[j]) * - fe_values.JxW(q); - - // Mass matrix - if (scheme == Parameters::SimulationControl::bdf1 || - scheme == Parameters::SimulationControl::bdf2 || - scheme == Parameters::SimulationControl::bdf3) - local_matrix(i, j) += - phi_u[j] * phi_u[i] * alpha_bdf[0] * fe_values.JxW(q); - - // PSPG GLS term - local_matrix(i, j) += - tau * strong_jac * grad_phi_p[i] * fe_values.JxW(q); - - // Jacobian is currently incomplete - if (SUPG) { - local_matrix(i, j) += - tau * - (strong_jac * (grad_phi_u[i] * present_velocity_values[q]) + - strong_residual * (grad_phi_u[i] * phi_u[j])) * + auto strong_residual = + present_velocity_gradients[q] * present_velocity_values[q] + + present_pressure_gradients[q] - + viscosity_ * present_velocity_laplacians[q] - force; + + if (scheme == Parameters::SimulationControl::bdf1) + strong_residual += alpha_bdf[0] * present_velocity_values[q] + + alpha_bdf[1] * p1_velocity_values[q]; + + if (scheme == Parameters::SimulationControl::bdf2) + strong_residual += alpha_bdf[0] * present_velocity_values[q] + + alpha_bdf[1] * p1_velocity_values[q] + + alpha_bdf[2] * p2_velocity_values[q]; + + if (scheme == Parameters::SimulationControl::bdf3) + strong_residual += alpha_bdf[0] * present_velocity_values[q] + + alpha_bdf[1] * p1_velocity_values[q] + + alpha_bdf[2] * p2_velocity_values[q] + + alpha_bdf[3] * p3_velocity_values[q]; + + if (assemble_matrix) + { + for (unsigned int j = 0; j < dofs_per_cell; ++j) + { + auto strong_jac = + (present_velocity_gradients[q] * phi_u[j] + + grad_phi_u[j] * present_velocity_values[q] + + grad_phi_p[j] - viscosity_ * laplacian_phi_u[j]); + + if (scheme == Parameters::SimulationControl::bdf1 || + scheme == Parameters::SimulationControl::bdf2 || + scheme == Parameters::SimulationControl::bdf3) + strong_jac += phi_u[j]; + + for (unsigned int i = 0; i < dofs_per_cell; ++i) + { + local_matrix(i, j) += + (viscosity_ * + scalar_product(grad_phi_u[j], grad_phi_u[i]) + + present_velocity_gradients[q] * phi_u[j] * + phi_u[i] + + grad_phi_u[j] * present_velocity_values[q] * + phi_u[i] - + div_phi_u[i] * phi_p[j] + + phi_p[i] * div_phi_u[j]) * + fe_values.JxW(q); + + // Mass matrix + if (scheme == Parameters::SimulationControl::bdf1 || + scheme == Parameters::SimulationControl::bdf2 || + scheme == Parameters::SimulationControl::bdf3) + local_matrix(i, j) += phi_u[j] * phi_u[i] * + alpha_bdf[0] * + fe_values.JxW(q); + + // PSPG GLS term + local_matrix(i, j) += + tau * strong_jac * grad_phi_p[i] * fe_values.JxW(q); + + // Jacobian is currently incomplete + if (SUPG) + { + local_matrix(i, j) += + tau * + (strong_jac * (grad_phi_u[i] * + present_velocity_values[q]) + + strong_residual * (grad_phi_u[i] * phi_u[j])) * + fe_values.JxW(q); + } + } + } + } + for (unsigned int i = 0; i < dofs_per_cell; ++i) + { + // const unsigned int component_i = + // fe.system_to_component_index(i).first; + + double present_velocity_divergence = + trace(present_velocity_gradients[q]); + local_rhs(i) += + (-viscosity_ * scalar_product(present_velocity_gradients[q], + grad_phi_u[i]) - + present_velocity_gradients[q] * + present_velocity_values[q] * phi_u[i] + + present_pressure_values[q] * div_phi_u[i] - + present_velocity_divergence * phi_p[i] + + force * phi_u[i]) * fe_values.JxW(q); - } + + if (scheme == Parameters::SimulationControl::bdf1) + local_rhs(i) -= + alpha_bdf[0] * + (present_velocity_values[q] - p1_velocity_values[q]) * + phi_u[i] * fe_values.JxW(q); + + if (scheme == Parameters::SimulationControl::bdf2) + local_rhs(i) -= + (alpha_bdf[0] * (present_velocity_values[q] * phi_u[i]) + + alpha_bdf[1] * (p1_velocity_values[q] * phi_u[i]) + + alpha_bdf[2] * (p2_velocity_values[q] * phi_u[i])) * + fe_values.JxW(q); + + if (scheme == Parameters::SimulationControl::bdf3) + local_rhs(i) -= + (alpha_bdf[0] * (present_velocity_values[q] * phi_u[i]) + + alpha_bdf[1] * (p1_velocity_values[q] * phi_u[i]) + + alpha_bdf[2] * (p2_velocity_values[q] * phi_u[i]) + + alpha_bdf[3] * (p3_velocity_values[q] * phi_u[i])) * + fe_values.JxW(q); + + // PSPG GLS term + local_rhs(i) += + -tau * (strong_residual * grad_phi_p[i]) * fe_values.JxW(q); + + // SUPG GLS term + if (SUPG) + { + local_rhs(i) += + -tau * + (strong_residual * + (grad_phi_u[i] * present_velocity_values[q])) * + fe_values.JxW(q); + } + } } - } - } - for (unsigned int i = 0; i < dofs_per_cell; ++i) { - - // const unsigned int component_i = - // fe.system_to_component_index(i).first; - - double present_velocity_divergence = - trace(present_velocity_gradients[q]); - local_rhs(i) += - (-viscosity_ * scalar_product(present_velocity_gradients[q], - grad_phi_u[i]) - - present_velocity_gradients[q] * present_velocity_values[q] * - phi_u[i] + - present_pressure_values[q] * div_phi_u[i] - - present_velocity_divergence * phi_p[i] + force * phi_u[i]) * - fe_values.JxW(q); - - if (scheme == Parameters::SimulationControl::bdf1) - local_rhs(i) -= - alpha_bdf[0] * - (present_velocity_values[q] - p1_velocity_values[q]) * - phi_u[i] * fe_values.JxW(q); - - if (scheme == Parameters::SimulationControl::bdf2) - local_rhs(i) -= - (alpha_bdf[0] * (present_velocity_values[q] * phi_u[i]) + - alpha_bdf[1] * (p1_velocity_values[q] * phi_u[i]) + - alpha_bdf[2] * (p2_velocity_values[q] * phi_u[i])) * - fe_values.JxW(q); - if (scheme == Parameters::SimulationControl::bdf3) - local_rhs(i) -= - (alpha_bdf[0] * (present_velocity_values[q] * phi_u[i]) + - alpha_bdf[1] * (p1_velocity_values[q] * phi_u[i]) + - alpha_bdf[2] * (p2_velocity_values[q] * phi_u[i]) + - alpha_bdf[3] * (p3_velocity_values[q] * phi_u[i])) * - fe_values.JxW(q); - - // PSPG GLS term - local_rhs(i) += - -tau * (strong_residual * grad_phi_p[i]) * fe_values.JxW(q); - - // SUPG GLS term - if (SUPG) { - local_rhs(i) += -tau * - (strong_residual * - (grad_phi_u[i] * present_velocity_values[q])) * - fe_values.JxW(q); - } + cell->get_dof_indices(local_dof_indices); + const AffineConstraints &constraints_used = + initial_step ? nonzero_constraints : zero_constraints; + if (assemble_matrix) + { + constraints_used.distribute_local_to_global(local_matrix, + local_rhs, + local_dof_indices, + system_matrix, + system_rhs); + } + else + { + constraints_used.distribute_local_to_global(local_rhs, + local_dof_indices, + system_rhs); + } } - } - - cell->get_dof_indices(local_dof_indices); - const AffineConstraints &constraints_used = - initial_step ? nonzero_constraints : zero_constraints; - if (assemble_matrix) { - constraints_used.distribute_local_to_global(local_matrix, local_rhs, - local_dof_indices, - system_matrix, system_rhs); - } else { - constraints_used.distribute_local_to_global( - local_rhs, local_dof_indices, system_rhs); - } } - } system_matrix.compress(VectorOperation::add); system_rhs.compress(VectorOperation::add); } @@ -745,202 +871,245 @@ void GLSNavierStokesSolver::assembleGLS(const bool initial_step) { * Set the initial condition using a L2 or a viscous solver **/ template -void GLSNavierStokesSolver::set_initial_condition( - Parameters::InitialConditionType initial_condition_type, bool restart) { - if (restart) { - pcout << "************************" << std::endl; - pcout << "---> Simulation Restart " << std::endl; - pcout << "************************" << std::endl; - read_checkpoint(); - } else if (initial_condition_type == - Parameters::InitialConditionType::L2projection) { - assemble_L2_projection(); - solve_system(true, 1e-15, 1e-15); - present_solution = newton_update; - finish_time_step(); - postprocess(); - } else if (initial_condition_type == - Parameters::InitialConditionType::nodal) { - set_nodal_values(); - finish_time_step(); - postprocess(); - } - +void +GLSNavierStokesSolver::set_initial_condition( + Parameters::InitialConditionType initial_condition_type, + bool restart) +{ + if (restart) + { + pcout << "************************" << std::endl; + pcout << "---> Simulation Restart " << std::endl; + pcout << "************************" << std::endl; + read_checkpoint(); + } else if (initial_condition_type == - Parameters::InitialConditionType::viscous) { - double viscosity = this->nsparam.physicalProperties.viscosity; - this->nsparam.physicalProperties.viscosity = + Parameters::InitialConditionType::L2projection) + { + assemble_L2_projection(); + solve_system(true, 1e-15, 1e-15); + present_solution = newton_update; + finish_time_step(); + postprocess(); + } + else if (initial_condition_type == Parameters::InitialConditionType::nodal) + { + set_nodal_values(); + finish_time_step(); + postprocess(); + } + + else if (initial_condition_type == Parameters::InitialConditionType::viscous) + { + double viscosity = this->nsparam.physicalProperties.viscosity; + this->nsparam.physicalProperties.viscosity = nsparam.initialCondition->viscosity; - Parameters::SimulationControl::TimeSteppingMethod previousControl = + Parameters::SimulationControl::TimeSteppingMethod previousControl = simulationControl.getMethod(); - simulationControl.setMethod(Parameters::SimulationControl::steady); - newton_iteration(true); - simulationControl.setMethod(previousControl); - finish_time_step(); - postprocess(); - simulationControl.setMethod(previousControl); - this->nsparam.physicalProperties.viscosity = viscosity; - } else { - throw std::runtime_error("GLSNS - Initial condition could not be set"); - } + simulationControl.setMethod(Parameters::SimulationControl::steady); + newton_iteration(true); + simulationControl.setMethod(previousControl); + finish_time_step(); + postprocess(); + simulationControl.setMethod(previousControl); + this->nsparam.physicalProperties.viscosity = viscosity; + } + else + { + throw std::runtime_error("GLSNS - Initial condition could not be set"); + } } // Do an iteration with the GLS NavierStokes Solver // Handles the fact that we may or may not be at a first // iteration with the solver and sets the initial condition template -void GLSNavierStokesSolver::iterate(bool firstIteration) { +void +GLSNavierStokesSolver::iterate(bool firstIteration) +{ // Carry out the integration normally - if (!firstIteration) { - newton_iteration(false); - } - // This is the first iteration - else { - if (simulationControl.getMethod() == - Parameters::SimulationControl::steady) { - newton_iteration(false); - } else if (simulationControl.getMethod() == - Parameters::SimulationControl::bdf1) { - newton_iteration(false); - } else if (simulationControl.getMethod() == - Parameters::SimulationControl::bdf2) { - Parameters::SimulationControl timeParameters = - simulationControl.getParameters(); - - // Start the BDF2 with a single Euler time step with a lower time step - simulationControl.setTimeStep(timeParameters.dt * - timeParameters.startup_timestep_scaling); - simulationControl.setMethod(Parameters::SimulationControl::bdf1); - newton_iteration(false); - solution_m2 = solution_m1; - solution_m1 = present_solution; - - // Reset the time step and do a bdf 2 newton iteration using the two steps - // to complete the full step - simulationControl.setMethod(Parameters::SimulationControl::bdf2); - simulationControl.setTimeStep( - timeParameters.dt * (1. - timeParameters.startup_timestep_scaling)); + if (!firstIteration) + { newton_iteration(false); } + // This is the first iteration + else + { + if (simulationControl.getMethod() == + Parameters::SimulationControl::steady) + { + newton_iteration(false); + } + else if (simulationControl.getMethod() == + Parameters::SimulationControl::bdf1) + { + newton_iteration(false); + } + else if (simulationControl.getMethod() == + Parameters::SimulationControl::bdf2) + { + Parameters::SimulationControl timeParameters = + simulationControl.getParameters(); + + // Start the BDF2 with a single Euler time step with a lower time step + simulationControl.setTimeStep( + timeParameters.dt * timeParameters.startup_timestep_scaling); + simulationControl.setMethod(Parameters::SimulationControl::bdf1); + newton_iteration(false); + solution_m2 = solution_m1; + solution_m1 = present_solution; + + // Reset the time step and do a bdf 2 newton iteration using the two + // steps to complete the full step + simulationControl.setMethod(Parameters::SimulationControl::bdf2); + simulationControl.setTimeStep( + timeParameters.dt * (1. - timeParameters.startup_timestep_scaling)); + newton_iteration(false); + } - else if (simulationControl.getMethod() == - Parameters::SimulationControl::bdf3) { - Parameters::SimulationControl timeParameters = - simulationControl.getParameters(); - - // Start the BDF2 with a single Euler time step with a lower time step - simulationControl.setTimeStep(timeParameters.dt * - timeParameters.startup_timestep_scaling); - simulationControl.setMethod(Parameters::SimulationControl::bdf1); - newton_iteration(false); - solution_m2 = solution_m1; - solution_m1 = present_solution; - - // Reset the time step and do a bdf 2 newton iteration using the two steps - simulationControl.setMethod(Parameters::SimulationControl::bdf1); - simulationControl.setTimeStep(timeParameters.dt * - timeParameters.startup_timestep_scaling); - newton_iteration(false); - solution_m3 = solution_m2; - solution_m2 = solution_m1; - solution_m1 = present_solution; - - // Reset the time step and do a bdf 3 newton iteration using the two steps - // to complete the full step - simulationControl.setMethod(Parameters::SimulationControl::bdf3); - simulationControl.setTimeStep( - timeParameters.dt * - (1. - 2. * timeParameters.startup_timestep_scaling)); - newton_iteration(false); + else if (simulationControl.getMethod() == + Parameters::SimulationControl::bdf3) + { + Parameters::SimulationControl timeParameters = + simulationControl.getParameters(); + + // Start the BDF2 with a single Euler time step with a lower time step + simulationControl.setTimeStep( + timeParameters.dt * timeParameters.startup_timestep_scaling); + simulationControl.setMethod(Parameters::SimulationControl::bdf1); + newton_iteration(false); + solution_m2 = solution_m1; + solution_m1 = present_solution; + + // Reset the time step and do a bdf 2 newton iteration using the two + // steps + simulationControl.setMethod(Parameters::SimulationControl::bdf1); + simulationControl.setTimeStep( + timeParameters.dt * timeParameters.startup_timestep_scaling); + newton_iteration(false); + solution_m3 = solution_m2; + solution_m2 = solution_m1; + solution_m1 = present_solution; + + // Reset the time step and do a bdf 3 newton iteration using the two + // steps to complete the full step + simulationControl.setMethod(Parameters::SimulationControl::bdf3); + simulationControl.setTimeStep( + timeParameters.dt * + (1. - 2. * timeParameters.startup_timestep_scaling)); + newton_iteration(false); + } } - } } -template void GLSNavierStokesSolver::assemble_L2_projection() { +template +void +GLSNavierStokesSolver::assemble_L2_projection() +{ system_matrix = 0; - system_rhs = 0; - QGauss quadrature_formula(degreeQuadrature_); - const MappingQ mapping(degreeVelocity_, + system_rhs = 0; + QGauss quadrature_formula(degreeQuadrature_); + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_quadrature_points | - update_JxW_values); - const unsigned int dofs_per_cell = fe.dofs_per_cell; - const unsigned int n_q_points = quadrature_formula.size(); - FullMatrix local_matrix(dofs_per_cell, dofs_per_cell); - Vector local_rhs(dofs_per_cell); + update_JxW_values); + const unsigned int dofs_per_cell = fe.dofs_per_cell; + const unsigned int n_q_points = quadrature_formula.size(); + FullMatrix local_matrix(dofs_per_cell, dofs_per_cell); + Vector local_rhs(dofs_per_cell); std::vector> initial_velocity(n_q_points, Vector(dim + 1)); std::vector local_dof_indices(dofs_per_cell); - const FEValuesExtractors::Vector velocities(0); - const FEValuesExtractors::Scalar pressure(dim); + const FEValuesExtractors::Vector velocities(0); + const FEValuesExtractors::Scalar pressure(dim); Tensor<1, dim> rhs_initial_velocity_pressure; - double rhs_initial_pressure; + double rhs_initial_pressure; std::vector> phi_u(dofs_per_cell); - std::vector phi_p(dofs_per_cell); + std::vector phi_p(dofs_per_cell); typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - fe_values.reinit(cell); - local_matrix = 0; - local_rhs = 0; - nsparam.initialCondition->uvwp.vector_value_list( - fe_values.get_quadrature_points(), initial_velocity); - for (unsigned int q = 0; q < n_q_points; ++q) { - for (unsigned int k = 0; k < dofs_per_cell; ++k) { - phi_p[k] = fe_values[pressure].value(k, q); - phi_u[k] = fe_values[velocities].value(k, q); - } + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + fe_values.reinit(cell); + local_matrix = 0; + local_rhs = 0; + nsparam.initialCondition->uvwp.vector_value_list( + fe_values.get_quadrature_points(), initial_velocity); + for (unsigned int q = 0; q < n_q_points; ++q) + { + for (unsigned int k = 0; k < dofs_per_cell; ++k) + { + phi_p[k] = fe_values[pressure].value(k, q); + phi_u[k] = fe_values[velocities].value(k, q); + } - // Establish the rhs tensor operator - for (int i = 0; i < dim; ++i) { - const unsigned int component_i = - fe.system_to_component_index(i).first; - rhs_initial_velocity_pressure[i] = initial_velocity[q](component_i); - } - rhs_initial_pressure = initial_velocity[q](dim); + // Establish the rhs tensor operator + for (int i = 0; i < dim; ++i) + { + const unsigned int component_i = + fe.system_to_component_index(i).first; + rhs_initial_velocity_pressure[i] = + initial_velocity[q](component_i); + } + rhs_initial_pressure = initial_velocity[q](dim); + + for (unsigned int i = 0; i < dofs_per_cell; ++i) + { + // Matrix assembly + for (unsigned int j = 0; j < dofs_per_cell; ++j) + { + local_matrix(i, j) += + (phi_u[j] * phi_u[i]) * fe_values.JxW(q); + local_matrix(i, j) += + (phi_p[j] * phi_p[i]) * fe_values.JxW(q); + } + local_rhs(i) += (phi_u[i] * rhs_initial_velocity_pressure + + phi_p[i] * rhs_initial_pressure) * + fe_values.JxW(q); + } + } - for (unsigned int i = 0; i < dofs_per_cell; ++i) { - // Matrix assembly - for (unsigned int j = 0; j < dofs_per_cell; ++j) { - local_matrix(i, j) += (phi_u[j] * phi_u[i]) * fe_values.JxW(q); - local_matrix(i, j) += (phi_p[j] * phi_p[i]) * fe_values.JxW(q); - } - local_rhs(i) += (phi_u[i] * rhs_initial_velocity_pressure + - phi_p[i] * rhs_initial_pressure) * - fe_values.JxW(q); + cell->get_dof_indices(local_dof_indices); + const AffineConstraints &constraints_used = + nonzero_constraints; + constraints_used.distribute_local_to_global(local_matrix, + local_rhs, + local_dof_indices, + system_matrix, + system_rhs); } - } - - cell->get_dof_indices(local_dof_indices); - const AffineConstraints &constraints_used = nonzero_constraints; - constraints_used.distribute_local_to_global(local_matrix, local_rhs, - local_dof_indices, - system_matrix, system_rhs); } - } system_matrix.compress(VectorOperation::add); system_rhs.compress(VectorOperation::add); } -template double GLSNavierStokesSolver::calculate_CFL() { - QGauss quadrature_formula(1); - const MappingQ mapping(degreeVelocity_, +template +double +GLSNavierStokesSolver::calculate_CFL() +{ + QGauss quadrature_formula(1); + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_quadrature_points); - const unsigned int dofs_per_cell = fe.dofs_per_cell; - const unsigned int n_q_points = quadrature_formula.size(); - std::vector> initial_velocity(n_q_points, - Vector(dim + 1)); + const unsigned int dofs_per_cell = fe.dofs_per_cell; + const unsigned int n_q_points = quadrature_formula.size(); + std::vector> initial_velocity(n_q_points, + Vector(dim + 1)); std::vector local_dof_indices(dofs_per_cell); - const FEValuesExtractors::Vector velocities(0); - const FEValuesExtractors::Scalar pressure(dim); + const FEValuesExtractors::Vector velocities(0); + const FEValuesExtractors::Scalar pressure(dim); std::vector> present_velocity_values(n_q_points); @@ -954,44 +1123,58 @@ template double GLSNavierStokesSolver::calculate_CFL() { double CFL = 0; typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - if (dim == 2) - h = std::sqrt(4. * cell->measure() / M_PI) / degreeVelocity_; - else if (dim == 3) - h = pow(6 * cell->measure() / M_PI, 1. / 3.) / degreeVelocity_; - fe_values.reinit(cell); - fe_values[velocities].get_function_values(present_solution, - present_velocity_values); - for (unsigned int q = 0; q < n_q_points; ++q) { - const double localCFL = - present_velocity_values[q].norm() / h * timeStep; - CFL = std::max(CFL, localCFL); - } + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + if (dim == 2) + h = std::sqrt(4. * cell->measure() / M_PI) / degreeVelocity_; + else if (dim == 3) + h = pow(6 * cell->measure() / M_PI, 1. / 3.) / degreeVelocity_; + fe_values.reinit(cell); + fe_values[velocities].get_function_values(present_solution, + present_velocity_values); + for (unsigned int q = 0; q < n_q_points; ++q) + { + const double localCFL = + present_velocity_values[q].norm() / h * timeStep; + CFL = std::max(CFL, localCFL); + } + } } - } CFL = Utilities::MPI::max(CFL, mpi_communicator); return CFL; } -template void GLSNavierStokesSolver::set_nodal_values() { +template +void +GLSNavierStokesSolver::set_nodal_values() +{ const FEValuesExtractors::Vector velocities(0); const FEValuesExtractors::Scalar pressure(dim); - const MappingQ mapping(degreeVelocity_, + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - VectorTools::interpolate(mapping, dof_handler, nsparam.initialCondition->uvwp, - newton_update, fe.component_mask(velocities)); - VectorTools::interpolate(mapping, dof_handler, nsparam.initialCondition->uvwp, - newton_update, fe.component_mask(pressure)); + VectorTools::interpolate(mapping, + dof_handler, + nsparam.initialCondition->uvwp, + newton_update, + fe.component_mask(velocities)); + VectorTools::interpolate(mapping, + dof_handler, + nsparam.initialCondition->uvwp, + newton_update, + fe.component_mask(pressure)); nonzero_constraints.distribute(newton_update); present_solution = newton_update; } template -void GLSNavierStokesSolver::assemble_system(const bool initial_step) { +void +GLSNavierStokesSolver::assemble_system(const bool initial_step) +{ TimerOutput::Scope t(computing_timer, "assemble_system"); if (simulationControl.getMethod() == Parameters::SimulationControl::bdf1) @@ -1005,7 +1188,9 @@ void GLSNavierStokesSolver::assemble_system(const bool initial_step) { assembleGLS(initial_step); } template -void GLSNavierStokesSolver::assemble_rhs(const bool initial_step) { +void +GLSNavierStokesSolver::assemble_rhs(const bool initial_step) +{ TimerOutput::Scope t(computing_timer, "assemble_rhs"); if (simulationControl.getMethod() == Parameters::SimulationControl::bdf1) @@ -1020,9 +1205,11 @@ void GLSNavierStokesSolver::assemble_rhs(const bool initial_step) { } template -void GLSNavierStokesSolver::solve_system(const bool initial_step, - double relative_residual, - double minimum_residual) { +void +GLSNavierStokesSolver::solve_system(const bool initial_step, + double relative_residual, + double minimum_residual) +{ if (nsparam.linearSolver.solver == nsparam.linearSolver.gmres) solve_system_GMRES(initial_step, minimum_residual, relative_residual); else if (nsparam.linearSolver.solver == nsparam.linearSolver.bicgstab) @@ -1034,25 +1221,30 @@ void GLSNavierStokesSolver::solve_system(const bool initial_step, } template -void GLSNavierStokesSolver::solve_system_GMRES(const bool initial_step, - double absolute_residual, - double relative_residual) { - TimerOutput::Scope t(computing_timer, "solve"); +void +GLSNavierStokesSolver::solve_system_GMRES(const bool initial_step, + double absolute_residual, + double relative_residual) +{ + TimerOutput::Scope t(computing_timer, "solve"); const AffineConstraints &constraints_used = - initial_step ? nonzero_constraints : zero_constraints; + initial_step ? nonzero_constraints : zero_constraints; const double linear_solver_tolerance = - std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); + std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Tolerance of iterative solver is : " - << std::setprecision(nsparam.linearSolver.residual_precision) - << linear_solver_tolerance << std::endl; - } + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Tolerance of iterative solver is : " + << std::setprecision(nsparam.linearSolver.residual_precision) + << linear_solver_tolerance << std::endl; + } TrilinosWrappers::MPI::Vector completely_distributed_solution( - locally_owned_dofs, mpi_communicator); + locally_owned_dofs, mpi_communicator); SolverControl solver_control(nsparam.linearSolver.max_iterations, - linear_solver_tolerance, true, true); + linear_solver_tolerance, + true, + true); TrilinosWrappers::SolverGMRES solver(solver_control); //********************************************** @@ -1062,43 +1254,51 @@ void GLSNavierStokesSolver::solve_system_GMRES(const bool initial_step, const double ilu_atol = nsparam.linearSolver.ilu_precond_atol; const double ilu_rtol = nsparam.linearSolver.ilu_precond_rtol; TrilinosWrappers::PreconditionILU::AdditionalData preconditionerOptions( - ilu_fill, ilu_atol, ilu_rtol, 0); + ilu_fill, ilu_atol, ilu_rtol, 0); TrilinosWrappers::PreconditionILU preconditioner; preconditioner.initialize(system_matrix, preconditionerOptions); - solver.solve(system_matrix, completely_distributed_solution, system_rhs, + solver.solve(system_matrix, + completely_distributed_solution, + system_rhs, preconditioner); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Iterative solver took : " << solver_control.last_step() - << " steps " << std::endl; - } + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Iterative solver took : " << solver_control.last_step() + << " steps " << std::endl; + } constraints_used.distribute(completely_distributed_solution); newton_update = completely_distributed_solution; } template -void GLSNavierStokesSolver::solve_system_BiCGStab( - const bool initial_step, double absolute_residual, - double relative_residual) { +void +GLSNavierStokesSolver::solve_system_BiCGStab(const bool initial_step, + double absolute_residual, + double relative_residual) +{ TimerOutput::Scope t(computing_timer, "solve"); const AffineConstraints &constraints_used = - initial_step ? nonzero_constraints : zero_constraints; + initial_step ? nonzero_constraints : zero_constraints; const double linear_solver_tolerance = - std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Tolerance of iterative solver is : " - << std::setprecision(nsparam.linearSolver.residual_precision) - << linear_solver_tolerance << std::endl; - } + std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Tolerance of iterative solver is : " + << std::setprecision(nsparam.linearSolver.residual_precision) + << linear_solver_tolerance << std::endl; + } TrilinosWrappers::MPI::Vector completely_distributed_solution( - locally_owned_dofs, mpi_communicator); + locally_owned_dofs, mpi_communicator); SolverControl solver_control(nsparam.linearSolver.max_iterations, - linear_solver_tolerance, true, true); + linear_solver_tolerance, + true, + true); TrilinosWrappers::SolverBicgstab solver(solver_control); //********************************************** @@ -1108,43 +1308,51 @@ void GLSNavierStokesSolver::solve_system_BiCGStab( const double ilu_atol = nsparam.linearSolver.ilu_precond_atol; const double ilu_rtol = nsparam.linearSolver.ilu_precond_rtol; TrilinosWrappers::PreconditionILU::AdditionalData preconditionerOptions( - ilu_fill, ilu_atol, ilu_rtol, 0); + ilu_fill, ilu_atol, ilu_rtol, 0); TrilinosWrappers::PreconditionILU preconditioner; preconditioner.initialize(system_matrix, preconditionerOptions); - solver.solve(system_matrix, completely_distributed_solution, system_rhs, + solver.solve(system_matrix, + completely_distributed_solution, + system_rhs, preconditioner); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Iterative solver took : " << solver_control.last_step() - << " steps " << std::endl; - } + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Iterative solver took : " << solver_control.last_step() + << " steps " << std::endl; + } constraints_used.distribute(completely_distributed_solution); newton_update = completely_distributed_solution; } template -void GLSNavierStokesSolver::solve_system_AMG(const bool initial_step, - double absolute_residual, - double relative_residual) { +void +GLSNavierStokesSolver::solve_system_AMG(const bool initial_step, + double absolute_residual, + double relative_residual) +{ TimerOutput::Scope t(computing_timer, "solve"); const AffineConstraints &constraints_used = - initial_step ? nonzero_constraints : zero_constraints; + initial_step ? nonzero_constraints : zero_constraints; const double linear_solver_tolerance = - std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Tolerance of iterative solver is : " - << std::setprecision(nsparam.linearSolver.residual_precision) - << linear_solver_tolerance << std::endl; - } + std::max(relative_residual * system_rhs.l2_norm(), absolute_residual); + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Tolerance of iterative solver is : " + << std::setprecision(nsparam.linearSolver.residual_precision) + << linear_solver_tolerance << std::endl; + } TrilinosWrappers::MPI::Vector completely_distributed_solution( - locally_owned_dofs, mpi_communicator); + locally_owned_dofs, mpi_communicator); SolverControl solver_control(nsparam.linearSolver.max_iterations, - linear_solver_tolerance, true, true); + linear_solver_tolerance, + true, + true); TrilinosWrappers::SolverGMRES solver(solver_control); TrilinosWrappers::PreconditionAMG preconditioner; @@ -1153,34 +1361,44 @@ void GLSNavierStokesSolver::solve_system_AMG(const bool initial_step, // Constant modes include pressure since everything is in the same matrix std::vector velocity_components(dim + 1, true); velocity_components[dim] = true; - DoFTools::extract_constant_modes(dof_handler, velocity_components, + DoFTools::extract_constant_modes(dof_handler, + velocity_components, constant_modes); TrilinosWrappers::PreconditionAMG::AdditionalData amg_data; amg_data.constant_modes = constant_modes; - const bool elliptic = false; - bool higher_order_elements = false; + const bool elliptic = false; + bool higher_order_elements = false; if (degreeVelocity_ > 1) higher_order_elements = true; const unsigned int n_cycles = nsparam.linearSolver.amg_n_cycles; - const bool w_cycle = nsparam.linearSolver.amg_w_cycles; - const double aggregation_threshold = - nsparam.linearSolver.amg_aggregation_threshold; + const bool w_cycle = nsparam.linearSolver.amg_w_cycles; + const double aggregation_threshold = + nsparam.linearSolver.amg_aggregation_threshold; const unsigned int smoother_sweeps = nsparam.linearSolver.amg_smoother_sweeps; const unsigned int smoother_overlap = - nsparam.linearSolver.amg_smoother_overlap; - const bool output_details = false; - const char *smoother_type = "ILU"; - const char *coarse_type = "ILU"; + nsparam.linearSolver.amg_smoother_overlap; + const bool output_details = false; + const char * smoother_type = "ILU"; + const char * coarse_type = "ILU"; TrilinosWrappers::PreconditionAMG::AdditionalData preconditionerOptions( - elliptic, higher_order_elements, n_cycles, w_cycle, aggregation_threshold, - constant_modes, smoother_sweeps, smoother_overlap, output_details, - smoother_type, coarse_type); - - Teuchos::ParameterList parameter_ml; + elliptic, + higher_order_elements, + n_cycles, + w_cycle, + aggregation_threshold, + constant_modes, + smoother_sweeps, + smoother_overlap, + output_details, + smoother_type, + coarse_type); + + Teuchos::ParameterList parameter_ml; std::unique_ptr distributed_constant_modes; - preconditionerOptions.set_parameters(parameter_ml, distributed_constant_modes, + preconditionerOptions.set_parameters(parameter_ml, + distributed_constant_modes, system_matrix); const double ilu_fill = nsparam.linearSolver.amg_precond_ilu_fill; const double ilu_atol = nsparam.linearSolver.amg_precond_ilu_atol; @@ -1194,72 +1412,94 @@ void GLSNavierStokesSolver::solve_system_AMG(const bool initial_step, parameter_ml.set("coarse: ifpack relative threshold", ilu_rtol); preconditioner.initialize(system_matrix, parameter_ml); - solver.solve(system_matrix, completely_distributed_solution, system_rhs, + solver.solve(system_matrix, + completely_distributed_solution, + system_rhs, preconditioner); - if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) { - pcout << " -Iterative solver took : " << solver_control.last_step() - << " steps " << std::endl; - } + if (nsparam.linearSolver.verbosity != Parameters::LinearSolver::quiet) + { + pcout << " -Iterative solver took : " << solver_control.last_step() + << " steps " << std::endl; + } constraints_used.distribute(completely_distributed_solution); newton_update = completely_distributed_solution; } -template void GLSNavierStokesSolver::refine_mesh() { - if (simulationControl.getIter() % nsparam.meshAdaptation.frequency == 0) { - if (nsparam.meshAdaptation.type == nsparam.meshAdaptation.kelly) - refine_mesh_Kelly(); - if (nsparam.meshAdaptation.type == nsparam.meshAdaptation.uniform) - refine_mesh_uniform(); - } +template +void +GLSNavierStokesSolver::refine_mesh() +{ + if (simulationControl.getIter() % nsparam.meshAdaptation.frequency == 0) + { + if (nsparam.meshAdaptation.type == nsparam.meshAdaptation.kelly) + refine_mesh_Kelly(); + if (nsparam.meshAdaptation.type == nsparam.meshAdaptation.uniform) + refine_mesh_uniform(); + } } -template void GLSNavierStokesSolver::refine_mesh_Kelly() { +template +void +GLSNavierStokesSolver::refine_mesh_Kelly() +{ // Time monitoring TimerOutput::Scope t(computing_timer, "refine"); - Vector estimated_error_per_cell(triangulation.n_active_cells()); + Vector estimated_error_per_cell(triangulation.n_active_cells()); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); const FEValuesExtractors::Vector velocity(0); const FEValuesExtractors::Scalar pressure(dim); - if (nsparam.meshAdaptation.variable == Parameters::MeshAdaptation::pressure) { - KellyErrorEstimator::estimate( - mapping, dof_handler, QGauss(degreeQuadrature_ + 1), + if (nsparam.meshAdaptation.variable == Parameters::MeshAdaptation::pressure) + { + KellyErrorEstimator::estimate( + mapping, + dof_handler, + QGauss(degreeQuadrature_ + 1), typename std::map *>(), - present_solution, estimated_error_per_cell, + present_solution, + estimated_error_per_cell, fe.component_mask(pressure)); - } - if (nsparam.meshAdaptation.variable == Parameters::MeshAdaptation::velocity) { - KellyErrorEstimator::estimate( - mapping, dof_handler, QGauss(degreeQuadrature_ + 1), + } + else if (nsparam.meshAdaptation.variable == Parameters::MeshAdaptation::velocity) + { + KellyErrorEstimator::estimate( + mapping, + dof_handler, + QGauss(degreeQuadrature_ + 1), typename std::map *>(), - present_solution, estimated_error_per_cell, + present_solution, + estimated_error_per_cell, fe.component_mask(velocity)); - } + } + if (nsparam.meshAdaptation.fractionType == Parameters::MeshAdaptation::number) parallel::distributed::GridRefinement::refine_and_coarsen_fixed_number( - triangulation, estimated_error_per_cell, - nsparam.meshAdaptation.fractionRefinement, - nsparam.meshAdaptation.fractionCoarsening, - nsparam.meshAdaptation.maxNbElements); + triangulation, + estimated_error_per_cell, + nsparam.meshAdaptation.fractionRefinement, + nsparam.meshAdaptation.fractionCoarsening, + nsparam.meshAdaptation.maxNbElements); - if (nsparam.meshAdaptation.fractionType == + else if (nsparam.meshAdaptation.fractionType == Parameters::MeshAdaptation::fraction) parallel::distributed::GridRefinement::refine_and_coarsen_fixed_fraction( - triangulation, estimated_error_per_cell, - nsparam.meshAdaptation.fractionRefinement, - nsparam.meshAdaptation.fractionCoarsening); + triangulation, + estimated_error_per_cell, + nsparam.meshAdaptation.fractionRefinement, + nsparam.meshAdaptation.fractionCoarsening); if (triangulation.n_levels() > nsparam.meshAdaptation.maxRefLevel) for (typename Triangulation::active_cell_iterator cell = - triangulation.begin_active(nsparam.meshAdaptation.maxRefLevel); - cell != triangulation.end(); ++cell) + triangulation.begin_active(nsparam.meshAdaptation.maxRefLevel); + cell != triangulation.end(); + ++cell) cell->clear_refine_flag(); for (typename Triangulation::active_cell_iterator cell = - triangulation.begin_active(nsparam.meshAdaptation.minRefLevel); + triangulation.begin_active(nsparam.meshAdaptation.minRefLevel); cell != triangulation.end_active(nsparam.meshAdaptation.minRefLevel); ++cell) cell->clear_coarsen_flag(); @@ -1268,13 +1508,13 @@ template void GLSNavierStokesSolver::refine_mesh_Kelly() { // Solution transfer objects for all the solutions parallel::distributed::SolutionTransfer - solution_transfer(dof_handler); + solution_transfer(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m1(dof_handler); + solution_transfer_m1(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m2(dof_handler); + solution_transfer_m2(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m3(dof_handler); + solution_transfer_m3(dof_handler); solution_transfer.prepare_for_coarsening_and_refinement(present_solution); solution_transfer_m1.prepare_for_coarsening_and_refinement(solution_m1); solution_transfer_m2.prepare_for_coarsening_and_refinement(solution_m2); @@ -1303,23 +1543,26 @@ template void GLSNavierStokesSolver::refine_mesh_Kelly() { // Fix on the new mesh present_solution = tmp; - solution_m1 = tmp_m1; - solution_m2 = tmp_m2; - solution_m3 = tmp_m3; + solution_m1 = tmp_m1; + solution_m2 = tmp_m2; + solution_m3 = tmp_m3; } -template void GLSNavierStokesSolver::refine_mesh_uniform() { +template +void +GLSNavierStokesSolver::refine_mesh_uniform() +{ TimerOutput::Scope t(computing_timer, "refine"); // Solution transfer objects for all the solutions parallel::distributed::SolutionTransfer - solution_transfer(dof_handler); + solution_transfer(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m1(dof_handler); + solution_transfer_m1(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m2(dof_handler); + solution_transfer_m2(dof_handler); parallel::distributed::SolutionTransfer - solution_transfer_m3(dof_handler); + solution_transfer_m3(dof_handler); solution_transfer.prepare_for_coarsening_and_refinement(present_solution); solution_transfer_m1.prepare_for_coarsening_and_refinement(solution_m1); solution_transfer_m2.prepare_for_coarsening_and_refinement(solution_m2); @@ -1350,114 +1593,135 @@ template void GLSNavierStokesSolver::refine_mesh_uniform() { // Fix on the new mesh present_solution = tmp; - solution_m1 = tmp_m1; - solution_m2 = tmp_m2; - solution_m3 = tmp_m3; + solution_m1 = tmp_m1; + solution_m2 = tmp_m2; + solution_m3 = tmp_m3; } template -void GLSNavierStokesSolver::newton_iteration(const bool is_initial_step) { +void +GLSNavierStokesSolver::newton_iteration(const bool is_initial_step) +{ double current_res; double last_res; - bool first_step = is_initial_step; + bool first_step = is_initial_step; { unsigned int outer_iteration = 0; - last_res = 1.0; - current_res = 1.0; + last_res = 1.0; + current_res = 1.0; while ((first_step || (current_res > nsparam.nonLinearSolver.tolerance)) && - outer_iteration < nsparam.nonLinearSolver.maxIterations) { - - if (first_step) { - evaluation_point = present_solution; // local_evaluation_point; - assemble_system(first_step); - current_res = system_rhs.l2_norm(); - if (nsparam.nonLinearSolver.verbosity != nsparam.nonLinearSolver.quiet) - pcout << "Initial Newton iteration: " << outer_iteration - << " - Residual: " - << std::setprecision(nsparam.nonLinearSolver.display_precision) - << current_res << std::endl; - solve_system(first_step, nsparam.linearSolver.relative_residual, - nsparam.linearSolver.minimum_residual); - local_evaluation_point = newton_update; - nonzero_constraints.distribute(local_evaluation_point); - evaluation_point = local_evaluation_point; - present_solution = evaluation_point; - first_step = false; - assemble_rhs(first_step); - current_res = system_rhs.l2_norm(); - last_res = current_res; - } else { - evaluation_point = present_solution; - assemble_system(first_step); - if (outer_iteration == 0) { - current_res = system_rhs.l2_norm(); - last_res = current_res; - } - if (nsparam.nonLinearSolver.verbosity != nsparam.nonLinearSolver.quiet) - pcout << "Newton iteration: " << outer_iteration - << " - Residual: " << current_res << std::endl; - solve_system(first_step, nsparam.linearSolver.relative_residual, - nsparam.linearSolver.minimum_residual); - for (double alpha = 1.0; alpha > 1e-3; alpha *= 0.5) { - local_evaluation_point = present_solution; - local_evaluation_point.add(alpha, newton_update); - nonzero_constraints.distribute(local_evaluation_point); - evaluation_point = local_evaluation_point; - assemble_rhs(first_step); - current_res = system_rhs.l2_norm(); - if (nsparam.nonLinearSolver.verbosity != - nsparam.nonLinearSolver.quiet) - pcout << "\t\talpha = " << std::setw(6) << alpha << std::setw(0) - << " res = " - << std::setprecision( + outer_iteration < nsparam.nonLinearSolver.maxIterations) + { + if (first_step) + { + evaluation_point = present_solution; // local_evaluation_point; + assemble_system(first_step); + current_res = system_rhs.l2_norm(); + if (nsparam.nonLinearSolver.verbosity != + nsparam.nonLinearSolver.quiet) + pcout << "Initial Newton iteration: " << outer_iteration + << " - Residual: " + << std::setprecision( nsparam.nonLinearSolver.display_precision) - << current_res << std::endl; - if (current_res < 0.9 * last_res || - last_res < nsparam.nonLinearSolver.tolerance) - break; - } - { - present_solution = evaluation_point; - last_res = current_res; - } + << current_res << std::endl; + solve_system(first_step, + nsparam.linearSolver.relative_residual, + nsparam.linearSolver.minimum_residual); + local_evaluation_point = newton_update; + nonzero_constraints.distribute(local_evaluation_point); + evaluation_point = local_evaluation_point; + present_solution = evaluation_point; + first_step = false; + assemble_rhs(first_step); + current_res = system_rhs.l2_norm(); + last_res = current_res; + } + else + { + evaluation_point = present_solution; + assemble_system(first_step); + if (outer_iteration == 0) + { + current_res = system_rhs.l2_norm(); + last_res = current_res; + } + if (nsparam.nonLinearSolver.verbosity != + nsparam.nonLinearSolver.quiet) + pcout << "Newton iteration: " << outer_iteration + << " - Residual: " << current_res << std::endl; + solve_system(first_step, + nsparam.linearSolver.relative_residual, + nsparam.linearSolver.minimum_residual); + for (double alpha = 1.0; alpha > 1e-3; alpha *= 0.5) + { + local_evaluation_point = present_solution; + local_evaluation_point.add(alpha, newton_update); + nonzero_constraints.distribute(local_evaluation_point); + evaluation_point = local_evaluation_point; + assemble_rhs(first_step); + current_res = system_rhs.l2_norm(); + if (nsparam.nonLinearSolver.verbosity != + nsparam.nonLinearSolver.quiet) + pcout << "\t\talpha = " << std::setw(6) << alpha + << std::setw(0) << " res = " + << std::setprecision( + nsparam.nonLinearSolver.display_precision) + << current_res << std::endl; + if (current_res < 0.9 * last_res || + last_res < nsparam.nonLinearSolver.tolerance) + break; + } + { + present_solution = evaluation_point; + last_res = current_res; + } + } + ++outer_iteration; } - ++outer_iteration; - } } } -template void GLSNavierStokesSolver::postprocess() { +template +void +GLSNavierStokesSolver::postprocess() +{ if (simulationControl.isOutputIteration()) - write_output_results( - simulationControl.getOutputFolder(), simulationControl.getOuputName(), - simulationControl.getIter(), simulationControl.getTime()); - - if (nsparam.forcesParameters.calculate_force) { - if (simulationControl.getIter() % + write_output_results(simulationControl.getOutputFolder(), + simulationControl.getOuputName(), + simulationControl.getIter(), + simulationControl.getTime()); + + if (nsparam.forcesParameters.calculate_force) + { + if (simulationControl.getIter() % nsparam.forcesParameters.calculation_frequency == - 0) - calculate_forces(); - if (simulationControl.getIter() % + 0) + calculate_forces(); + if (simulationControl.getIter() % nsparam.forcesParameters.output_frequency == - 0) - write_output_forces(); - } + 0) + write_output_forces(); + } - if (nsparam.forcesParameters.calculate_torque) { - if (simulationControl.getIter() % + if (nsparam.forcesParameters.calculate_torque) + { + if (simulationControl.getIter() % nsparam.forcesParameters.calculation_frequency == - 0) - calculate_torques(); - if (simulationControl.getIter() % + 0) + calculate_torques(); + if (simulationControl.getIter() % nsparam.forcesParameters.output_frequency == - 0) - write_output_torques(); - } + 0) + write_output_torques(); + } } -template void GLSNavierStokesSolver::write_checkpoint() { +template +void +GLSNavierStokesSolver::write_checkpoint() +{ TimerOutput::Scope timer(computing_timer, "write_checkpoint"); - std::string prefix = nsparam.restartParameters.filename; + std::string prefix = nsparam.restartParameters.filename; if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) simulationControl.save(prefix); if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) @@ -1469,35 +1733,42 @@ template void GLSNavierStokesSolver::write_checkpoint() { sol_set_transfer.push_back(&solution_m2); sol_set_transfer.push_back(&solution_m3); parallel::distributed::SolutionTransfer - system_trans_vectors(dof_handler); + system_trans_vectors(dof_handler); system_trans_vectors.prepare_for_serialization(sol_set_transfer); std::string triangulationName = prefix + ".triangulation"; triangulation.save(prefix + ".triangulation"); } -template void GLSNavierStokesSolver::read_checkpoint() { +template +void +GLSNavierStokesSolver::read_checkpoint() +{ TimerOutput::Scope timer(computing_timer, "read_checkpoint"); - std::string prefix = nsparam.restartParameters.filename; + std::string prefix = nsparam.restartParameters.filename; simulationControl.read(prefix); pvdhandler.read(prefix); const std::string filename = prefix + ".triangulation"; - std::ifstream in(filename.c_str()); + std::ifstream in(filename.c_str()); if (!in) - AssertThrow( - false, - ExcMessage( - std::string("You are trying to restart a previous computation, " - "but the restart file <") + - filename + "> does not appear to exist!")); - - try { - triangulation.load(filename.c_str()); - } catch (...) { - AssertThrow(false, ExcMessage("Cannot open snapshot mesh file or read the " - "triangulation stored there.")); - } + AssertThrow(false, + ExcMessage( + std::string( + "You are trying to restart a previous computation, " + "but the restart file <") + + filename + "> does not appear to exist!")); + + try + { + triangulation.load(filename.c_str()); + } + catch (...) + { + AssertThrow(false, + ExcMessage("Cannot open snapshot mesh file or read the " + "triangulation stored there.")); + } setup_dofs(); std::vector x_system(4); @@ -1510,34 +1781,38 @@ template void GLSNavierStokesSolver::read_checkpoint() { x_system[2] = &(distributed_system_m2); x_system[3] = &(distributed_system_m3); parallel::distributed::SolutionTransfer - system_trans_vectors(dof_handler); + system_trans_vectors(dof_handler); system_trans_vectors.deserialize(x_system); present_solution = distributed_system; - solution_m1 = distributed_system_m1; - solution_m2 = distributed_system_m2; - solution_m3 = distributed_system_m3; + solution_m1 = distributed_system_m1; + solution_m2 = distributed_system_m2; + solution_m3 = distributed_system_m3; } template -void GLSNavierStokesSolver::write_output_results( - const std::string folder, const std::string solutionName, - const unsigned int iter, const double time) { - TimerOutput::Scope t(computing_timer, "output"); - const MappingQ mapping(degreeVelocity_, +void +GLSNavierStokesSolver::write_output_results(const std::string folder, + const std::string solutionName, + const unsigned int iter, + const double time) +{ + TimerOutput::Scope t(computing_timer, "output"); + const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - vorticity_postprocessor vorticity; + vorticity_postprocessor vorticity; qcriterion_postprocessor ob1; - std::vector solution_names(dim, "velocity"); + std::vector solution_names(dim, "velocity"); solution_names.push_back("pressure"); std::vector - data_component_interpretation( - dim, DataComponentInterpretation::component_is_part_of_vector); + data_component_interpretation( + dim, DataComponentInterpretation::component_is_part_of_vector); data_component_interpretation.push_back( - DataComponentInterpretation::component_is_scalar); + DataComponentInterpretation::component_is_scalar); DataOut data_out; data_out.attach_dof_handler(dof_handler); - data_out.add_data_vector(present_solution, solution_names, + data_out.add_data_vector(present_solution, + solution_names, DataOut::type_dof_data, data_component_interpretation); data_out.add_data_vector(present_solution, vorticity); @@ -1550,534 +1825,654 @@ void GLSNavierStokesSolver::write_output_results( data_out.build_patches(mapping, simulationControl.getSubdivision()); const std::string filename = - (folder + solutionName + "." + Utilities::int_to_string(iter, 4) + "." + - Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4)); + (folder + solutionName + "." + Utilities::int_to_string(iter, 4) + "." + + Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4)); std::ofstream output((filename + ".vtu").c_str()); data_out.write_vtu(output); - if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) { - std::vector filenames; - for (unsigned int i = 0; - i < Utilities::MPI::n_mpi_processes(mpi_communicator); ++i) - filenames.push_back(solutionName + "." + - Utilities::int_to_string(iter, 4) + "." + - Utilities::int_to_string(i, 4) + ".vtu"); - - std::string pvtu_filename = + if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) + { + std::vector filenames; + for (unsigned int i = 0; + i < Utilities::MPI::n_mpi_processes(mpi_communicator); + ++i) + filenames.push_back(solutionName + "." + + Utilities::int_to_string(iter, 4) + "." + + Utilities::int_to_string(i, 4) + ".vtu"); + + std::string pvtu_filename = (solutionName + "." + Utilities::int_to_string(iter, 4) + ".pvtu"); - std::ofstream master_output((folder + pvtu_filename).c_str()); + std::ofstream master_output((folder + pvtu_filename).c_str()); - data_out.write_pvtu_record(master_output, filenames); + data_out.write_pvtu_record(master_output, filenames); - const std::string pvdPrefix = (folder + solutionName); - pvdhandler.append(time, pvtu_filename); - std::ofstream pvd_output(pvdPrefix + ".pvd"); - DataOutBase::write_pvd_record(pvd_output, pvdhandler.times_and_names_); - } + const std::string pvdPrefix = (folder + solutionName); + pvdhandler.append(time, pvtu_filename); + std::ofstream pvd_output(pvdPrefix + ".pvd"); + DataOutBase::write_pvd_record(pvd_output, pvdhandler.times_and_names_); + } } -template void GLSNavierStokesSolver::write_output_forces() { +template +void +GLSNavierStokesSolver::write_output_forces() +{ TimerOutput::Scope t(computing_timer, "output_forces"); for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - std::string filename = nsparam.forcesParameters.force_output_name + "." + - Utilities::int_to_string(boundary_id, 2) + ".dat"; - std::ofstream output(filename.c_str()); - - forces_tables[boundary_id].write_text(output); - } + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + std::string filename = nsparam.forcesParameters.force_output_name + "." + + Utilities::int_to_string(boundary_id, 2) + ".dat"; + std::ofstream output(filename.c_str()); + + forces_tables[boundary_id].write_text(output); + } } -template void GLSNavierStokesSolver::write_output_torques() { +template +void +GLSNavierStokesSolver::write_output_torques() +{ TimerOutput::Scope t(computing_timer, "output_torques"); for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - std::string filename = nsparam.forcesParameters.torque_output_name + "." + - Utilities::int_to_string(boundary_id, 2) + ".dat"; - std::ofstream output(filename.c_str()); - - torques_tables[boundary_id].write_text(output); - } + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + std::string filename = nsparam.forcesParameters.torque_output_name + "." + + Utilities::int_to_string(boundary_id, 2) + ".dat"; + std::ofstream output(filename.c_str()); + + torques_tables[boundary_id].write_text(output); + } } // Find the l2 norm of the error between the finite element sol'n and the exact // sol'n -template double GLSNavierStokesSolver::calculate_L2_error() { +template +double +GLSNavierStokesSolver::calculate_L2_error() +{ TimerOutput::Scope t(computing_timer, "error"); - QGauss quadrature_formula(degreeQuadrature_ + 1); + QGauss quadrature_formula(degreeQuadrature_ + 1); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_gradients | - update_quadrature_points | update_JxW_values); + update_quadrature_points | update_JxW_values); const FEValuesExtractors::Vector velocities(0); const FEValuesExtractors::Scalar pressure(dim); const unsigned int dofs_per_cell = - fe.dofs_per_cell; // This gives you dofs per cell + fe.dofs_per_cell; // This gives you dofs per cell std::vector local_dof_indices( - dofs_per_cell); // Local connectivity + dofs_per_cell); // Local connectivity const unsigned int n_q_points = quadrature_formula.size(); std::vector> q_exactSol(n_q_points, Vector(dim + 1)); std::vector> local_velocity_values(n_q_points); - std::vector local_pressure_values(n_q_points); + std::vector local_pressure_values(n_q_points); double l2errorU = 0.; // loop over elements typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - fe_values.reinit(cell); - fe_values[velocities].get_function_values(present_solution, - local_velocity_values); - fe_values[pressure].get_function_values(present_solution, - local_pressure_values); - - // Retrieve the effective "connectivity matrix" for this element - cell->get_dof_indices(local_dof_indices); - - // Get the exact solution at all gauss points - exact_solution->vector_value_list(fe_values.get_quadrature_points(), - q_exactSol); - - for (unsigned int q = 0; q < n_q_points; q++) { - // Find the values of x and u_h (the finite element solution) at the - // quadrature points - double ux_sim = local_velocity_values[q][0]; - double ux_exact = q_exactSol[q][0]; - - double uy_sim = local_velocity_values[q][1]; - double uy_exact = q_exactSol[q][1]; - - l2errorU += - (ux_sim - ux_exact) * (ux_sim - ux_exact) * fe_values.JxW(q); - l2errorU += - (uy_sim - uy_exact) * (uy_sim - uy_exact) * fe_values.JxW(q); - - if (dim == 3) { - double uz_sim = local_velocity_values[q][2]; - double uz_exact = q_exactSol[q][2]; - l2errorU += - (uz_sim - uz_exact) * (uz_sim - uz_exact) * fe_values.JxW(q); + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + fe_values.reinit(cell); + fe_values[velocities].get_function_values(present_solution, + local_velocity_values); + fe_values[pressure].get_function_values(present_solution, + local_pressure_values); + + // Retrieve the effective "connectivity matrix" for this element + cell->get_dof_indices(local_dof_indices); + + // Get the exact solution at all gauss points + exact_solution->vector_value_list(fe_values.get_quadrature_points(), + q_exactSol); + + for (unsigned int q = 0; q < n_q_points; q++) + { + // Find the values of x and u_h (the finite element solution) at + // the quadrature points + double ux_sim = local_velocity_values[q][0]; + double ux_exact = q_exactSol[q][0]; + + double uy_sim = local_velocity_values[q][1]; + double uy_exact = q_exactSol[q][1]; + + l2errorU += + (ux_sim - ux_exact) * (ux_sim - ux_exact) * fe_values.JxW(q); + l2errorU += + (uy_sim - uy_exact) * (uy_sim - uy_exact) * fe_values.JxW(q); + + if (dim == 3) + { + double uz_sim = local_velocity_values[q][2]; + double uz_exact = q_exactSol[q][2]; + l2errorU += (uz_sim - uz_exact) * (uz_sim - uz_exact) * + fe_values.JxW(q); + } + } } - } } - } l2errorU = Utilities::MPI::sum(l2errorU, mpi_communicator); return std::sqrt(l2errorU); } // kinetic energy calculation -template double GLSNavierStokesSolver::calculate_average_KE() { +template +double +GLSNavierStokesSolver::calculate_average_KE() +{ TimerOutput::Scope t(computing_timer, "KE"); - QGauss quadrature_formula(degreeQuadrature_ + 1); + QGauss quadrature_formula(degreeQuadrature_ + 1); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_gradients | - update_quadrature_points | update_JxW_values); + update_quadrature_points | update_JxW_values); const FEValuesExtractors::Vector velocities(0); - const unsigned int n_q_points = quadrature_formula.size(); + const unsigned int n_q_points = quadrature_formula.size(); std::vector> local_velocity_values(n_q_points); - double KEU = 0.0; + double KEU = 0.0; // loop over elements typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - fe_values.reinit(cell); - fe_values[velocities].get_function_values(present_solution, - local_velocity_values); - - for (unsigned int q = 0; q < n_q_points; q++) { - // Find the values of x and u_h (the finite element solution) at the - // quadrature points - double ux_sim = local_velocity_values[q][0]; - double uy_sim = local_velocity_values[q][1]; - - if (dim == 2) { - KEU += 0.5 * ((ux_sim) * (ux_sim)*fe_values.JxW(q)) * - (1 / globalVolume_); - KEU += 0.5 * ((uy_sim) * (uy_sim)*fe_values.JxW(q)) * - (1 / globalVolume_); - } else { - double uz_sim = local_velocity_values[q][2]; - KEU += 0.5 * ((ux_sim) * (ux_sim)*fe_values.JxW(q)) * - (1 / globalVolume_); - KEU += 0.5 * ((uy_sim) * (uy_sim)*fe_values.JxW(q)) * - (1 / globalVolume_); - KEU += 0.5 * ((uz_sim) * (uz_sim)*fe_values.JxW(q)) * - (1 / globalVolume_); + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + fe_values.reinit(cell); + fe_values[velocities].get_function_values(present_solution, + local_velocity_values); + + for (unsigned int q = 0; q < n_q_points; q++) + { + // Find the values of x and u_h (the finite element solution) at + // the quadrature points + double ux_sim = local_velocity_values[q][0]; + double uy_sim = local_velocity_values[q][1]; + + if (dim == 2) + { + KEU += 0.5 * ((ux_sim) * (ux_sim)*fe_values.JxW(q)) * + (1 / globalVolume_); + KEU += 0.5 * ((uy_sim) * (uy_sim)*fe_values.JxW(q)) * + (1 / globalVolume_); + } + else + { + double uz_sim = local_velocity_values[q][2]; + KEU += 0.5 * ((ux_sim) * (ux_sim)*fe_values.JxW(q)) * + (1 / globalVolume_); + KEU += 0.5 * ((uy_sim) * (uy_sim)*fe_values.JxW(q)) * + (1 / globalVolume_); + KEU += 0.5 * ((uz_sim) * (uz_sim)*fe_values.JxW(q)) * + (1 / globalVolume_); + } + } } - } } - } KEU = Utilities::MPI::sum(KEU, mpi_communicator); return (KEU); } // enstrophy calculation template -double GLSNavierStokesSolver::calculate_average_enstrophy() { +double +GLSNavierStokesSolver::calculate_average_enstrophy() +{ TimerOutput::Scope t(computing_timer, "Entrosphy"); - QGauss quadrature_formula(degreeQuadrature_ + 1); + QGauss quadrature_formula(degreeQuadrature_ + 1); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - FEValues fe_values(mapping, fe, quadrature_formula, + FEValues fe_values(mapping, + fe, + quadrature_formula, update_values | update_gradients | - update_quadrature_points | update_JxW_values); + update_quadrature_points | update_JxW_values); const FEValuesExtractors::Vector velocities(0); const unsigned int n_q_points = quadrature_formula.size(); std::vector> present_velocity_gradients(n_q_points); - double en = 0.0; + double en = 0.0; // loop over elements typename DoFHandler::active_cell_iterator cell = - dof_handler.begin_active(), + dof_handler.begin_active(), endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - fe_values.reinit(cell); - - fe_values[velocities].get_function_gradients(evaluation_point, - present_velocity_gradients); - - for (unsigned int q = 0; q < n_q_points; q++) { - // en += - // 0.5*(present_velocity_curl[q]*present_velocity_curl[q])*fe_values.JxW(q) - // / globalVolume_; - - // Find the values of gradient of ux and uy (the finite element - // solution) at the quadrature points - double ux_y = present_velocity_gradients[q][0][1]; - double uy_x = present_velocity_gradients[q][1][0]; - - if (dim == 2) { - en += 0.5 * (uy_x - ux_y) * (uy_x - ux_y) * fe_values.JxW(q) * - (1 / globalVolume_); - } else { - double uz_y = present_velocity_gradients[q][2][1]; - double uy_z = present_velocity_gradients[q][1][2]; - double ux_z = present_velocity_gradients[q][0][2]; - double uz_x = present_velocity_gradients[q][2][0]; - en += 0.5 * (uz_y - uy_z) * (uz_y - uy_z) * fe_values.JxW(q) * - (1 / globalVolume_); - en += 0.5 * (ux_z - uz_x) * (ux_z - uz_x) * fe_values.JxW(q) * - (1 / globalVolume_); - en += 0.5 * (uy_x - ux_y) * (uy_x - ux_y) * fe_values.JxW(q) * - (1 / globalVolume_); + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + fe_values.reinit(cell); + + fe_values[velocities].get_function_gradients( + evaluation_point, present_velocity_gradients); + + for (unsigned int q = 0; q < n_q_points; q++) + { + // en += + // 0.5*(present_velocity_curl[q]*present_velocity_curl[q])*fe_values.JxW(q) + // / globalVolume_; + + // Find the values of gradient of ux and uy (the finite element + // solution) at the quadrature points + double ux_y = present_velocity_gradients[q][0][1]; + double uy_x = present_velocity_gradients[q][1][0]; + + if (dim == 2) + { + en += 0.5 * (uy_x - ux_y) * (uy_x - ux_y) * fe_values.JxW(q) * + (1 / globalVolume_); + } + else + { + double uz_y = present_velocity_gradients[q][2][1]; + double uy_z = present_velocity_gradients[q][1][2]; + double ux_z = present_velocity_gradients[q][0][2]; + double uz_x = present_velocity_gradients[q][2][0]; + en += 0.5 * (uz_y - uy_z) * (uz_y - uy_z) * fe_values.JxW(q) * + (1 / globalVolume_); + en += 0.5 * (ux_z - uz_x) * (ux_z - uz_x) * fe_values.JxW(q) * + (1 / globalVolume_); + en += 0.5 * (uy_x - ux_y) * (uy_x - ux_y) * fe_values.JxW(q) * + (1 / globalVolume_); + } + } } - } } - } en = Utilities::MPI::sum(en, mpi_communicator); return (en); } // This is a primitive first implementation that could be greatly improved by // doing a single pass instead of N boundary passes -template void GLSNavierStokesSolver::calculate_forces() { +template +void +GLSNavierStokesSolver::calculate_forces() +{ TimerOutput::Scope t(computing_timer, "calculate_forces"); - double viscosity = this->nsparam.physicalProperties.viscosity; + double viscosity = this->nsparam.physicalProperties.viscosity; - QGauss face_quadrature_formula(degreeQuadrature_ + 1); + QGauss face_quadrature_formula(degreeQuadrature_ + 1); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - const int n_q_points = face_quadrature_formula.size(); + const int n_q_points = face_quadrature_formula.size(); const FEValuesExtractors::Vector velocities(0); const FEValuesExtractors::Scalar pressure(dim); - std::vector pressure_values(n_q_points); - std::vector> velocity_gradients(n_q_points); - Tensor<1, dim> normal_vector; - Tensor<2, dim> fluid_stress; - Tensor<2, dim> fluid_pressure; - Tensor<1, dim> force; - - FEFaceValues fe_face_values(mapping, fe, face_quadrature_formula, + std::vector pressure_values(n_q_points); + std::vector> velocity_gradients(n_q_points); + Tensor<1, dim> normal_vector; + Tensor<2, dim> fluid_stress; + Tensor<2, dim> fluid_pressure; + Tensor<1, dim> force; + + FEFaceValues fe_face_values(mapping, + fe, + face_quadrature_formula, update_values | update_quadrature_points | - update_gradients | update_JxW_values | - update_normal_vectors); + update_gradients | update_JxW_values | + update_normal_vectors); for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - force = 0; - typename DoFHandler::active_cell_iterator cell = dof_handler + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + force = 0; + typename DoFHandler::active_cell_iterator cell = dof_handler .begin_active(), - endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - for (unsigned int face = 0; face < GeometryInfo::faces_per_cell; - face++) { - if (cell->face(face)->at_boundary()) { - fe_face_values.reinit(cell, face); - if (cell->face(face)->boundary_id() == boundary_id) { - std::vector> q_points = - fe_face_values.get_quadrature_points(); - fe_face_values[velocities].get_function_gradients( - present_solution, velocity_gradients); - fe_face_values[pressure].get_function_values(present_solution, - pressure_values); - for (int q = 0; q < n_q_points; q++) { - normal_vector = -fe_face_values.normal_vector(q); - for (int d = 0; d < dim; ++d) { - fluid_pressure[d][d] = pressure_values[q]; + endc = dof_handler.end(); + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + for (unsigned int face = 0; + face < GeometryInfo::faces_per_cell; + face++) + { + if (cell->face(face)->at_boundary()) + { + fe_face_values.reinit(cell, face); + if (cell->face(face)->boundary_id() == boundary_id) + { + std::vector> q_points = + fe_face_values.get_quadrature_points(); + fe_face_values[velocities].get_function_gradients( + present_solution, velocity_gradients); + fe_face_values[pressure].get_function_values( + present_solution, pressure_values); + for (int q = 0; q < n_q_points; q++) + { + normal_vector = -fe_face_values.normal_vector(q); + for (int d = 0; d < dim; ++d) + { + fluid_pressure[d][d] = pressure_values[q]; + } + fluid_stress = + viscosity * (velocity_gradients[q] + + transpose(velocity_gradients[q])) - + fluid_pressure; + force += fluid_stress * normal_vector * + fe_face_values.JxW(q); + } + } + } } - fluid_stress = viscosity * (velocity_gradients[q] + - transpose(velocity_gradients[q])) - - fluid_pressure; - force += fluid_stress * normal_vector * fe_face_values.JxW(q); - } } - } } - } + forces_[boundary_id] = Utilities::MPI::sum(force, mpi_communicator); } - forces_[boundary_id] = Utilities::MPI::sum(force, mpi_communicator); - } if (nsparam.forcesParameters.verbosity == Parameters::Forces::verbose && - this_mpi_process == 0) { - std::cout << std::endl; - TableHandler table; - - for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - table.add_value("Boundary ID", boundary_id); - table.add_value("f_x", forces_[boundary_id][0]); - table.add_value("f_y", forces_[boundary_id][1]); - table.set_precision("f_x", nsparam.forcesParameters.display_precision); - table.set_precision("f_y", nsparam.forcesParameters.display_precision); - if (dim == 3) { - table.add_value("f_z", forces_[boundary_id][2]); - table.set_precision("f_z", nsparam.forcesParameters.display_precision); - } + this_mpi_process == 0) + { + std::cout << std::endl; + TableHandler table; + + for (unsigned int boundary_id = 0; + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + table.add_value("Boundary ID", boundary_id); + table.add_value("f_x", forces_[boundary_id][0]); + table.add_value("f_y", forces_[boundary_id][1]); + table.set_precision("f_x", + nsparam.forcesParameters.display_precision); + table.set_precision("f_y", + nsparam.forcesParameters.display_precision); + if (dim == 3) + { + table.add_value("f_z", forces_[boundary_id][2]); + table.set_precision("f_z", + nsparam.forcesParameters.display_precision); + } + } + std::cout << "+------------------------------------------+" << std::endl; + std::cout << "| Force summary |" << std::endl; + std::cout << "+------------------------------------------+" << std::endl; + table.write_text(std::cout); } - std::cout << "+------------------------------------------+" << std::endl; - std::cout << "| Force summary |" << std::endl; - std::cout << "+------------------------------------------+" << std::endl; - table.write_text(std::cout); - } for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - forces_tables[boundary_id].add_value("time", simulationControl.getTime()); - forces_tables[boundary_id].add_value("f_x", forces_[boundary_id][0]); - forces_tables[boundary_id].add_value("f_y", forces_[boundary_id][1]); - if (dim == 3) - forces_tables[boundary_id].add_value("f_z", forces_[boundary_id][2]); - else - forces_tables[boundary_id].add_value("f_z", 0.); - - // Precision - forces_tables[boundary_id].set_precision( + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + forces_tables[boundary_id].add_value("time", simulationControl.getTime()); + forces_tables[boundary_id].add_value("f_x", forces_[boundary_id][0]); + forces_tables[boundary_id].add_value("f_y", forces_[boundary_id][1]); + if (dim == 3) + forces_tables[boundary_id].add_value("f_z", forces_[boundary_id][2]); + else + forces_tables[boundary_id].add_value("f_z", 0.); + + // Precision + forces_tables[boundary_id].set_precision( "f_x", nsparam.forcesParameters.output_precision); - forces_tables[boundary_id].set_precision( + forces_tables[boundary_id].set_precision( "f_y", nsparam.forcesParameters.output_precision); - forces_tables[boundary_id].set_precision( + forces_tables[boundary_id].set_precision( "f_z", nsparam.forcesParameters.output_precision); - forces_tables[boundary_id].set_precision( + forces_tables[boundary_id].set_precision( "time", nsparam.forcesParameters.output_precision); - } + } } -template void GLSNavierStokesSolver::calculate_torques() { +template +void +GLSNavierStokesSolver::calculate_torques() +{ TimerOutput::Scope t(computing_timer, "calculate_torques"); - double viscosity = this->nsparam.physicalProperties.viscosity; + double viscosity = this->nsparam.physicalProperties.viscosity; - QGauss face_quadrature_formula(degreeQuadrature_ + 1); + QGauss face_quadrature_formula(degreeQuadrature_ + 1); const MappingQ mapping(degreeVelocity_, nsparam.femParameters.qmapping_all); - const int n_q_points = face_quadrature_formula.size(); + const int n_q_points = face_quadrature_formula.size(); const FEValuesExtractors::Vector velocities(0); const FEValuesExtractors::Scalar pressure(dim); - std::vector pressure_values(n_q_points); - std::vector> velocity_gradients(n_q_points); - Tensor<1, dim> normal_vector; - Tensor<2, dim> fluid_stress; - Tensor<2, dim> fluid_pressure; + std::vector pressure_values(n_q_points); + std::vector> velocity_gradients(n_q_points); + Tensor<1, dim> normal_vector; + Tensor<2, dim> fluid_stress; + Tensor<2, dim> fluid_pressure; Tensor<1, dim> force; Tensor<1, dim> distance; // torque tensor had to be considered in 3D at all time... Tensor<1, 3> torque; - FEFaceValues fe_face_values(mapping, fe, face_quadrature_formula, + FEFaceValues fe_face_values(mapping, + fe, + face_quadrature_formula, update_values | update_quadrature_points | - update_gradients | update_JxW_values | - update_normal_vectors); + update_gradients | update_JxW_values | + update_normal_vectors); for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - torque = 0; - Point center_of_rotation = + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + torque = 0; + Point center_of_rotation = nsparam.boundaryConditions.bcFunctions[boundary_id].cor; - typename DoFHandler::active_cell_iterator cell = dof_handler + typename DoFHandler::active_cell_iterator cell = dof_handler .begin_active(), - endc = dof_handler.end(); - for (; cell != endc; ++cell) { - if (cell->is_locally_owned()) { - for (unsigned int face = 0; face < GeometryInfo::faces_per_cell; - face++) { - - if (cell->face(face)->at_boundary()) { - fe_face_values.reinit(cell, face); - if (cell->face(face)->boundary_id() == boundary_id) { - std::vector> q_points = - fe_face_values.get_quadrature_points(); - fe_face_values[velocities].get_function_gradients( - present_solution, velocity_gradients); - fe_face_values[pressure].get_function_values(present_solution, - pressure_values); - for (int q = 0; q < n_q_points; q++) { - normal_vector = -fe_face_values.normal_vector(q); - for (int d = 0; d < dim; ++d) { - fluid_pressure[d][d] = pressure_values[q]; - } - fluid_stress = viscosity * (velocity_gradients[q] + - transpose(velocity_gradients[q])) - - fluid_pressure; - force = fluid_stress * normal_vector * fe_face_values.JxW(q); - - distance = q_points[q] - center_of_rotation; - if (dim == 2) { - torque[0] = 0.; - torque[1] = 0.; - torque[2] += distance[0] * force[1] - distance[1] * force[0]; - } else if (dim == 3) { - torque[0] += distance[1] * force[2] - distance[2] * force[1]; - torque[1] += distance[2] * force[0] - distance[0] * force[2]; - torque[2] += distance[0] * force[1] - distance[1] * force[0]; + endc = dof_handler.end(); + for (; cell != endc; ++cell) + { + if (cell->is_locally_owned()) + { + for (unsigned int face = 0; + face < GeometryInfo::faces_per_cell; + face++) + { + if (cell->face(face)->at_boundary()) + { + fe_face_values.reinit(cell, face); + if (cell->face(face)->boundary_id() == boundary_id) + { + std::vector> q_points = + fe_face_values.get_quadrature_points(); + fe_face_values[velocities].get_function_gradients( + present_solution, velocity_gradients); + fe_face_values[pressure].get_function_values( + present_solution, pressure_values); + for (int q = 0; q < n_q_points; q++) + { + normal_vector = -fe_face_values.normal_vector(q); + for (int d = 0; d < dim; ++d) + { + fluid_pressure[d][d] = pressure_values[q]; + } + fluid_stress = + viscosity * (velocity_gradients[q] + + transpose(velocity_gradients[q])) - + fluid_pressure; + force = fluid_stress * normal_vector * + fe_face_values.JxW(q); + + distance = q_points[q] - center_of_rotation; + if (dim == 2) + { + torque[0] = 0.; + torque[1] = 0.; + torque[2] += distance[0] * force[1] - + distance[1] * force[0]; + } + else if (dim == 3) + { + torque[0] += distance[1] * force[2] - + distance[2] * force[1]; + torque[1] += distance[2] * force[0] - + distance[0] * force[2]; + torque[2] += distance[0] * force[1] - + distance[1] * force[0]; + } + } + } + } } - } } - } } - } + torques_[boundary_id] = Utilities::MPI::sum(torque, mpi_communicator); } - torques_[boundary_id] = Utilities::MPI::sum(torque, mpi_communicator); - } if (nsparam.forcesParameters.verbosity == nsparam.forcesParameters.verbose && - this_mpi_process == 0) { - pcout << std::endl; - TableHandler table; - - for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - table.add_value("Boundary ID", boundary_id); - table.add_value("T_x", torques_[boundary_id][0]); - table.add_value("T_y", torques_[boundary_id][1]); - table.set_precision("T_x", nsparam.forcesParameters.display_precision); - table.set_precision("T_y", nsparam.forcesParameters.display_precision); - table.add_value("T_z", torques_[boundary_id][2]); - table.set_precision("T_z", nsparam.forcesParameters.display_precision); - } + this_mpi_process == 0) + { + pcout << std::endl; + TableHandler table; + + for (unsigned int boundary_id = 0; + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + table.add_value("Boundary ID", boundary_id); + table.add_value("T_x", torques_[boundary_id][0]); + table.add_value("T_y", torques_[boundary_id][1]); + table.set_precision("T_x", + nsparam.forcesParameters.display_precision); + table.set_precision("T_y", + nsparam.forcesParameters.display_precision); + table.add_value("T_z", torques_[boundary_id][2]); + table.set_precision("T_z", + nsparam.forcesParameters.display_precision); + } - std::cout << "+------------------------------------------+" << std::endl; - std::cout << "| Torque summary |" << std::endl; - std::cout << "+------------------------------------------+" << std::endl; - table.write_text(std::cout); - } + std::cout << "+------------------------------------------+" << std::endl; + std::cout << "| Torque summary |" << std::endl; + std::cout << "+------------------------------------------+" << std::endl; + table.write_text(std::cout); + } for (unsigned int boundary_id = 0; - boundary_id < nsparam.boundaryConditions.size; ++boundary_id) { - torques_tables[boundary_id].add_value("time", simulationControl.getTime()); - torques_tables[boundary_id].add_value("T_x", torques_[boundary_id][0]); - torques_tables[boundary_id].add_value("T_y", torques_[boundary_id][1]); - torques_tables[boundary_id].add_value("T_z", torques_[boundary_id][2]); - - // Precision - torques_tables[boundary_id].set_precision( + boundary_id < nsparam.boundaryConditions.size; + ++boundary_id) + { + torques_tables[boundary_id].add_value("time", + simulationControl.getTime()); + torques_tables[boundary_id].add_value("T_x", torques_[boundary_id][0]); + torques_tables[boundary_id].add_value("T_y", torques_[boundary_id][1]); + torques_tables[boundary_id].add_value("T_z", torques_[boundary_id][2]); + + // Precision + torques_tables[boundary_id].set_precision( "T_x", nsparam.forcesParameters.output_precision); - torques_tables[boundary_id].set_precision( + torques_tables[boundary_id].set_precision( "T_y", nsparam.forcesParameters.output_precision); - torques_tables[boundary_id].set_precision( + torques_tables[boundary_id].set_precision( "T_z", nsparam.forcesParameters.output_precision); - torques_tables[boundary_id].set_precision( + torques_tables[boundary_id].set_precision( "time", nsparam.forcesParameters.output_precision); - } + } } /* * Reads a CFD Mesh from a GMSH file or generates a pre-defined primitive */ -template void GLSNavierStokesSolver::read_mesh() { +template +void +GLSNavierStokesSolver::read_mesh() +{ // GMSH input - if (nsparam.mesh.type == Parameters::Mesh::gmsh) { - GridIn grid_in; - grid_in.attach_triangulation(this->triangulation); - std::ifstream input_file(this->nsparam.mesh.fileName); - grid_in.read_msh(input_file); - this->set_periodicity(); - } + if (nsparam.mesh.type == Parameters::Mesh::gmsh) + { + GridIn grid_in; + grid_in.attach_triangulation(this->triangulation); + std::ifstream input_file(this->nsparam.mesh.fileName); + grid_in.read_msh(input_file); + this->set_periodicity(); + } // Primitive input - else if (nsparam.mesh.type == Parameters::Mesh::primitive) { - const int initialSize = this->nsparam.mesh.initialRefinement; - - if (nsparam.mesh.primitiveType == Parameters::Mesh::hyper_cube) { - GridGenerator::hyper_cube(this->triangulation, this->nsparam.mesh.hc_left, - this->nsparam.mesh.hc_right, - this->nsparam.mesh.colorize); - } else if (nsparam.mesh.primitiveType == Parameters::Mesh::hyper_shell) { - Point circleCenter; - if (dim == 2) - circleCenter = Point(0, 0); + else if (nsparam.mesh.type == Parameters::Mesh::primitive) + { + const int initialSize = this->nsparam.mesh.initialRefinement; - if (dim == 3) - circleCenter = Point(0, 0, 0); - - GridGenerator::hyper_shell( - this->triangulation, circleCenter, this->nsparam.mesh.hs_inner_radius, - this->nsparam.mesh.hs_outer_radius, 4, this->nsparam.mesh.colorize); - - static const SphericalManifold manifold_description(circleCenter); - this->triangulation.set_manifold(0, manifold_description); - this->triangulation.set_all_manifold_ids_on_boundary(0); - } else { - throw std::runtime_error( - "Unsupported primitive type - mesh will not be created"); + if (nsparam.mesh.primitiveType == Parameters::Mesh::hyper_cube) + { + GridGenerator::hyper_cube(this->triangulation, + this->nsparam.mesh.hc_left, + this->nsparam.mesh.hc_right, + this->nsparam.mesh.colorize); + } + else if (nsparam.mesh.primitiveType == Parameters::Mesh::hyper_shell) + { + Point circleCenter; + if (dim == 2) + circleCenter = Point(0, 0); + + if (dim == 3) + circleCenter = Point(0, 0, 0); + + GridGenerator::hyper_shell(this->triangulation, + circleCenter, + this->nsparam.mesh.hs_inner_radius, + this->nsparam.mesh.hs_outer_radius, + 4, + this->nsparam.mesh.colorize); + + static const SphericalManifold manifold_description( + circleCenter); + this->triangulation.set_manifold(0, manifold_description); + this->triangulation.set_all_manifold_ids_on_boundary(0); + } + else + { + throw std::runtime_error( + "Unsupported primitive type - mesh will not be created"); + } + this->set_periodicity(); + this->triangulation.refine_global(initialSize); } - this->set_periodicity(); - this->triangulation.refine_global(initialSize); - } else + else throw std::runtime_error( - "Unsupported mesh type - mesh will not be created"); + "Unsupported mesh type - mesh will not be created"); } /* * Generic CFD Solver application that is generally appropriate for most CFD * problems */ -template void GLSNavierStokesSolver::solve() { +template +void +GLSNavierStokesSolver::solve() +{ this->read_mesh(); this->setup_dofs(); this->forcing_function = new NoForce; this->set_initial_condition(this->nsparam.initialCondition->type, this->nsparam.restartParameters.restart); - while (this->simulationControl.integrate()) { - this->refine_mesh(); - this->iterate(this->simulationControl.firstIter()); - this->postprocess(); - this->finish_time_step(); - } + while (this->simulationControl.integrate()) + { + this->refine_mesh(); + this->iterate(this->simulationControl.firstIter()); + this->postprocess(); + this->finish_time_step(); + } } #endif diff --git a/src/initialconditions.cc b/src/initialconditions.cc index 3f47d36f31..a38a4a346f 100644 --- a/src/initialconditions.cc +++ b/src/initialconditions.cc @@ -19,7 +19,8 @@ #include "initialconditions.h" -namespace Parameters { -extern template class InitialConditions<2>; -extern template class InitialConditions<3>; +namespace Parameters +{ + extern template class InitialConditions<2>; + extern template class InitialConditions<3>; } // namespace Parameters diff --git a/src/initialconditions.h b/src/initialconditions.h index 6c950f28f8..30720bbd6e 100644 --- a/src/initialconditions.h +++ b/src/initialconditions.h @@ -28,68 +28,87 @@ using namespace dealii; -namespace Parameters { - -// Type of initial conditions -enum InitialConditionType { none, L2projection, viscous, nodal }; - -template class InitialConditions { -public: - InitialConditions() : uvwp(dim + 1) {} +namespace Parameters +{ + // Type of initial conditions + enum InitialConditionType + { + none, + L2projection, + viscous, + nodal + }; + + template + class InitialConditions + { + public: + InitialConditions() + : uvwp(dim + 1) + {} - InitialConditionType type; + InitialConditionType type; - // Velocity components - Functions::ParsedFunction uvwp; + // Velocity components + Functions::ParsedFunction uvwp; - // Artificial viscosity - double viscosity; + // Artificial viscosity + double viscosity; - void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; + void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; -template -void InitialConditions::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("initial conditions"); + template + void + InitialConditions::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("type", "nodal", - Patterns::Selection("L2projection|viscous|nodal"), - "Type of initial condition" - "Choices are ."); - prm.enter_subsection("uvwp"); - uvwp.declare_parameters(prm, dim); - if (dim == 2) - prm.set("Function expression", "0; 0; 0"); - if (dim == 3) - prm.set("Function expression", "0; 0; 0; 0"); + prm.enter_subsection("initial conditions"); + { + prm.declare_entry("type", + "nodal", + Patterns::Selection("L2projection|viscous|nodal"), + "Type of initial condition" + "Choices are ."); + prm.enter_subsection("uvwp"); + uvwp.declare_parameters(prm, dim); + if (dim == 2) + prm.set("Function expression", "0; 0; 0"); + if (dim == 3) + prm.set("Function expression", "0; 0; 0; 0"); + prm.leave_subsection(); + + prm.declare_entry("viscosity", + "1", + Patterns::Double(), + "viscosity for viscous initial conditions"); + } prm.leave_subsection(); - - prm.declare_entry("viscosity", "1", Patterns::Double(), - "viscosity for viscous initial conditions"); } - prm.leave_subsection(); -} -template -void InitialConditions::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("initial conditions"); + template + void + InitialConditions::parse_parameters(ParameterHandler &prm) { - const std::string op = prm.get("type"); - if (op == "L2projection") - type = L2projection; - else if (op == "viscous") - type = viscous; - else if (op == "nodal") - type = nodal; - - viscosity = prm.get_double("viscosity"); - prm.enter_subsection("uvwp"); - uvwp.parse_parameters(prm); + prm.enter_subsection("initial conditions"); + { + const std::string op = prm.get("type"); + if (op == "L2projection") + type = L2projection; + else if (op == "viscous") + type = viscous; + else if (op == "nodal") + type = nodal; + + viscosity = prm.get_double("viscosity"); + prm.enter_subsection("uvwp"); + uvwp.parse_parameters(prm); + prm.leave_subsection(); + } prm.leave_subsection(); } - prm.leave_subsection(); -} } // namespace Parameters #endif diff --git a/src/navierstokessolverparameters.h b/src/navierstokessolverparameters.h index 2b7f23576a..d2de2b1db6 100644 --- a/src/navierstokessolverparameters.h +++ b/src/navierstokessolverparameters.h @@ -27,24 +27,28 @@ #include "parameters.h" #include "simulationcontrol.h" -template class NavierStokesSolverParameters { +template +class NavierStokesSolverParameters +{ public: - Parameters::Testing test; - Parameters::LinearSolver linearSolver; - Parameters::NonLinearSolver nonLinearSolver; - Parameters::MeshAdaptation meshAdaptation; - Parameters::Mesh mesh; - Parameters::PhysicalProperties physicalProperties; - Parameters::Timer timer; - Parameters::FEM femParameters; - Parameters::Forces forcesParameters; - Parameters::AnalyticalSolution analyticalSolution; - Parameters::Restart restartParameters; + Parameters::Testing test; + Parameters::LinearSolver linearSolver; + Parameters::NonLinearSolver nonLinearSolver; + Parameters::MeshAdaptation meshAdaptation; + Parameters::Mesh mesh; + Parameters::PhysicalProperties physicalProperties; + Parameters::Timer timer; + Parameters::FEM femParameters; + Parameters::Forces forcesParameters; + Parameters::AnalyticalSolution analyticalSolution; + Parameters::Restart restartParameters; BoundaryConditions::NSBoundaryConditions boundaryConditions; - Parameters::InitialConditions *initialCondition; - SimulationControl simulationControl; + Parameters::InitialConditions * initialCondition; + SimulationControl simulationControl; - void declare(ParameterHandler &prm) { + void + declare(ParameterHandler &prm) + { initialCondition = new Parameters::InitialConditions; Parameters::SimulationControl::declare_parameters(prm); Parameters::PhysicalProperties::declare_parameters(prm); @@ -62,7 +66,9 @@ template class NavierStokesSolverParameters { Parameters::Testing::declare_parameters(prm); } - void parse(ParameterHandler &prm) { + void + parse(ParameterHandler &prm) + { test.parse_parameters(prm); linearSolver.parse_parameters(prm); nonLinearSolver.parse_parameters(prm); diff --git a/src/parameters.cc b/src/parameters.cc index ccd69ca653..f67afb8b5b 100644 --- a/src/parameters.cc +++ b/src/parameters.cc @@ -1,305 +1,428 @@ #include "parameters.h" -namespace Parameters { -void SimulationControl::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("simulation control"); +namespace Parameters +{ + void + SimulationControl::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("method", "steady", - Patterns::Selection("steady|bdf1|bdf2|bdf3"), - "The kind of solver for the linear system. " - "Choices are ."); - prm.declare_entry("time step", "1.", Patterns::Double(), "Time step value"); - prm.declare_entry("time end", "1", Patterns::Double(), "Time step value"); - prm.declare_entry("startup time scaling", "0.4", Patterns::Double(), - "Scaling factor used in the iterations necessary to " - "start-up the BDF schemes."); - - prm.declare_entry("adapt", "false", Patterns::Bool(), - "Adaptative time-stepping "); - prm.declare_entry("number mesh adapt", "0", Patterns::Integer(), - "Number of mesh adaptation (for steady simulations)"); - prm.declare_entry("max cfl", "1", Patterns::Double(), "Maximum CFL value"); - prm.declare_entry("output path", "./", Patterns::FileName(), - "File output prefix"); - - prm.declare_entry("output name", "out", Patterns::FileName(), - "File output prefix"); - - prm.declare_entry("output frequency", "1", Patterns::Integer(), - "Output frequency"); - - prm.declare_entry("subdivision", "1", Patterns::Integer(), - "Subdivision of mesh cell in postprocessing"); + prm.enter_subsection("simulation control"); + { + prm.declare_entry("method", + "steady", + Patterns::Selection("steady|bdf1|bdf2|bdf3"), + "The kind of solver for the linear system. " + "Choices are ."); + prm.declare_entry("time step", + "1.", + Patterns::Double(), + "Time step value"); + prm.declare_entry("time end", "1", Patterns::Double(), "Time step value"); + prm.declare_entry("startup time scaling", + "0.4", + Patterns::Double(), + "Scaling factor used in the iterations necessary to " + "start-up the BDF schemes."); + + prm.declare_entry("adapt", + "false", + Patterns::Bool(), + "Adaptative time-stepping "); + prm.declare_entry("number mesh adapt", + "0", + Patterns::Integer(), + "Number of mesh adaptation (for steady simulations)"); + prm.declare_entry("max cfl", + "1", + Patterns::Double(), + "Maximum CFL value"); + prm.declare_entry("output path", + "./", + Patterns::FileName(), + "File output prefix"); + + prm.declare_entry("output name", + "out", + Patterns::FileName(), + "File output prefix"); + + prm.declare_entry("output frequency", + "1", + Patterns::Integer(), + "Output frequency"); + + prm.declare_entry("subdivision", + "1", + Patterns::Integer(), + "Subdivision of mesh cell in postprocessing"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void SimulationControl::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("simulation control"); + void + SimulationControl::parse_parameters(ParameterHandler &prm) { - const std::string sv = prm.get("method"); - if (sv == "steady") - method = steady; - else if (sv == "bdf1") - method = bdf1; - else if (sv == "bdf2") - method = bdf2; - else if (sv == "bdf3") - method = bdf3; - dt = prm.get_double("time step"); - timeEnd = prm.get_double("time end"); - adapt = prm.get_bool("adapt"); - maxCFL = prm.get_double("max cfl"); - startup_timestep_scaling = prm.get_double("startup time scaling"); - nbMeshAdapt = prm.get_integer("number mesh adapt"); - output_folder = prm.get("output path"); - output_name = prm.get("output name"); - outputFrequency = prm.get_integer("output frequency"); - subdivision = prm.get_integer("subdivision"); + prm.enter_subsection("simulation control"); + { + const std::string sv = prm.get("method"); + if (sv == "steady") + method = steady; + else if (sv == "bdf1") + method = bdf1; + else if (sv == "bdf2") + method = bdf2; + else if (sv == "bdf3") + method = bdf3; + dt = prm.get_double("time step"); + timeEnd = prm.get_double("time end"); + adapt = prm.get_bool("adapt"); + maxCFL = prm.get_double("max cfl"); + startup_timestep_scaling = prm.get_double("startup time scaling"); + nbMeshAdapt = prm.get_integer("number mesh adapt"); + output_folder = prm.get("output path"); + output_name = prm.get("output name"); + outputFrequency = prm.get_integer("output frequency"); + subdivision = prm.get_integer("subdivision"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Timer::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("timer"); + void + Timer::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("type", "none", Patterns::Selection("none|iteration|end"), - "Clock monitoring methods " - "Choices are ."); + prm.enter_subsection("timer"); + { + prm.declare_entry("type", + "none", + Patterns::Selection("none|iteration|end"), + "Clock monitoring methods " + "Choices are ."); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Timer::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("timer"); + void + Timer::parse_parameters(ParameterHandler &prm) { - const std::string cl = prm.get("type"); - if (cl == "none") - type = none; - else if (cl == "iteration") - type = iteration; - else if (cl == "end") - type = end; + prm.enter_subsection("timer"); + { + const std::string cl = prm.get("type"); + if (cl == "none") + type = none; + else if (cl == "iteration") + type = iteration; + else if (cl == "end") + type = end; + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void PhysicalProperties::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("physical properties"); + void + PhysicalProperties::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("kinematic viscosity", "1", Patterns::Double(), - "Kinematic viscosity"); + prm.enter_subsection("physical properties"); + { + prm.declare_entry("kinematic viscosity", + "1", + Patterns::Double(), + "Kinematic viscosity"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void PhysicalProperties::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("physical properties"); - { viscosity = prm.get_double("kinematic viscosity"); } - prm.leave_subsection(); -} + void + PhysicalProperties::parse_parameters(ParameterHandler &prm) + { + prm.enter_subsection("physical properties"); + { + viscosity = prm.get_double("kinematic viscosity"); + } + prm.leave_subsection(); + } -void FEM::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("FEM"); + void + FEM::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("velocity order", "1", Patterns::Integer(), - "interpolation order velocity"); - prm.declare_entry("pressure order", "1", Patterns::Integer(), - "interpolation order pressure"); - prm.declare_entry("quadrature points", "0", Patterns::Integer(), - "interpolation order pressure"); - prm.declare_entry("qmapping all", "false", Patterns::Bool(), - "Apply high order mapping everywhere"); + prm.enter_subsection("FEM"); + { + prm.declare_entry("velocity order", + "1", + Patterns::Integer(), + "interpolation order velocity"); + prm.declare_entry("pressure order", + "1", + Patterns::Integer(), + "interpolation order pressure"); + prm.declare_entry("quadrature points", + "0", + Patterns::Integer(), + "interpolation order pressure"); + prm.declare_entry("qmapping all", + "false", + Patterns::Bool(), + "Apply high order mapping everywhere"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void FEM::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("FEM"); + void + FEM::parse_parameters(ParameterHandler &prm) { - velocityOrder = prm.get_integer("velocity order"); - pressureOrder = prm.get_integer("pressure order"); - quadraturePoints = prm.get_integer("quadrature points"); - qmapping_all = prm.get_bool("qmapping all"); + prm.enter_subsection("FEM"); + { + velocityOrder = prm.get_integer("velocity order"); + pressureOrder = prm.get_integer("pressure order"); + quadraturePoints = prm.get_integer("quadrature points"); + qmapping_all = prm.get_bool("qmapping all"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Forces::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("forces"); + void + Forces::declare_parameters(ParameterHandler &prm) { - prm.declare_entry( - "verbosity", "quiet", Patterns::Selection("quiet|verbose"), + prm.enter_subsection("forces"); + { + prm.declare_entry( + "verbosity", + "quiet", + Patterns::Selection("quiet|verbose"), "State whether from the non-linear solver should be printed " "Choices are ."); - prm.declare_entry("calculate forces", "false", Patterns::Bool(), - "Enable calculation of forces"); - prm.declare_entry("calculate torques", "false", Patterns::Bool(), - "Enable calculation of torques"); - prm.declare_entry("force name", "force", Patterns::FileName(), - "File output force prefix"); - prm.declare_entry("torque name", "torque", Patterns::FileName(), - "File output force prefix"); - prm.declare_entry("output precision", "10", Patterns::Integer(), - "Calculation frequency"); - prm.declare_entry("display precision", "4", Patterns::Integer(), - "Output frequency"); - prm.declare_entry("calculation frequency", "1", Patterns::Integer(), - "Calculation frequency"); - prm.declare_entry("output frequency", "1", Patterns::Integer(), - "Output frequency"); + prm.declare_entry("calculate forces", + "false", + Patterns::Bool(), + "Enable calculation of forces"); + prm.declare_entry("calculate torques", + "false", + Patterns::Bool(), + "Enable calculation of torques"); + prm.declare_entry("force name", + "force", + Patterns::FileName(), + "File output force prefix"); + prm.declare_entry("torque name", + "torque", + Patterns::FileName(), + "File output force prefix"); + prm.declare_entry("output precision", + "10", + Patterns::Integer(), + "Calculation frequency"); + prm.declare_entry("display precision", + "4", + Patterns::Integer(), + "Output frequency"); + prm.declare_entry("calculation frequency", + "1", + Patterns::Integer(), + "Calculation frequency"); + prm.declare_entry("output frequency", + "1", + Patterns::Integer(), + "Output frequency"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Forces::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("forces"); + void + Forces::parse_parameters(ParameterHandler &prm) { - const std::string op = prm.get("verbosity"); - if (op == "verbose") - verbosity = verbose; - if (op == "quiet") - verbosity = quiet; - calculate_force = prm.get_bool("calculate forces"); - calculate_torque = prm.get_bool("calculate torques"); - force_output_name = prm.get("force name"); - torque_output_name = prm.get("torque name"); - display_precision = prm.get_integer("display precision"); - output_precision = prm.get_integer("output precision"); - calculation_frequency = prm.get_integer("calculation frequency"); - output_frequency = prm.get_integer("output frequency"); + prm.enter_subsection("forces"); + { + const std::string op = prm.get("verbosity"); + if (op == "verbose") + verbosity = verbose; + if (op == "quiet") + verbosity = quiet; + calculate_force = prm.get_bool("calculate forces"); + calculate_torque = prm.get_bool("calculate torques"); + force_output_name = prm.get("force name"); + torque_output_name = prm.get("torque name"); + display_precision = prm.get_integer("display precision"); + output_precision = prm.get_integer("output precision"); + calculation_frequency = prm.get_integer("calculation frequency"); + output_frequency = prm.get_integer("output frequency"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void AnalyticalSolution::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("analytical solution"); + void + AnalyticalSolution::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("error precision", "3", Patterns::Integer(), - "Number of digits displayed when showing residuals"); + prm.enter_subsection("analytical solution"); + { + prm.declare_entry("error precision", + "3", + Patterns::Integer(), + "Number of digits displayed when showing residuals"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void AnalyticalSolution::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("analytical solution"); - { errorPrecision = prm.get_integer("error precision"); } - prm.leave_subsection(); -} + void + AnalyticalSolution::parse_parameters(ParameterHandler &prm) + { + prm.enter_subsection("analytical solution"); + { + errorPrecision = prm.get_integer("error precision"); + } + prm.leave_subsection(); + } -void NonLinearSolver::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("non-linear solver"); + void + NonLinearSolver::declare_parameters(ParameterHandler &prm) { - prm.declare_entry( - "verbosity", "verbose", Patterns::Selection("quiet|verbose"), + prm.enter_subsection("non-linear solver"); + { + prm.declare_entry( + "verbosity", + "verbose", + Patterns::Selection("quiet|verbose"), "State whether from the non-linear solver should be printed " "Choices are ."); - prm.declare_entry("tolerance", "1e-6", Patterns::Double(), - "Newton solver tolerance"); - prm.declare_entry("max iterations", "10", Patterns::Integer(), - "Maximum number of Newton Iterations"); - prm.declare_entry("residual precision", "4", Patterns::Integer(), - "Number of digits displayed when showing residuals"); + prm.declare_entry("tolerance", + "1e-6", + Patterns::Double(), + "Newton solver tolerance"); + prm.declare_entry("max iterations", + "10", + Patterns::Integer(), + "Maximum number of Newton Iterations"); + prm.declare_entry("residual precision", + "4", + Patterns::Integer(), + "Number of digits displayed when showing residuals"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void NonLinearSolver::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("non-linear solver"); + void + NonLinearSolver::parse_parameters(ParameterHandler &prm) { - const std::string op = prm.get("verbosity"); - if (op == "verbose") - verbosity = verbose; - if (op == "quiet") - verbosity = quiet; - tolerance = prm.get_double("tolerance"); - maxIterations = prm.get_integer("max iterations"); - display_precision = prm.get_integer("residual precision"); + prm.enter_subsection("non-linear solver"); + { + const std::string op = prm.get("verbosity"); + if (op == "verbose") + verbosity = verbose; + if (op == "quiet") + verbosity = quiet; + tolerance = prm.get_double("tolerance"); + maxIterations = prm.get_integer("max iterations"); + display_precision = prm.get_integer("residual precision"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Mesh::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("mesh"); + void + Mesh::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("type", "gmsh", Patterns::Selection("gmsh|primitive"), - "Type of mesh " - "Choices are ."); - - prm.declare_entry("file name", "none", Patterns::FileName(), - "GMSH file name"); - - prm.declare_entry("primitive type", "hyper_cube", - Patterns::Selection("hyper_cube|hyper_shell"), - "Type of primitive " - "Choices are ."); - - prm.declare_entry("initial refinement", "0", Patterns::Integer(), - "Initial refinement of primitive mesh"); - - prm.declare_entry("hs inner radius", "1", Patterns::Double(), - "Inner radius for hyper shell"); - - prm.declare_entry("hs outer radius", "2", Patterns::Double(), - "Outer radius for hyper shell"); - - prm.declare_entry("hc left", "0", Patterns::Double(), - "Left position of hyper cube"); - - prm.declare_entry("hc right", "1", Patterns::Double(), - "Right position of hyper cube"); - - prm.declare_entry("colorize", "false", Patterns::Bool(), - "Colorize boundary conditions"); + prm.enter_subsection("mesh"); + { + prm.declare_entry("type", + "gmsh", + Patterns::Selection("gmsh|primitive"), + "Type of mesh " + "Choices are ."); + + prm.declare_entry("file name", + "none", + Patterns::FileName(), + "GMSH file name"); + + prm.declare_entry("primitive type", + "hyper_cube", + Patterns::Selection("hyper_cube|hyper_shell"), + "Type of primitive " + "Choices are ."); + + prm.declare_entry("initial refinement", + "0", + Patterns::Integer(), + "Initial refinement of primitive mesh"); + + prm.declare_entry("hs inner radius", + "1", + Patterns::Double(), + "Inner radius for hyper shell"); + + prm.declare_entry("hs outer radius", + "2", + Patterns::Double(), + "Outer radius for hyper shell"); + + prm.declare_entry("hc left", + "0", + Patterns::Double(), + "Left position of hyper cube"); + + prm.declare_entry("hc right", + "1", + Patterns::Double(), + "Right position of hyper cube"); + + prm.declare_entry("colorize", + "false", + Patterns::Bool(), + "Colorize boundary conditions"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Mesh::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("mesh"); + void + Mesh::parse_parameters(ParameterHandler &prm) { + prm.enter_subsection("mesh"); { - const std::string op = prm.get("type"); - if (op == "gmsh") - type = gmsh; - if (op == "primitive") - type = primitive; + { + const std::string op = prm.get("type"); + if (op == "gmsh") + type = gmsh; + if (op == "primitive") + type = primitive; + } + + fileName = prm.get("file name"); + + initialRefinement = prm.get_integer("initial refinement"); + + const std::string prim_type = prm.get("primitive type"); + if (prim_type == "hyper_cube") + primitiveType = hyper_cube; + else if (prim_type == "hyper_shell") + primitiveType = hyper_shell; + else + throw std::runtime_error("Unsupported primitive - Program will abort"); + + hc_left = prm.get_double("hc left"); + hc_right = prm.get_double("hc right"); + hs_inner_radius = prm.get_double("hs inner radius"); + hs_outer_radius = prm.get_double("hs outer radius"); + + colorize = prm.get_bool("colorize"); } - - fileName = prm.get("file name"); - - initialRefinement = prm.get_integer("initial refinement"); - - const std::string prim_type = prm.get("primitive type"); - if (prim_type == "hyper_cube") - primitiveType = hyper_cube; - else if (prim_type == "hyper_shell") - primitiveType = hyper_shell; - else - throw std::runtime_error("Unsupported primitive - Program will abort"); - - hc_left = prm.get_double("hc left"); - hc_right = prm.get_double("hc right"); - hs_inner_radius = prm.get_double("hs inner radius"); - hs_outer_radius = prm.get_double("hs outer radius"); - - colorize = prm.get_bool("colorize"); + prm.leave_subsection(); } - prm.leave_subsection(); -} -void LinearSolver::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("linear solver"); + void + LinearSolver::declare_parameters(ParameterHandler &prm) { - prm.declare_entry( - "verbosity", "verbose", Patterns::Selection("quiet|verbose"), + prm.enter_subsection("linear solver"); + { + prm.declare_entry( + "verbosity", + "verbose", + Patterns::Selection("quiet|verbose"), "State whether output from solver runs should be printed. " "Choices are ."); - prm.declare_entry( - "residual precision", "6", Patterns::Integer(), + prm.declare_entry( + "residual precision", + "6", + Patterns::Integer(), "Number of digits used when outputing the residual in the terminal"); - prm.declare_entry( - "method", "gmres", Patterns::Selection("gmres|bicgstab|amg"), + prm.declare_entry( + "method", + "gmres", + Patterns::Selection("gmres|bicgstab|amg"), "The iterative solver for the linear system of equations. " "Choices are . gmres is a GMRES iterative solver " "with ILU preconditioning. bicgstab is a BICGSTAB iterative solver " @@ -310,185 +433,257 @@ void LinearSolver::declare_parameters(ParameterHandler &prm) { "As the number of mesh elements increase, the amg solver is the most " "efficient. Generally, at 1M elements, the amg solver always " "outperforms the gmres or bicgstab"); - prm.declare_entry("relative residual", "1e-3", Patterns::Double(), - "Linear solver residual"); - prm.declare_entry("minimum residual", "1e-8", Patterns::Double(), - "Linear solver minimum residual"); - prm.declare_entry("max iters", "1000", Patterns::Integer(), - "Maximum solver iterations"); - - prm.declare_entry("ilu preconditioner fill", "1", Patterns::Double(), - "Ilu preconditioner fill"); - - prm.declare_entry("ilu preconditioner absolute tolerance", "1e-6", - Patterns::Double(), "Ilu preconditioner tolerance"); - - prm.declare_entry("ilu preconditioner relative tolerance", "1.00", - Patterns::Double(), "Ilu relative tolerance"); - - prm.declare_entry("amg preconditioner ilu fill", "1", Patterns::Double(), - "amg preconditioner ilu smoother/coarsener fill"); - - prm.declare_entry( - "amg preconditioner ilu absolute tolerance", "1e-12", + prm.declare_entry("relative residual", + "1e-3", + Patterns::Double(), + "Linear solver residual"); + prm.declare_entry("minimum residual", + "1e-8", + Patterns::Double(), + "Linear solver minimum residual"); + prm.declare_entry("max iters", + "1000", + Patterns::Integer(), + "Maximum solver iterations"); + + prm.declare_entry("ilu preconditioner fill", + "1", + Patterns::Double(), + "Ilu preconditioner fill"); + + prm.declare_entry("ilu preconditioner absolute tolerance", + "1e-6", + Patterns::Double(), + "Ilu preconditioner tolerance"); + + prm.declare_entry("ilu preconditioner relative tolerance", + "1.00", + Patterns::Double(), + "Ilu relative tolerance"); + + prm.declare_entry("amg preconditioner ilu fill", + "1", + Patterns::Double(), + "amg preconditioner ilu smoother/coarsener fill"); + + prm.declare_entry( + "amg preconditioner ilu absolute tolerance", + "1e-12", Patterns::Double(), "amg preconditioner ilu smoother/coarsener absolute tolerance"); - prm.declare_entry( - "amg preconditioner ilu relative tolerance", "1.00", Patterns::Double(), + prm.declare_entry( + "amg preconditioner ilu relative tolerance", + "1.00", + Patterns::Double(), "amg preconditioner ilu smoother/coarsener relative tolerance"); - prm.declare_entry("amg aggregation threshold", "1e-14", Patterns::Double(), - "amg aggregation threshold"); - prm.declare_entry("amg n cycles", "1", Patterns::Integer(), - "amg number of cycles"); - prm.declare_entry("amg w cycles", "false", Patterns::Bool(), - "amg w cycling. If this is set to true, W cycling is " - "used. Otherwise, V cycling is used."); - prm.declare_entry("amg smoother sweeps", "2", Patterns::Integer(), - "amg smoother sweeps"); - prm.declare_entry("amg smoother overlap", "1", Patterns::Integer(), - "amg smoother overlap"); + prm.declare_entry("amg aggregation threshold", + "1e-14", + Patterns::Double(), + "amg aggregation threshold"); + prm.declare_entry("amg n cycles", + "1", + Patterns::Integer(), + "amg number of cycles"); + prm.declare_entry("amg w cycles", + "false", + Patterns::Bool(), + "amg w cycling. If this is set to true, W cycling is " + "used. Otherwise, V cycling is used."); + prm.declare_entry("amg smoother sweeps", + "2", + Patterns::Integer(), + "amg smoother sweeps"); + prm.declare_entry("amg smoother overlap", + "1", + Patterns::Integer(), + "amg smoother overlap"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void LinearSolver::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("linear solver"); + void + LinearSolver::parse_parameters(ParameterHandler &prm) { - const std::string op = prm.get("verbosity"); - if (op == "verbose") - verbosity = verbose; - if (op == "quiet") - verbosity = quiet; - - const std::string sv = prm.get("method"); - if (sv == "amg") - solver = amg; - else if (sv == "gmres") - solver = gmres; - else if (sv == "bicgstab") - solver = bicgstab; - residual_precision = prm.get_integer("residual precision"); - relative_residual = prm.get_double("relative residual"); - minimum_residual = prm.get_double("minimum residual"); - max_iterations = prm.get_integer("max iters"); - ilu_precond_fill = prm.get_double("ilu preconditioner fill"); - ilu_precond_atol = prm.get_double("ilu preconditioner absolute tolerance"); - ilu_precond_rtol = prm.get_double("ilu preconditioner relative tolerance"); - amg_precond_ilu_fill = prm.get_double("amg preconditioner ilu fill"); - amg_precond_ilu_atol = + prm.enter_subsection("linear solver"); + { + const std::string op = prm.get("verbosity"); + if (op == "verbose") + verbosity = verbose; + if (op == "quiet") + verbosity = quiet; + + const std::string sv = prm.get("method"); + if (sv == "amg") + solver = amg; + else if (sv == "gmres") + solver = gmres; + else if (sv == "bicgstab") + solver = bicgstab; + residual_precision = prm.get_integer("residual precision"); + relative_residual = prm.get_double("relative residual"); + minimum_residual = prm.get_double("minimum residual"); + max_iterations = prm.get_integer("max iters"); + ilu_precond_fill = prm.get_double("ilu preconditioner fill"); + ilu_precond_atol = + prm.get_double("ilu preconditioner absolute tolerance"); + ilu_precond_rtol = + prm.get_double("ilu preconditioner relative tolerance"); + amg_precond_ilu_fill = prm.get_double("amg preconditioner ilu fill"); + amg_precond_ilu_atol = prm.get_double("amg preconditioner ilu absolute tolerance"); - amg_precond_ilu_rtol = + amg_precond_ilu_rtol = prm.get_double("amg preconditioner ilu relative tolerance"); - amg_aggregation_threshold = prm.get_double("amg aggregation threshold"); - amg_n_cycles = prm.get_integer("amg n cycles"); - amg_w_cycles = prm.get_bool("amg w cycles"); - amg_smoother_sweeps = prm.get_integer("amg smoother sweeps"); - amg_smoother_overlap = prm.get_integer("amg smoother overlap"); + amg_aggregation_threshold = prm.get_double("amg aggregation threshold"); + amg_n_cycles = prm.get_integer("amg n cycles"); + amg_w_cycles = prm.get_bool("amg w cycles"); + amg_smoother_sweeps = prm.get_integer("amg smoother sweeps"); + amg_smoother_overlap = prm.get_integer("amg smoother overlap"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void MeshAdaptation::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("mesh adaptation"); + void + MeshAdaptation::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("type", "none", Patterns::Selection("none|uniform|kelly"), - "Type of mesh adaptation" - "Choices are ."); - - prm.declare_entry("variable", "velocity", - Patterns::Selection("velocity|pressure"), - "Variable for kelly estimation" - "Choices are ."); - prm.declare_entry( - "fraction type", "number", Patterns::Selection("number|fraction"), + prm.enter_subsection("mesh adaptation"); + { + prm.declare_entry("type", + "none", + Patterns::Selection("none|uniform|kelly"), + "Type of mesh adaptation" + "Choices are ."); + + prm.declare_entry("variable", + "velocity", + Patterns::Selection("velocity|pressure"), + "Variable for kelly estimation" + "Choices are ."); + prm.declare_entry( + "fraction type", + "number", + Patterns::Selection("number|fraction"), "How the fraction of refinement/coarsening are interepreted" "Choices are ."); - prm.declare_entry("max number elements", "100000000", Patterns::Integer(), - "Maximum number of elements"); - prm.declare_entry("max refinement level", "10", Patterns::Integer(), - "Maximum refinement level"); - prm.declare_entry("min refinement level", "1", Patterns::Integer(), - "Minimum refinement level"); - prm.declare_entry("frequency", "1", Patterns::Integer(), - "Frequency of the mesh refinement"); - prm.declare_entry("fraction refinement", "0.1", Patterns::Double(), - "Fraction of refined elements"); - prm.declare_entry("fraction coarsening", "0.05", Patterns::Double(), - "Fraction of coarsened elements"); + prm.declare_entry("max number elements", + "100000000", + Patterns::Integer(), + "Maximum number of elements"); + prm.declare_entry("max refinement level", + "10", + Patterns::Integer(), + "Maximum refinement level"); + prm.declare_entry("min refinement level", + "1", + Patterns::Integer(), + "Minimum refinement level"); + prm.declare_entry("frequency", + "1", + Patterns::Integer(), + "Frequency of the mesh refinement"); + prm.declare_entry("fraction refinement", + "0.1", + Patterns::Double(), + "Fraction of refined elements"); + prm.declare_entry("fraction coarsening", + "0.05", + Patterns::Double(), + "Fraction of coarsened elements"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void MeshAdaptation::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("mesh adaptation"); + void + MeshAdaptation::parse_parameters(ParameterHandler &prm) { - const std::string op = prm.get("type"); - if (op == "none") - type = none; - if (op == "uniform") - type = uniform; - if (op == "kelly") - type = kelly; - - const std::string vop = prm.get("variable"); - if (vop == "velocity") - variable = velocity; - if (vop == "pressure") - variable = pressure; - - const std::string fop = prm.get("fraction type"); - if (fop == "number") - fractionType = number; - if (fop == "fraction") - fractionType = fraction; - maxNbElements = prm.get_integer("max number elements"); - maxRefLevel = prm.get_integer("max refinement level"); - minRefLevel = prm.get_integer("min refinement level"); - frequency = prm.get_integer("frequency"); - fractionCoarsening = prm.get_double("fraction coarsening"); - fractionRefinement = prm.get_double("fraction refinement"); + prm.enter_subsection("mesh adaptation"); + { + const std::string op = prm.get("type"); + if (op == "none") + type = none; + if (op == "uniform") + type = uniform; + if (op == "kelly") + type = kelly; + + const std::string vop = prm.get("variable"); + if (vop == "velocity") + variable = velocity; + if (vop == "pressure") + variable = pressure; + + const std::string fop = prm.get("fraction type"); + if (fop == "number") + fractionType = number; + if (fop == "fraction") + fractionType = fraction; + maxNbElements = prm.get_integer("max number elements"); + maxRefLevel = prm.get_integer("max refinement level"); + minRefLevel = prm.get_integer("min refinement level"); + frequency = prm.get_integer("frequency"); + fractionCoarsening = prm.get_double("fraction coarsening"); + fractionRefinement = prm.get_double("fraction refinement"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Testing::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("test"); + void + Testing::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("enable", "false", Patterns::Bool(), - "Enable testing mode of a solver"); + prm.enter_subsection("test"); + { + prm.declare_entry("enable", + "false", + Patterns::Bool(), + "Enable testing mode of a solver"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Testing::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("test"); - { enabled = prm.get_bool("enable"); } - prm.leave_subsection(); -} + void + Testing::parse_parameters(ParameterHandler &prm) + { + prm.enter_subsection("test"); + { + enabled = prm.get_bool("enable"); + } + prm.leave_subsection(); + } -void Restart::declare_parameters(ParameterHandler &prm) { - prm.enter_subsection("restart"); + void + Restart::declare_parameters(ParameterHandler &prm) { - prm.declare_entry("filename", "restart", Patterns::FileName(), - "Prefix for the filename of checkpoints"); - prm.declare_entry("restart", "false", Patterns::Bool(), - "Frequency for checkpointing"); - prm.declare_entry("checkpoint", "false", Patterns::Bool(), - "Enable checkpointing"); - prm.declare_entry("frequency", "1", Patterns::Integer(), - "Frequency for checkpointing"); + prm.enter_subsection("restart"); + { + prm.declare_entry("filename", + "restart", + Patterns::FileName(), + "Prefix for the filename of checkpoints"); + prm.declare_entry("restart", + "false", + Patterns::Bool(), + "Frequency for checkpointing"); + prm.declare_entry("checkpoint", + "false", + Patterns::Bool(), + "Enable checkpointing"); + prm.declare_entry("frequency", + "1", + Patterns::Integer(), + "Frequency for checkpointing"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} -void Restart::parse_parameters(ParameterHandler &prm) { - prm.enter_subsection("restart"); + void + Restart::parse_parameters(ParameterHandler &prm) { - filename = prm.get("filename"); - checkpoint = prm.get_bool("checkpoint"); - restart = prm.get_bool("restart"); - frequency = prm.get_integer("frequency"); + prm.enter_subsection("restart"); + { + filename = prm.get("filename"); + checkpoint = prm.get_bool("checkpoint"); + restart = prm.get_bool("restart"); + frequency = prm.get_integer("frequency"); + } + prm.leave_subsection(); } - prm.leave_subsection(); -} } // namespace Parameters diff --git a/src/parameters.h b/src/parameters.h index 43d648ca85..c6a1543956 100644 --- a/src/parameters.h +++ b/src/parameters.h @@ -5,282 +5,367 @@ #include #ifndef LETHE_GLS_PARAMETERS_H -#define LETHE_GLS_PARAMETERS_H +# define LETHE_GLS_PARAMETERS_H using namespace dealii; -namespace Parameters { -struct SimulationControl { - // Method used for time progression (steady, unsteady) - enum TimeSteppingMethod { steady, bdf1, bdf2, bdf3 }; - TimeSteppingMethod method; - - // Initial time step - double dt; - - // End time - double timeEnd; - - // Adaptative time stepping - bool adapt; - - // Max CFL - double maxCFL; - - // BDF startup time scaling - double startup_timestep_scaling; - - // Number of mesh adaptation (steady simulations) - unsigned int nbMeshAdapt; - - // Folder for simulation output - std::string output_folder; - - // Prefix for simulation output - std::string output_name; - - // Frequency of the output - unsigned int outputFrequency; - - // Subdivsions of the results in the output - unsigned int subdivision; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct PhysicalProperties { - // Kinematic viscosity (mu/rho) - double viscosity; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct Timer { - // Time measurement in the simulation. None, at each iteration, only at the - // end - enum Type { none, iteration, end }; - Type type; - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct AnalyticalSolution { - // Residual precision - unsigned int errorPrecision; - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct Forces { - // Type of verbosity for the iterative solver - enum Verbosity { quiet, verbose }; - Verbosity verbosity; - - // Enable force post-processing - bool calculate_force; - - // Enable torque post-processing - bool calculate_torque; - - // Frequency of the output - unsigned int calculation_frequency; - - // Frequency of the output - unsigned int output_frequency; - - // Output precision - unsigned int output_precision; - - // Display precision - unsigned int display_precision; - - // Prefix for simulation output - std::string force_output_name; - - // Prefix for the torque output - std::string torque_output_name; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct FEM { - // Interpolation order velocity - unsigned int velocityOrder; - - // Interpolation order pressure - unsigned int pressureOrder; - - // Number of quadrature points - unsigned int quadraturePoints; - - // Apply high order mapping everywhere - bool qmapping_all; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct NonLinearSolver { - // Type of verbosity for the iterative solver - enum Verbosity { quiet, verbose }; - Verbosity verbosity; - - // Tolerance - double tolerance; - - // Maximal number of iterations for the Newton solver - unsigned int maxIterations; - - // Residual precision - unsigned int display_precision; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct LinearSolver { - // Type of linear solver - enum SolverType { gmres, bicgstab, amg }; - SolverType solver; - - // Type of verbosity for the iterative solver - enum Verbosity { quiet, verbose }; - Verbosity verbosity; - - // Residual precision - unsigned int residual_precision; - - // Relative residual of the iterative solver - double relative_residual; - - // Minimum residual of the iterative solver - double minimum_residual; - - // Maximum number of iterations - int max_iterations; - - // ILU or ILUT fill - double ilu_precond_fill; - - // ILU or ILUT absolute tolerance - double ilu_precond_atol; - - // ILU or ILUT relative tolerance - double ilu_precond_rtol; - - // ILU or ILUT fill - double amg_precond_ilu_fill; - - // ILU or ILUT absolute tolerance - double amg_precond_ilu_atol; - - // ILU or ILUT relative tolerance - double amg_precond_ilu_rtol; - - // AMG aggregation threshold - double amg_aggregation_threshold; - - // AMG number of cycles - unsigned int amg_n_cycles; - - // AMG W_cycle - bool amg_w_cycles; - - // AMG Smoother sweeps - unsigned int amg_smoother_sweeps; - - // AMG Smoother overalp - unsigned int amg_smoother_overlap; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct Mesh { - // GMSH or dealii primitive - enum Type { gmsh, primitive }; - Type type; - - // Primitive types - enum PrimitiveType { hyper_cube, hyper_shell }; - PrimitiveType primitiveType; - - bool colorize; - - // Parameters for the hyper shell - double hs_inner_radius; - double hs_outer_radius; - - // Parameters for the hyper cube - double hc_left; - double hc_right; - - // File name of the mesh - std::string fileName; - - // Initial refinement level of primitive mesh - unsigned int initialRefinement; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct MeshAdaptation { - - // Type of mesh adaptation - enum Type { none, uniform, kelly }; - Type type; - - enum Variable { velocity, pressure }; - Variable variable; - - // Decision factor for KELLY refinement (number or fraction) - enum FractionType { number, fraction }; - FractionType fractionType; - - // Maximum number of elements - unsigned int maxNbElements; - - // Maximum refinement level - unsigned int maxRefLevel; - - // Maximum refinement level - unsigned int minRefLevel; - - // Refinement after frequency iter - unsigned int frequency; - - // Refinement fractioni havent used ILUT much) - double fractionRefinement; - - // Coarsening fraction - double fractionCoarsening; - - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct Testing { - // Time measurement in the simulation. None, at each iteration, only at the - // end - bool enabled; - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; - -struct Restart { - // Time measurement in the simulation. None, at each iteration, only at the - // end - std::string filename; - bool restart; - bool checkpoint; - unsigned int frequency; - static void declare_parameters(ParameterHandler &prm); - void parse_parameters(ParameterHandler &prm); -}; +namespace Parameters +{ + struct SimulationControl + { + // Method used for time progression (steady, unsteady) + enum TimeSteppingMethod + { + steady, + bdf1, + bdf2, + bdf3 + }; + TimeSteppingMethod method; + + // Initial time step + double dt; + + // End time + double timeEnd; + + // Adaptative time stepping + bool adapt; + + // Max CFL + double maxCFL; + + // BDF startup time scaling + double startup_timestep_scaling; + + // Number of mesh adaptation (steady simulations) + unsigned int nbMeshAdapt; + + // Folder for simulation output + std::string output_folder; + + // Prefix for simulation output + std::string output_name; + + // Frequency of the output + unsigned int outputFrequency; + + // Subdivsions of the results in the output + unsigned int subdivision; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct PhysicalProperties + { + // Kinematic viscosity (mu/rho) + double viscosity; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct Timer + { + // Time measurement in the simulation. None, at each iteration, only at the + // end + enum Type + { + none, + iteration, + end + }; + Type type; + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct AnalyticalSolution + { + // Residual precision + unsigned int errorPrecision; + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct Forces + { + // Type of verbosity for the iterative solver + enum Verbosity + { + quiet, + verbose + }; + Verbosity verbosity; + + // Enable force post-processing + bool calculate_force; + + // Enable torque post-processing + bool calculate_torque; + + // Frequency of the output + unsigned int calculation_frequency; + + // Frequency of the output + unsigned int output_frequency; + + // Output precision + unsigned int output_precision; + + // Display precision + unsigned int display_precision; + + // Prefix for simulation output + std::string force_output_name; + + // Prefix for the torque output + std::string torque_output_name; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct FEM + { + // Interpolation order velocity + unsigned int velocityOrder; + + // Interpolation order pressure + unsigned int pressureOrder; + + // Number of quadrature points + unsigned int quadraturePoints; + + // Apply high order mapping everywhere + bool qmapping_all; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct NonLinearSolver + { + // Type of verbosity for the iterative solver + enum Verbosity + { + quiet, + verbose + }; + Verbosity verbosity; + + // Tolerance + double tolerance; + + // Maximal number of iterations for the Newton solver + unsigned int maxIterations; + + // Residual precision + unsigned int display_precision; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct LinearSolver + { + // Type of linear solver + enum SolverType + { + gmres, + bicgstab, + amg + }; + SolverType solver; + + // Type of verbosity for the iterative solver + enum Verbosity + { + quiet, + verbose + }; + Verbosity verbosity; + + // Residual precision + unsigned int residual_precision; + + // Relative residual of the iterative solver + double relative_residual; + + // Minimum residual of the iterative solver + double minimum_residual; + + // Maximum number of iterations + int max_iterations; + + // ILU or ILUT fill + double ilu_precond_fill; + + // ILU or ILUT absolute tolerance + double ilu_precond_atol; + + // ILU or ILUT relative tolerance + double ilu_precond_rtol; + + // ILU or ILUT fill + double amg_precond_ilu_fill; + + // ILU or ILUT absolute tolerance + double amg_precond_ilu_atol; + + // ILU or ILUT relative tolerance + double amg_precond_ilu_rtol; + + // AMG aggregation threshold + double amg_aggregation_threshold; + + // AMG number of cycles + unsigned int amg_n_cycles; + + // AMG W_cycle + bool amg_w_cycles; + + // AMG Smoother sweeps + unsigned int amg_smoother_sweeps; + + // AMG Smoother overalp + unsigned int amg_smoother_overlap; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct Mesh + { + // GMSH or dealii primitive + enum Type + { + gmsh, + primitive + }; + Type type; + + // Primitive types + enum PrimitiveType + { + hyper_cube, + hyper_shell + }; + PrimitiveType primitiveType; + + bool colorize; + + // Parameters for the hyper shell + double hs_inner_radius; + double hs_outer_radius; + + // Parameters for the hyper cube + double hc_left; + double hc_right; + + // File name of the mesh + std::string fileName; + + // Initial refinement level of primitive mesh + unsigned int initialRefinement; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct MeshAdaptation + { + // Type of mesh adaptation + enum Type + { + none, + uniform, + kelly + }; + Type type; + + enum Variable + { + velocity, + pressure + }; + Variable variable; + + // Decision factor for KELLY refinement (number or fraction) + enum FractionType + { + number, + fraction + }; + FractionType fractionType; + + // Maximum number of elements + unsigned int maxNbElements; + + // Maximum refinement level + unsigned int maxRefLevel; + + // Maximum refinement level + unsigned int minRefLevel; + + // Refinement after frequency iter + unsigned int frequency; + + // Refinement fractioni havent used ILUT much) + double fractionRefinement; + + // Coarsening fraction + double fractionCoarsening; + + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct Testing + { + // Time measurement in the simulation. None, at each iteration, only at the + // end + bool enabled; + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; + + struct Restart + { + // Time measurement in the simulation. None, at each iteration, only at the + // end + std::string filename; + bool restart; + bool checkpoint; + unsigned int frequency; + static void + declare_parameters(ParameterHandler &prm); + void + parse_parameters(ParameterHandler &prm); + }; } // namespace Parameters #endif diff --git a/src/postprocessors.h b/src/postprocessors.h index f861e4e6c2..5d4e6d93bb 100644 --- a/src/postprocessors.h +++ b/src/postprocessors.h @@ -19,66 +19,86 @@ using namespace dealii; // Calculates the vorticity within each element using the velocity vector template -class vorticity_postprocessor : public DataPostprocessorVector { +class vorticity_postprocessor : public DataPostprocessorVector +{ public: vorticity_postprocessor() - : DataPostprocessorVector("vorticity", update_gradients) {} - virtual void evaluate_vector_field( - const DataPostprocessorInputs::Vector &input_data, - std::vector> &computed_quantities) const { + : DataPostprocessorVector("vorticity", update_gradients) + {} + virtual void + evaluate_vector_field(const DataPostprocessorInputs::Vector &input_data, + std::vector> &computed_quantities) const + { AssertDimension(input_data.solution_gradients.size(), computed_quantities.size()); - for (unsigned int p = 0; p < input_data.solution_gradients.size(); ++p) { - AssertDimension(computed_quantities[p].size(), dim); - if (dim == 3) { - computed_quantities[p](0) = (input_data.solution_gradients[p][2][1] - - input_data.solution_gradients[p][1][2]); - computed_quantities[p](1) = (input_data.solution_gradients[p][0][2] - - input_data.solution_gradients[p][2][0]); - computed_quantities[p](2) = (input_data.solution_gradients[p][1][0] - - input_data.solution_gradients[p][0][1]); - } else { - computed_quantities[p][0] = (input_data.solution_gradients[p][1][0] - - input_data.solution_gradients[p][0][1]); + for (unsigned int p = 0; p < input_data.solution_gradients.size(); ++p) + { + AssertDimension(computed_quantities[p].size(), dim); + if (dim == 3) + { + computed_quantities[p](0) = + (input_data.solution_gradients[p][2][1] - + input_data.solution_gradients[p][1][2]); + computed_quantities[p](1) = + (input_data.solution_gradients[p][0][2] - + input_data.solution_gradients[p][2][0]); + computed_quantities[p](2) = + (input_data.solution_gradients[p][1][0] - + input_data.solution_gradients[p][0][1]); + } + else + { + computed_quantities[p][0] = + (input_data.solution_gradients[p][1][0] - + input_data.solution_gradients[p][0][1]); + } } - } } }; // Calculate the Q criterion within each element template -class qcriterion_postprocessor : public DataPostprocessorScalar { +class qcriterion_postprocessor : public DataPostprocessorScalar +{ public: qcriterion_postprocessor() - : DataPostprocessorScalar("q_criterion", update_gradients) {} - virtual void evaluate_vector_field( - const DataPostprocessorInputs::Vector &input_data, - std::vector> &computed_quantities) const { - for (unsigned int p = 0; p < input_data.solution_gradients.size(); ++p) { - AssertDimension(computed_quantities[p].size(), 1); - double p1 = 0.0, r1 = 0.0; - std::vector> vorticity_vector( + : DataPostprocessorScalar("q_criterion", update_gradients) + {} + virtual void + evaluate_vector_field(const DataPostprocessorInputs::Vector &input_data, + std::vector> &computed_quantities) const + { + for (unsigned int p = 0; p < input_data.solution_gradients.size(); ++p) + { + AssertDimension(computed_quantities[p].size(), 1); + double p1 = 0.0, r1 = 0.0; + std::vector> vorticity_vector( input_data.solution_gradients.size()); - std::vector> strain_rate_tensor( + std::vector> strain_rate_tensor( input_data.solution_gradients.size()); - for (unsigned int j = 0; j < dim; j++) { - for (unsigned int k = 0; k < dim; k++) { - vorticity_vector[p][j][k] = - 0.5 * ((input_data.solution_gradients[p][j][k]) - - input_data.solution_gradients[p][k][j]); - strain_rate_tensor[p][j][k] = - 0.5 * ((input_data.solution_gradients[p][j][k]) + - input_data.solution_gradients[p][k][j]); - } + for (unsigned int j = 0; j < dim; j++) + { + for (unsigned int k = 0; k < dim; k++) + { + vorticity_vector[p][j][k] = + 0.5 * ((input_data.solution_gradients[p][j][k]) - + input_data.solution_gradients[p][k][j]); + strain_rate_tensor[p][j][k] = + 0.5 * ((input_data.solution_gradients[p][j][k]) + + input_data.solution_gradients[p][k][j]); + } + } + for (unsigned int m = 0; m < dim; m++) + { + for (unsigned int n = 0; n < dim; n++) + { + p1 += (vorticity_vector[p][m][n]) * (vorticity_vector[p][m][n]); + r1 += + (strain_rate_tensor[p][m][n]) * (strain_rate_tensor[p][m][n]); + } + } + computed_quantities[p] = 0.5 * (p1 - r1); } - for (unsigned int m = 0; m < dim; m++) { - for (unsigned int n = 0; n < dim; n++) { - p1 += (vorticity_vector[p][m][n]) * (vorticity_vector[p][m][n]); - r1 += (strain_rate_tensor[p][m][n]) * (strain_rate_tensor[p][m][n]); - } - } - computed_quantities[p] = 0.5 * (p1 - r1); - } } }; diff --git a/src/pvdhandler.cc b/src/pvdhandler.cc index 25108e23db..763aa8d955 100644 --- a/src/pvdhandler.cc +++ b/src/pvdhandler.cc @@ -1,40 +1,48 @@ #include "pvdhandler.h" + #include using namespace dealii; -void PVDHandler::save(std::string prefix) { - std::string filename = prefix + ".pvdhandler"; +void +PVDHandler::save(std::string prefix) +{ + std::string filename = prefix + ".pvdhandler"; std::ofstream output(filename.c_str()); output << times_and_names_.size() << std::endl; output << "Time File" << std::endl; - for (unsigned int i = 0; i < times_and_names_.size(); ++i) { - output << times_and_names_[i].first << " " << times_and_names_[i].second - << std::endl; - } + for (unsigned int i = 0; i < times_and_names_.size(); ++i) + { + output << times_and_names_[i].first << " " << times_and_names_[i].second + << std::endl; + } } -void PVDHandler::read(std::string prefix) { +void +PVDHandler::read(std::string prefix) +{ times_and_names_.clear(); - std::string filename = prefix + ".pvdhandler"; + std::string filename = prefix + ".pvdhandler"; std::ifstream input(filename.c_str()); - if (!input) { - throw("Unable to open file"); - } - std::string buffer; + if (!input) + { + throw("Unable to open file"); + } + std::string buffer; unsigned int size; input >> size; std::getline(input, buffer); std::getline(input, buffer); - for (unsigned int i = 0; i < size; ++i) { - double time; - std::string filename; - input >> time; - input >> filename; - append(time, filename); - } + for (unsigned int i = 0; i < size; ++i) + { + double time; + std::string filename; + input >> time; + input >> filename; + append(time, filename); + } if (size != times_and_names_.size()) throw std::runtime_error("Error when reading pvd restart file "); diff --git a/src/pvdhandler.h b/src/pvdhandler.h index 2a3082f294..a98b9aaea7 100644 --- a/src/pvdhandler.h +++ b/src/pvdhandler.h @@ -6,16 +6,25 @@ using namespace dealii; -class PVDHandler { +class PVDHandler +{ public: std::vector> times_and_names_; - void save(std::string filename); - void read(std::string filename); - void append(double time, std::string pvtu_filename) { + void + save(std::string filename); + void + read(std::string filename); + void + append(double time, std::string pvtu_filename) + { times_and_names_.push_back( - std::pair(time, pvtu_filename)); + std::pair(time, pvtu_filename)); + } + unsigned + size() + { + return times_and_names_.size(); } - unsigned size() { return times_and_names_.size(); } }; #endif diff --git a/src/simulationcontrol.cc b/src/simulationcontrol.cc index 4d94938940..911876c867 100644 --- a/src/simulationcontrol.cc +++ b/src/simulationcontrol.cc @@ -1,35 +1,47 @@ #include "simulationcontrol.h" + #include -void printTime(ConditionalOStream pcout, SimulationControl control) { - if (control.getMethod() == Parameters::SimulationControl::steady) { - pcout << std::endl; - pcout << "*****************************************************************" - "******************" - << std::endl; - pcout << "Steady iteration : " << std::setw(8) << std::right - << control.getIter() << "/" << control.getNbMeshAdapt() + 1 - << std::endl; - pcout << "*****************************************************************" - "******************" - << std::endl; - } else { - pcout << std::endl; - pcout << "*****************************************************************" - "******************" - << std::endl; - pcout << "Transient iteration : " << std::setw(8) << std::left - << control.getIter() << " Time : " << std::setw(8) << std::left - << control.getTime() << " Time step : " << std::setw(8) << std::left - << control.getCurrentTimeStep() << " CFL : " << std::setw(8) - << std::left << control.getCFL() << std::endl; - pcout << "*****************************************************************" - "******************" - << std::endl; - } +void +printTime(ConditionalOStream pcout, SimulationControl control) +{ + if (control.getMethod() == Parameters::SimulationControl::steady) + { + pcout << std::endl; + pcout + << "*****************************************************************" + "******************" + << std::endl; + pcout << "Steady iteration : " << std::setw(8) << std::right + << control.getIter() << "/" << control.getNbMeshAdapt() + 1 + << std::endl; + pcout + << "*****************************************************************" + "******************" + << std::endl; + } + else + { + pcout << std::endl; + pcout + << "*****************************************************************" + "******************" + << std::endl; + pcout << "Transient iteration : " << std::setw(8) << std::left + << control.getIter() << " Time : " << std::setw(8) << std::left + << control.getTime() << " Time step : " << std::setw(8) << std::left + << control.getCurrentTimeStep() << " CFL : " << std::setw(8) + << std::left << control.getCFL() << std::endl; + pcout + << "*****************************************************************" + "******************" + << std::endl; + } } -void SimulationControl::addTimeStep(double p_timestep) { +void +SimulationControl::addTimeStep(double p_timestep) +{ // Store previous time step in table for (unsigned int i_time = dt.size() - 1; i_time > 0; --i_time) dt[i_time] = dt[i_time - 1]; @@ -38,54 +50,68 @@ void SimulationControl::addTimeStep(double p_timestep) { dt[0] = p_timestep; } -bool SimulationControl::integrate() { +bool +SimulationControl::integrate() +{ if ((parameterControl.method == parameterControl.steady && iter >= (nbMeshAdapt + 1)) || (parameterControl.method != parameterControl.steady && time >= (endTime - 1e-6 * dt[0]))) return false; - else { - iter++; - addTimeStep(calculateTimeStep()); - // Increment time - time += dt[0]; - return true; - } + else + { + iter++; + addTimeStep(calculateTimeStep()); + // Increment time + time += dt[0]; + return true; + } } // Calculate the time step depending on the time stepping control parameters -double SimulationControl::calculateTimeStep() { return parameterControl.dt; } +double +SimulationControl::calculateTimeStep() +{ + return parameterControl.dt; +} -void SimulationControl::initialize(ParameterHandler &prm) { +void +SimulationControl::initialize(ParameterHandler &prm) +{ parameterControl.parse_parameters(prm); method = parameterControl.method; // Even if high order time stepping schemes are not used // dt always contains the necessary information to restart // at the highest order method available dt.resize(numberTimeStepStored); - dt[0] = parameterControl.dt; - endTime = parameterControl.timeEnd; - maxCFL = parameterControl.maxCFL; + dt[0] = parameterControl.dt; + endTime = parameterControl.timeEnd; + maxCFL = parameterControl.maxCFL; nbMeshAdapt = parameterControl.nbMeshAdapt; - time = 0; - iter = 0; - CFL = 0; + time = 0; + iter = 0; + CFL = 0; } -void SimulationControl::initialize(Parameters::SimulationControl param) { + +void +SimulationControl::initialize(Parameters::SimulationControl param) +{ parameterControl = param; - method = parameterControl.method; + method = parameterControl.method; dt.resize(numberTimeStepStored); - dt[0] = parameterControl.dt; - endTime = parameterControl.timeEnd; - maxCFL = parameterControl.maxCFL; + dt[0] = parameterControl.dt; + endTime = parameterControl.timeEnd; + maxCFL = parameterControl.maxCFL; nbMeshAdapt = parameterControl.nbMeshAdapt; - time = 0; - iter = 0; - CFL = 0; + time = 0; + iter = 0; + CFL = 0; } -void SimulationControl::save(std::string prefix) { - std::string filename = prefix + ".simulationcontrol"; +void +SimulationControl::save(std::string prefix) +{ + std::string filename = prefix + ".simulationcontrol"; std::ofstream output(filename.c_str()); output << "Simulation control" << std::endl; for (unsigned int i = 0; i < dt.size(); ++i) @@ -95,12 +121,15 @@ void SimulationControl::save(std::string prefix) { output << "Iter " << iter << std::endl; } -void SimulationControl::read(std::string prefix) { - std::string filename = prefix + ".simulationcontrol"; +void +SimulationControl::read(std::string prefix) +{ + std::string filename = prefix + ".simulationcontrol"; std::ifstream input(filename.c_str()); - if (!input) { - throw("Unable to open file"); - } + if (!input) + { + throw("Unable to open file"); + } std::string buffer; std::getline(input, buffer); for (unsigned int i = 0; i < dt.size(); ++i) diff --git a/src/simulationcontrol.h b/src/simulationcontrol.h index 9ecbaa8d0b..37d1e6a5c4 100644 --- a/src/simulationcontrol.h +++ b/src/simulationcontrol.h @@ -4,7 +4,8 @@ #include "parameters.h" -class SimulationControl { +class SimulationControl +{ // Time step std::vector dt; // CFL @@ -25,10 +26,12 @@ class SimulationControl { static const unsigned int numberTimeStepStored = 4; // Calculate time step based on either CFL or fixed; - double calculateTimeStep(); + double + calculateTimeStep(); // Add a time step and stores the previous one in a list - void addTimeStep(double p_timestep); + void + addTimeStep(double p_timestep); // Time stepping method Parameters::SimulationControl::TimeSteppingMethod method; @@ -38,45 +41,117 @@ class SimulationControl { Parameters::SimulationControl parameterControl; public: - void initialize(ParameterHandler &prm); - void initialize(Parameters::SimulationControl param); - - Parameters::SimulationControl::TimeSteppingMethod getMethod() { + void + initialize(ParameterHandler &prm); + void + initialize(Parameters::SimulationControl param); + + Parameters::SimulationControl::TimeSteppingMethod + getMethod() + { return method; } - void setMethod(Parameters::SimulationControl::TimeSteppingMethod p_method) { + void + setMethod(Parameters::SimulationControl::TimeSteppingMethod p_method) + { method = p_method; } - std::string getOuputName() { return parameterControl.output_name; } - std::string getOutputFolder() { return parameterControl.output_folder; } + std::string + getOuputName() + { + return parameterControl.output_name; + } + std::string + getOutputFolder() + { + return parameterControl.output_folder; + } - void setTimeStep(double p_timestep) { addTimeStep(p_timestep); } - double getCurrentTimeStep() { return dt[0]; } - std::vector getTimeSteps() { return dt; } - double getTime() { return time; } - double getEndTime() { return endTime; } + void + setTimeStep(double p_timestep) + { + addTimeStep(p_timestep); + } + double + getCurrentTimeStep() + { + return dt[0]; + } + std::vector + getTimeSteps() + { + return dt; + } + double + getTime() + { + return time; + } + double + getEndTime() + { + return endTime; + } - unsigned int getIter() { return iter; } - bool firstIter() { return iter == 1; } - double getCFL() { return CFL; } - void setCFL(double p_CFL) { CFL = p_CFL; } - double getMaxCFL() { return maxCFL; } - Parameters::SimulationControl getParameters() { return parameterControl; } + unsigned int + getIter() + { + return iter; + } + bool + firstIter() + { + return iter == 1; + } + double + getCFL() + { + return CFL; + } + void + setCFL(double p_CFL) + { + CFL = p_CFL; + } + double + getMaxCFL() + { + return maxCFL; + } + Parameters::SimulationControl + getParameters() + { + return parameterControl; + } - unsigned int getNbMeshAdapt() { return nbMeshAdapt; } - unsigned int getSubdivision() { return parameterControl.subdivision; } + unsigned int + getNbMeshAdapt() + { + return nbMeshAdapt; + } + unsigned int + getSubdivision() + { + return parameterControl.subdivision; + } - bool isOutputIteration() { + bool + isOutputIteration() + { return (iter % parameterControl.outputFrequency == 0); } - bool integrate(); + bool + integrate(); - void save(std::string filename); - void read(std::string filename); + void + save(std::string filename); + void + read(std::string filename); }; -void printTime(ConditionalOStream pcout, SimulationControl control); +void +printTime(ConditionalOStream pcout, SimulationControl control); #endif diff --git a/tests/bdf/bdf_01.cc b/tests/bdf/bdf_01.cc index e9ff0f1f1e..dc8ffd08cd 100644 --- a/tests/bdf/bdf_01.cc +++ b/tests/bdf/bdf_01.cc @@ -3,68 +3,76 @@ #include "../tests.h" #include "bdf.h" -int main(int argc, char *argv[]) { - try { - initlog(); - std::vector dt(5, 0.1); - dt[1] = 0.2; - dt[2] = 0.3; - dt[3] = 0.4; - dt[4] = 0.5; - deallog << "Time steps "; - for (unsigned int i = 0; i < dt.size(); ++i) { - deallog << dt[i] << " "; - } - deallog << std::endl; +int +main(int argc, char *argv[]) +{ + try + { + initlog(); + std::vector dt(5, 0.1); + dt[1] = 0.2; + dt[2] = 0.3; + dt[3] = 0.4; + dt[4] = 0.5; + deallog << "Time steps "; + for (unsigned int i = 0; i < dt.size(); ++i) + { + deallog << dt[i] << " "; + } + deallog << std::endl; - Vector order1_coefficients = bdf_coefficients(1, dt); - if (!approximatelyEqual(order1_coefficients[0], 10., 1e-8)) - throw std::runtime_error("Error order 1 term 0"); - if (!approximatelyEqual(order1_coefficients[1], -10., 1e-8)) - throw std::runtime_error("Error order 1 term 1"); - deallog << "Order 1 : " << order1_coefficients << std::endl; + Vector order1_coefficients = bdf_coefficients(1, dt); + if (!approximatelyEqual(order1_coefficients[0], 10., 1e-8)) + throw std::runtime_error("Error order 1 term 0"); + if (!approximatelyEqual(order1_coefficients[1], -10., 1e-8)) + throw std::runtime_error("Error order 1 term 1"); + deallog << "Order 1 : " << order1_coefficients << std::endl; - Vector order2_coefficients = bdf_coefficients(2, dt); - if (!approximatelyEqual(order2_coefficients[0], 13.3333333333333, 1e-8)) - throw std::runtime_error("Error order 2 term 0"); - if (!approximatelyEqual(order2_coefficients[1], -15.0000000000000, 1e-8)) - throw std::runtime_error("Error order 2 term 1"); - if (!approximatelyEqual(order2_coefficients[2], 1.66666666666667, 1e-8)) - throw std::runtime_error("Error order 2 term 2"); - deallog << "Order 2 : " << order2_coefficients << std::endl; + Vector order2_coefficients = bdf_coefficients(2, dt); + if (!approximatelyEqual(order2_coefficients[0], 13.3333333333333, 1e-8)) + throw std::runtime_error("Error order 2 term 0"); + if (!approximatelyEqual(order2_coefficients[1], -15.0000000000000, 1e-8)) + throw std::runtime_error("Error order 2 term 1"); + if (!approximatelyEqual(order2_coefficients[2], 1.66666666666667, 1e-8)) + throw std::runtime_error("Error order 2 term 2"); + deallog << "Order 2 : " << order2_coefficients << std::endl; - Vector order3_coefficients = bdf_coefficients(3, dt); - if (!approximatelyEqual(order3_coefficients[0], 15.0000000000000, 1e-8)) - throw std::runtime_error("Error order 3 term 0"); - if (!approximatelyEqual(order3_coefficients[1], -18.0000000000000, 1e-8)) - throw std::runtime_error("Error order 3 term 1"); - if (!approximatelyEqual(order3_coefficients[2], 3.33333333333333, 1e-8)) - throw std::runtime_error("Error order 3 term 2"); - if (!approximatelyEqual(order3_coefficients[3], -0.333333333333333, 1e-8)) - throw std::runtime_error("Error order 3 term 3"); - deallog << "Order 3 : " << order3_coefficients << std::endl; - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + Vector order3_coefficients = bdf_coefficients(3, dt); + if (!approximatelyEqual(order3_coefficients[0], 15.0000000000000, 1e-8)) + throw std::runtime_error("Error order 3 term 0"); + if (!approximatelyEqual(order3_coefficients[1], -18.0000000000000, 1e-8)) + throw std::runtime_error("Error order 3 term 1"); + if (!approximatelyEqual(order3_coefficients[2], 3.33333333333333, 1e-8)) + throw std::runtime_error("Error order 3 term 2"); + if (!approximatelyEqual(order3_coefficients[3], -0.333333333333333, 1e-8)) + throw std::runtime_error("Error order 3 term 3"); + deallog << "Order 3 : " << order3_coefficients << std::endl; + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/tests/pvdhandler/pvdhandler_01.cc b/tests/pvdhandler/pvdhandler_01.cc index 8493540453..342c13edd8 100644 --- a/tests/pvdhandler/pvdhandler_01.cc +++ b/tests/pvdhandler/pvdhandler_01.cc @@ -3,57 +3,65 @@ #include "../tests.h" #include "pvdhandler.h" -int main() { - try { - initlog(); +int +main() +{ + try + { + initlog(); - deallog << "Beggining" << std::endl; + deallog << "Beggining" << std::endl; - PVDHandler pvdhandlerMaster; + PVDHandler pvdhandlerMaster; - pvdhandlerMaster.append(0.03, "test1"); - pvdhandlerMaster.append(2.00, "test2"); - pvdhandlerMaster.append(7.00, "test3"); - pvdhandlerMaster.save("restart"); + pvdhandlerMaster.append(0.03, "test1"); + pvdhandlerMaster.append(2.00, "test2"); + pvdhandlerMaster.append(7.00, "test3"); + pvdhandlerMaster.save("restart"); - PVDHandler pvdhandlerWorker; - pvdhandlerWorker.read("restart"); + PVDHandler pvdhandlerWorker; + pvdhandlerWorker.read("restart"); - if (pvdhandlerWorker.size() != pvdhandlerMaster.size()) - throw std::runtime_error("Size are not equal"); - unsigned int size = pvdhandlerWorker.size(); - for (unsigned int i = 0; i < size; ++i) { - deallog << pvdhandlerWorker.times_and_names_[i].first << " " - << pvdhandlerWorker.times_and_names_[i].second << std::endl; - if (!approximatelyEqual(pvdhandlerMaster.times_and_names_[i].first, - pvdhandlerWorker.times_and_names_[i].first, 1e-8)) - throw std::runtime_error("Time not equal"); - if (pvdhandlerMaster.times_and_names_[i].second != - pvdhandlerWorker.times_and_names_[i].second) - throw std::runtime_error("File not equal"); + if (pvdhandlerWorker.size() != pvdhandlerMaster.size()) + throw std::runtime_error("Size are not equal"); + unsigned int size = pvdhandlerWorker.size(); + for (unsigned int i = 0; i < size; ++i) + { + deallog << pvdhandlerWorker.times_and_names_[i].first << " " + << pvdhandlerWorker.times_and_names_[i].second << std::endl; + if (!approximatelyEqual(pvdhandlerMaster.times_and_names_[i].first, + pvdhandlerWorker.times_and_names_[i].first, + 1e-8)) + throw std::runtime_error("Time not equal"); + if (pvdhandlerMaster.times_and_names_[i].second != + pvdhandlerWorker.times_and_names_[i].second) + throw std::runtime_error("File not equal"); + } + deallog << "OK" << std::endl; + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; } - deallog << "OK" << std::endl; - - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } } diff --git a/tests/restart/restart_01.cc b/tests/restart/restart_01.cc index 087b59c152..715ab2c8b4 100644 --- a/tests/restart/restart_01.cc +++ b/tests/restart/restart_01.cc @@ -1,28 +1,33 @@ // check the read and write of simulationcontrol #include "../tests.h" +#include "glsNS.h" #include "navierstokessolverparameters.h" #include "parameters.h" #include "simulationcontrol.h" -#include "glsNS.h" - template -class RestartNavierStokes : public GLSNavierStokesSolver { +class RestartNavierStokes : public GLSNavierStokesSolver +{ public: RestartNavierStokes(NavierStokesSolverParameters nsparam, - const unsigned int degreeVelocity, - const unsigned int degreePressure) - : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) {} - void run(); + const unsigned int degreeVelocity, + const unsigned int degreePressure) + : GLSNavierStokesSolver(nsparam, degreeVelocity, degreePressure) + {} + void + run(); }; -template void RestartNavierStokes::run() { +template +void +RestartNavierStokes::run() +{ const int initialSize = 4; this->make_cube_grid(initialSize); this->setup_dofs(); - this->exact_solution = new ExactSolutionMMS; - this->forcing_function = new MMSSineForcingFunction; + this->exact_solution = new ExactSolutionMMS; + this->forcing_function = new MMSSineForcingFunction; this->nsparam.physicalProperties.viscosity = 1.; printTime(this->pcout, this->simulationControl); @@ -51,50 +56,57 @@ template void RestartNavierStokes::run() { std::runtime_error("Reloaded solution is not the same"); } -int main(int argc, char *argv[]) { - try { - initlog(); - Utilities::MPI::MPI_InitFinalize mpi_initialization( +int +main(int argc, char *argv[]) +{ + try + { + initlog(); + Utilities::MPI::MPI_InitFinalize mpi_initialization( argc, argv, numbers::invalid_unsigned_int); - ParameterHandler prm; - NavierStokesSolverParameters<2> NSparam; - NSparam.declare(prm); - NSparam.parse(prm); + ParameterHandler prm; + NavierStokesSolverParameters<2> NSparam; + NSparam.declare(prm); + NSparam.parse(prm); - // Manually alter some of the default parameters of the solver - NSparam.restartParameters.checkpoint = true; - NSparam.restartParameters.frequency = 1; - NSparam.nonLinearSolver.verbosity = Parameters::NonLinearSolver::quiet; - NSparam.linearSolver.verbosity = Parameters::LinearSolver::quiet; - NSparam.boundaryConditions.createDefaultNoSlip(); + // Manually alter some of the default parameters of the solver + NSparam.restartParameters.checkpoint = true; + NSparam.restartParameters.frequency = 1; + NSparam.nonLinearSolver.verbosity = Parameters::NonLinearSolver::quiet; + NSparam.linearSolver.verbosity = Parameters::LinearSolver::quiet; + NSparam.boundaryConditions.createDefaultNoSlip(); - RestartNavierStokes<2> problem_2d(NSparam, - NSparam.femParameters.velocityOrder, - NSparam.femParameters.pressureOrder); - problem_2d.run(); - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + RestartNavierStokes<2> problem_2d(NSparam, + NSparam.femParameters.velocityOrder, + NSparam.femParameters.pressureOrder); + problem_2d.run(); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } return 0; } diff --git a/tests/simulationcontrol/simulationcontrol_01.cc b/tests/simulationcontrol/simulationcontrol_01.cc index 620898bba3..08ad2d3b9e 100644 --- a/tests/simulationcontrol/simulationcontrol_01.cc +++ b/tests/simulationcontrol/simulationcontrol_01.cc @@ -5,77 +5,85 @@ #include "parameters.h" #include "simulationcontrol.h" -int main() { - try { +int +main() +{ + try + { + initlog(); - initlog(); + Parameters::SimulationControl simulationControlParameters; + simulationControlParameters.dt = 0.01; + simulationControlParameters.adapt = false; + simulationControlParameters.maxCFL = 99; + simulationControlParameters.method = simulationControlParameters.bdf1; + simulationControlParameters.timeEnd = 999; + simulationControlParameters.nbMeshAdapt = 9; + simulationControlParameters.output_name = "test"; + simulationControlParameters.subdivision = 7; + simulationControlParameters.output_folder = "canard"; + simulationControlParameters.outputFrequency = 8; - Parameters::SimulationControl simulationControlParameters; - simulationControlParameters.dt = 0.01; - simulationControlParameters.adapt = false; - simulationControlParameters.maxCFL = 99; - simulationControlParameters.method = simulationControlParameters.bdf1; - simulationControlParameters.timeEnd = 999; - simulationControlParameters.nbMeshAdapt = 9; - simulationControlParameters.output_name = "test"; - simulationControlParameters.subdivision = 7; - simulationControlParameters.output_folder = "canard"; - simulationControlParameters.outputFrequency = 8; + SimulationControl simulationControl; + simulationControl.initialize(simulationControlParameters); - SimulationControl simulationControl; - simulationControl.initialize(simulationControlParameters); + for (int i = 0; i < 10; ++i) + simulationControl.integrate(); - for (int i = 0; i < 10; ++i) - simulationControl.integrate(); + if (simulationControl.getIter() != 10) + std::runtime_error("Iteration number is wrong - before"); + if (!approximatelyEqual(simulationControl.getTime(), 0.1, 1e-10)) + std::runtime_error("Run time is wrong - before"); + if (!approximatelyEqual(simulationControl.getCurrentTimeStep(), + 0.01, + 1e-10)) + std::runtime_error("Time step is wrong - before"); - if (simulationControl.getIter() != 10) - std::runtime_error("Iteration number is wrong - before"); - if (!approximatelyEqual(simulationControl.getTime(), 0.1, 1e-10)) - std::runtime_error("Run time is wrong - before"); - if (!approximatelyEqual(simulationControl.getCurrentTimeStep(), 0.01, - 1e-10)) - std::runtime_error("Time step is wrong - before"); + simulationControl.save("testFile"); + simulationControl.read("testFile"); - simulationControl.save("testFile"); - simulationControl.read("testFile"); + if (simulationControl.getIter() != 10) + std::runtime_error("Iteration number is wrong - after"); + if (!approximatelyEqual(simulationControl.getTime(), 0.1, 1e-10)) + std::runtime_error("Run time is wrong - after"); + if (!approximatelyEqual(simulationControl.getCurrentTimeStep(), + 0.01, + 1e-10)) + std::runtime_error("Time step is wrong - after"); - if (simulationControl.getIter() != 10) - std::runtime_error("Iteration number is wrong - after"); - if (!approximatelyEqual(simulationControl.getTime(), 0.1, 1e-10)) - std::runtime_error("Run time is wrong - after"); - if (!approximatelyEqual(simulationControl.getCurrentTimeStep(), 0.01, - 1e-10)) - std::runtime_error("Time step is wrong - after"); - - deallog << "dt : " - << simulationControl.getCurrentTimeStep() << std::endl; - deallog << "CFL : " << simulationControl.getCFL() - << std::endl; - deallog << "time : " << simulationControl.getTime() - << std::endl; - deallog << "iter : " << simulationControl.getIter() - << std::endl; - deallog << "OK" << std::endl; - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" + deallog << "dt : " + << simulationControl.getCurrentTimeStep() << std::endl; + deallog << "CFL : " << simulationControl.getCFL() << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" + deallog << "time : " << simulationControl.getTime() << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" + deallog << "iter : " << simulationControl.getIter() << std::endl; - return 1; - } + deallog << "OK" << std::endl; + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } } diff --git a/tests/template_parameters/template_glsns.cc b/tests/template_parameters/template_glsns.cc index 5729d9a3cf..6cd2d8e229 100644 --- a/tests/template_parameters/template_glsns.cc +++ b/tests/template_parameters/template_glsns.cc @@ -3,40 +3,46 @@ #include "../tests.h" #include "navierstokessolverparameters.h" -int main() { - try { - initlog(); +int +main() +{ + try + { + initlog(); - deallog << "Beggining" << std::endl; - ParameterHandler prm; - NavierStokesSolverParameters<2> nsparam; - nsparam.declare(prm); - std::ofstream output_prm("template.prm"); - prm.print_parameters(output_prm, prm.Text); + deallog << "Beggining" << std::endl; + ParameterHandler prm; + NavierStokesSolverParameters<2> nsparam; + nsparam.declare(prm); + std::ofstream output_prm("template.prm"); + prm.print_parameters(output_prm, prm.Text); - std::ofstream output_xml("template.xml"); - prm.print_parameters(output_xml, prm.XML); - - } catch (std::exception &exc) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Exception on processing: " << std::endl - << exc.what() << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } catch (...) { - std::cerr << std::endl - << std::endl - << "----------------------------------------------------" - << std::endl; - std::cerr << "Unknown exception!" << std::endl - << "Aborting!" << std::endl - << "----------------------------------------------------" - << std::endl; - return 1; - } + std::ofstream output_xml("template.xml"); + prm.print_parameters(output_xml, prm.XML); + } + catch (std::exception &exc) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } + catch (...) + { + std::cerr << std::endl + << std::endl + << "----------------------------------------------------" + << std::endl; + std::cerr << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + } } diff --git a/tests/tests.h b/tests/tests.h index d620e20c56..43f0cd45b2 100644 --- a/tests/tests.h +++ b/tests/tests.h @@ -40,7 +40,7 @@ #include #if defined(DEBUG) && defined(DEAL_II_HAVE_FP_EXCEPTIONS) -#include +# include #endif // silence extra diagnostics in the testsuite @@ -51,10 +51,12 @@ DEAL_II_DISABLE_EXTRA_DIAGNOSTICS #ifdef DEAL_II_MSVC // Under windows tests will hang and show a debugging dialog box from the // debug CRT if an exception is encountered. Disable this: -#include +# include -struct DisableWindowsDebugRuntimeDialog { - DisableWindowsDebugRuntimeDialog() { +struct DisableWindowsDebugRuntimeDialog +{ + DisableWindowsDebugRuntimeDialog() + { _set_abort_behavior(0, _WRITE_ABORT_MSG); } } deal_II_windows_crt_dialog; @@ -70,32 +72,40 @@ using namespace dealii; * Go through the input stream @p in and filter out binary data for the key @p * key . The filtered stream is returned in @p out. */ -void filter_out_xml_key(std::istream &in, const std::string &key, - std::ostream &out) { - std::string line; - bool found = false; +void +filter_out_xml_key(std::istream &in, const std::string &key, std::ostream &out) +{ + std::string line; + bool found = false; const std::string opening = "<" + key; const std::string closing = "" but keep things after "", 0) + 1) + line.substr(pos); - found = false; - } else - line = line.substr(0, line.find(">", 0) + 1); - out << line << std::endl; - } else if (line.find(closing) != std::string::npos) { - found = false; - // remove everything before "<" - line = line.substr(line.find("<", 0)); - out << line << std::endl; - } else if (!found) - out << line << std::endl; - } + while (std::getline(in, line)) + { + if (line.find(opening) != std::string::npos && + line.find("binary") != std::string::npos) + { + found = true; + // remove everything after ">" but keep things after "", 0) + 1) + line.substr(pos); + found = false; + } + else + line = line.substr(0, line.find(">", 0) + 1); + out << line << std::endl; + } + else if (line.find(closing) != std::string::npos) + { + found = false; + // remove everything before "<" + line = line.substr(line.find("<", 0)); + out << line << std::endl; + } + else if (!found) + out << line << std::endl; + } } /** @@ -103,21 +113,27 @@ void filter_out_xml_key(std::istream &in, const std::string &key, * its imaginary part is zero. */ #ifdef DEAL_II_WITH_PETSC -#include +# include PetscReal -get_real_assert_zero_imag(const PETScWrappers::internal::VectorReference &a) { +get_real_assert_zero_imag(const PETScWrappers::internal::VectorReference &a) +{ Assert(a.imag() == 0.0, ExcInternalError()); return a.real(); } #endif template -number get_real_assert_zero_imag(const std::complex &a) { +number +get_real_assert_zero_imag(const std::complex &a) +{ Assert(a.imag() == 0.0, ExcInternalError()); return a.real(); } -template number get_real_assert_zero_imag(const number &a) { +template +number +get_real_assert_zero_imag(const number &a) +{ return a; } @@ -125,92 +141,109 @@ template number get_real_assert_zero_imag(const number &a) { // fail. This here is a reimplementation that gives the same sequence of numbers // as a program that uses rand() on a typical linux machine. we put this into a // namespace to not conflict with stdlib -namespace Testing { -/** - * This function defines how to deal with signed overflow, which is undefined - * behavior otherwise, in sums. Since unsigned overflow is well-defined there - * is no reason to resort to this function. - * The way we want to define the overflow is the following: - * The value after the maximal value is the minimal one and the value - * before the minimal one is the maximal one. Hence, we have to distinguish - * three cases: - * 1. $a+b>max$: This can only happen if both @p a and @p b are positive. By - * adding $min-max-1$ we are mapping $max+n$ to $min+n-1$ for - * $n>1$. - * 2. $a+b1$. - * 3. $min<=a+b<=max$: No overflow. - */ -template Number nonoverflow_add(Number a, Number b) { - constexpr Number max = std::numeric_limits::max(); - constexpr Number min = std::numeric_limits::min(); - if (b > 0 && a > max - b) - return (min + a) + (b - max) - 1; - if (b < 0 && a < min - b) - return (max + a) + (b - min) + 1; - return a + b; -} +namespace Testing +{ + /** + * This function defines how to deal with signed overflow, which is undefined + * behavior otherwise, in sums. Since unsigned overflow is well-defined there + * is no reason to resort to this function. + * The way we want to define the overflow is the following: + * The value after the maximal value is the minimal one and the value + * before the minimal one is the maximal one. Hence, we have to distinguish + * three cases: + * 1. $a+b>max$: This can only happen if both @p a and @p b are positive. By + * adding $min-max-1$ we are mapping $max+n$ to $min+n-1$ for + * $n>1$. + * 2. $a+b1$. + * 3. $min<=a+b<=max$: No overflow. + */ + template + Number + nonoverflow_add(Number a, Number b) + { + constexpr Number max = std::numeric_limits::max(); + constexpr Number min = std::numeric_limits::min(); + if (b > 0 && a > max - b) + return (min + a) + (b - max) - 1; + if (b < 0 && a < min - b) + return (max + a) + (b - min) + 1; + return a + b; + } -int rand(const bool reseed = false, const int seed = 1) { - static int r[32]; - static int k; - static bool inited = false; - - if (!inited || reseed) { - // srand treats a seed 0 as 1 for some reason - r[0] = (seed == 0) ? 1 : seed; - long int word = r[0]; - - for (int i = 1; i < 31; i++) { - // This does: - // r[i] = (16807 * r[i-1]) % 2147483647; - // but avoids overflowing 31 bits. - const long int hi = word / 127773; - const long int lo = word % 127773; - word = 16807 * lo - 2836 * hi; - if (word < 0) - word += 2147483647; - r[i] = word; - } - k = 31; - for (int i = 31; i < 34; i++) { - r[k % 32] = r[(k + 32 - 31) % 32]; - k = (k + 1) % 32; - } + int + rand(const bool reseed = false, const int seed = 1) + { + static int r[32]; + static int k; + static bool inited = false; - for (int i = 34; i < 344; i++) { - r[k % 32] = nonoverflow_add(r[(k + 32 - 31) % 32], r[(k + 32 - 3) % 32]); - k = (k + 1) % 32; - } - inited = true; - if (reseed == true) - return 0; // do not generate new no - } + if (!inited || reseed) + { + // srand treats a seed 0 as 1 for some reason + r[0] = (seed == 0) ? 1 : seed; + long int word = r[0]; + + for (int i = 1; i < 31; i++) + { + // This does: + // r[i] = (16807 * r[i-1]) % 2147483647; + // but avoids overflowing 31 bits. + const long int hi = word / 127773; + const long int lo = word % 127773; + word = 16807 * lo - 2836 * hi; + if (word < 0) + word += 2147483647; + r[i] = word; + } + k = 31; + for (int i = 31; i < 34; i++) + { + r[k % 32] = r[(k + 32 - 31) % 32]; + k = (k + 1) % 32; + } + + for (int i = 34; i < 344; i++) + { + r[k % 32] = + nonoverflow_add(r[(k + 32 - 31) % 32], r[(k + 32 - 3) % 32]); + k = (k + 1) % 32; + } + inited = true; + if (reseed == true) + return 0; // do not generate new no + } - r[k % 32] = nonoverflow_add(r[(k + 32 - 31) % 32], r[(k + 32 - 3) % 32]); - int ret = r[k % 32]; - k = (k + 1) % 32; - return static_cast(ret) >> 1; -} + r[k % 32] = nonoverflow_add(r[(k + 32 - 31) % 32], r[(k + 32 - 3) % 32]); + int ret = r[k % 32]; + k = (k + 1) % 32; + return static_cast(ret) >> 1; + } -// reseed our random number generator -void srand(const int seed) { rand(true, seed); } + // reseed our random number generator + void + srand(const int seed) + { + rand(true, seed); + } } // namespace Testing // Get a uniformly distributed random value between min and max template -T random_value(const T &min = static_cast(0), - const T &max = static_cast(1)) { +T +random_value(const T &min = static_cast(0), const T &max = static_cast(1)) +{ return min + (max - min) * - (static_cast(Testing::rand()) / static_cast(RAND_MAX)); + (static_cast(Testing::rand()) / static_cast(RAND_MAX)); } // Construct a uniformly distributed random point, with each coordinate // between min and max template -inline Point random_point(const double &min = 0.0, - const double &max = 1.0) { +inline Point +random_point(const double &min = 0.0, const double &max = 1.0) +{ Assert(max >= min, ExcMessage("Make sure max>=min")); Point p; for (unsigned int i = 0; i < dim; ++i) @@ -220,15 +253,18 @@ inline Point random_point(const double &min = 0.0, // given the name of a file, copy it to deallog // and then delete it -void cat_file(const char *filename) { +void +cat_file(const char *filename) +{ std::ifstream in(filename); Assert(in, dealii::ExcIO()); - while (in) { - std::string s; - std::getline(in, s); - dealii::deallog.get_file_stream() << s << "\n"; - } + while (in) + { + std::string s; + std::getline(in, s); + dealii::deallog.get_file_stream() << s << "\n"; + } in.close(); std::remove(filename); @@ -242,16 +278,21 @@ void cat_file(const char *filename) { * This function does just that with the file given. All streams writing * to this should be closed when calling this function. */ -void sort_file_contents(const std::string &filename) { +void +sort_file_contents(const std::string &filename) +{ int error = std::system( - (std::string("LC_ALL=C sort ") + filename + " -o " + filename).c_str()); + (std::string("LC_ALL=C sort ") + filename + " -o " + filename).c_str()); AssertThrow(error == 0, ExcInternalError()); } /* * simple ADLER32 checksum for a range of chars */ -template unsigned int checksum(const IT &begin, const IT &end) { +template +unsigned int +checksum(const IT &begin, const IT &end) +{ AssertThrow(sizeof(unsigned int) == 4, ExcInternalError()); AssertThrow(sizeof(*begin) == 1, ExcInternalError()); @@ -260,11 +301,12 @@ template unsigned int checksum(const IT &begin, const IT &end) { IT it = begin; - while (it != end) { - a = (a + static_cast(*it)) % 65521; - b = (a + b) % 65521; - ++it; - } + while (it != end) + { + a = (a + static_cast(*it)) % 65521; + b = (a + b) % 65521; + ++it; + } return (b << 16) | a; } @@ -276,13 +318,15 @@ template unsigned int checksum(const IT &begin, const IT &end) { * Also, while GCC prepends the name by "virtual " if the function is virtual, * Intel's ICC does not do that, so filter that out as well. */ -std::string unify_pretty_function(const std::string &text) { +std::string +unify_pretty_function(const std::string &text) +{ std::string t = text; - t = Utilities::replace_in_string(t, " &", " & "); - t = Utilities::replace_in_string(t, " & ,", "&,"); - t = Utilities::replace_in_string(t, " & )", "&)"); - t = Utilities::replace_in_string(t, " & ", "& "); - t = Utilities::replace_in_string(t, "virtual ", ""); + t = Utilities::replace_in_string(t, " &", " & "); + t = Utilities::replace_in_string(t, " & ,", "&,"); + t = Utilities::replace_in_string(t, " & )", "&)"); + t = Utilities::replace_in_string(t, " & ", "& "); + t = Utilities::replace_in_string(t, "virtual ", ""); return t; } @@ -295,23 +339,30 @@ std::string unify_pretty_function(const std::string &text) { * steps. */ -#define check_solver_within_range(SolverType_COMMAND, CONTROL_COMMAND, \ - MIN_ALLOWED, MAX_ALLOWED) \ - { \ - const unsigned int previous_depth = deallog.depth_file(0); \ - try { \ - SolverType_COMMAND; \ - } catch (SolverControl::NoConvergence & exc) { \ - } \ - deallog.depth_file(previous_depth); \ - const unsigned int steps = CONTROL_COMMAND; \ - if (steps >= MIN_ALLOWED && steps <= MAX_ALLOWED) { \ - deallog << "Solver stopped within " << MIN_ALLOWED << " - " \ - << MAX_ALLOWED << " iterations" << std::endl; \ - } else { \ - deallog << "Solver stopped after " << steps << " iterations" \ - << std::endl; \ - } \ +#define check_solver_within_range(SolverType_COMMAND, \ + CONTROL_COMMAND, \ + MIN_ALLOWED, \ + MAX_ALLOWED) \ + { \ + const unsigned int previous_depth = deallog.depth_file(0); \ + try \ + { \ + SolverType_COMMAND; \ + } \ + catch (SolverControl::NoConvergence & exc) \ + {} \ + deallog.depth_file(previous_depth); \ + const unsigned int steps = CONTROL_COMMAND; \ + if (steps >= MIN_ALLOWED && steps <= MAX_ALLOWED) \ + { \ + deallog << "Solver stopped within " << MIN_ALLOWED << " - " \ + << MAX_ALLOWED << " iterations" << std::endl; \ + } \ + else \ + { \ + deallog << "Solver stopped after " << steps << " iterations" \ + << std::endl; \ + } \ } /* @@ -321,7 +372,9 @@ std::string unify_pretty_function(const std::string &text) { * have set for numdiff (that is appropriate for double variables). */ template -Number filter_out_small_numbers(const Number number, const double tolerance) { +Number +filter_out_small_numbers(const Number number, const double tolerance) +{ if (std::abs(number) < tolerance) return Number(); else @@ -336,49 +389,61 @@ Number filter_out_small_numbers(const Number number, const double tolerance) { * Limit concurrency to a fixed (small) number of threads, independent * of the core count. */ -inline unsigned int testing_max_num_threads() { return 3; } +inline unsigned int +testing_max_num_threads() +{ + return 3; +} -struct LimitConcurrency { - LimitConcurrency() { +struct LimitConcurrency +{ + LimitConcurrency() + { MultithreadInfo::set_thread_limit(testing_max_num_threads()); } } limit_concurrency; #ifdef DEAL_II_WITH_PETSC -#include - -namespace { -void check_petsc_allocations() { -#if DEAL_II_PETSC_VERSION_GTE(3, 2, 0) - PetscStageLog stageLog; - PetscLogGetStageLog(&stageLog); - - // I don't quite understand petsc and it looks like - // stageLog->stageInfo->classLog->classInfo[i].id is always -1, so we look - // it up in stageLog->classLog, make sure it has the same number of entries: - Assert(stageLog->stageInfo->classLog->numClasses == +# include + +namespace +{ + void + check_petsc_allocations() + { +# if DEAL_II_PETSC_VERSION_GTE(3, 2, 0) + PetscStageLog stageLog; + PetscLogGetStageLog(&stageLog); + + // I don't quite understand petsc and it looks like + // stageLog->stageInfo->classLog->classInfo[i].id is always -1, so we look + // it up in stageLog->classLog, make sure it has the same number of entries: + Assert(stageLog->stageInfo->classLog->numClasses == stageLog->classLog->numClasses, - dealii::ExcInternalError()); - - bool errors = false; - for (int i = 0; i < stageLog->stageInfo->classLog->numClasses; ++i) { - if (stageLog->stageInfo->classLog->classInfo[i].destructions != - stageLog->stageInfo->classLog->classInfo[i].creations) { - errors = true; - std::cerr << "ERROR: PETSc objects leaking of type '" - << stageLog->classLog->classInfo[i].name << "'" - << " with " - << stageLog->stageInfo->classLog->classInfo[i].creations - << " creations and only " - << stageLog->stageInfo->classLog->classInfo[i].destructions - << " destructions." << std::endl; - } - } + dealii::ExcInternalError()); - if (errors) - throw dealii::ExcMessage("PETSc memory leak"); -#endif -} + bool errors = false; + for (int i = 0; i < stageLog->stageInfo->classLog->numClasses; ++i) + { + if (stageLog->stageInfo->classLog->classInfo[i].destructions != + stageLog->stageInfo->classLog->classInfo[i].creations) + { + errors = true; + std::cerr + << "ERROR: PETSc objects leaking of type '" + << stageLog->classLog->classInfo[i].name << "'" + << " with " + << stageLog->stageInfo->classLog->classInfo[i].creations + << " creations and only " + << stageLog->stageInfo->classLog->classInfo[i].destructions + << " destructions." << std::endl; + } + } + + if (errors) + throw dealii::ExcMessage("PETSc memory leak"); +# endif + } } // namespace #endif @@ -390,12 +455,14 @@ void check_petsc_allocations() { // This will open the correct output file, divert log output there and // switch off screen output. If screen output is desired, provide the // optional first argument as 'true'. -std::string deallogname; +std::string deallogname; std::ofstream deallogfile; -void initlog(bool console = false, - const std::ios_base::fmtflags flags = std::ios::showpoint | - std::ios::left) { +void +initlog(bool console = false, + const std::ios_base::fmtflags flags = std::ios::showpoint | + std::ios::left) +{ deallogname = "output"; deallogfile.open(deallogname.c_str()); deallog.attach(deallogfile, true, flags); @@ -403,17 +470,19 @@ void initlog(bool console = false, } inline void -mpi_initlog(const bool console = false, - const std::ios_base::fmtflags flags = std::ios::showpoint | - std::ios::left) { +mpi_initlog(const bool console = false, + const std::ios_base::fmtflags flags = std::ios::showpoint | + std::ios::left) +{ #ifdef DEAL_II_WITH_MPI unsigned int myid = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD); - if (myid == 0) { - deallogname = "output"; - deallogfile.open(deallogname.c_str()); - deallog.attach(deallogfile, true, flags); - deallog.depth_console(console ? 10 : 0); - } + if (myid == 0) + { + deallogname = "output"; + deallogfile.open(deallogname.c_str()); + deallog.attach(deallogfile, true, flags); + deallog.depth_console(console ? 10 : 0); + } #else (void)console; (void)flags; @@ -428,57 +497,67 @@ mpi_initlog(const bool console = false, * more correctly, the end of the current object), concatenates them * all into the output file used on processor 0. */ -struct MPILogInitAll { - MPILogInitAll(const bool console = false, - const std::ios_base::fmtflags flags = std::ios::showpoint | - std::ios::left) { +struct MPILogInitAll +{ + MPILogInitAll(const bool console = false, + const std::ios_base::fmtflags flags = std::ios::showpoint | + std::ios::left) + { #ifdef DEAL_II_WITH_MPI const unsigned int myid = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD); #else constexpr unsigned int myid = 0; #endif - if (myid == 0) { - if (!deallog.has_file()) { - deallogfile.open("output"); + if (myid == 0) + { + if (!deallog.has_file()) + { + deallogfile.open("output"); + deallog.attach(deallogfile, true, flags); + } + } + else + { + deallogname = "output" + Utilities::int_to_string(myid); + deallogfile.open(deallogname.c_str()); deallog.attach(deallogfile, true, flags); } - } else { - deallogname = "output" + Utilities::int_to_string(myid); - deallogfile.open(deallogname.c_str()); - deallog.attach(deallogfile, true, flags); - } deallog.depth_console(console ? 10 : 0); deallog.push(Utilities::int_to_string(myid)); } - ~MPILogInitAll() { + ~MPILogInitAll() + { // pop the prefix for the MPI rank of the current process deallog.pop(); #ifdef DEAL_II_WITH_MPI - const unsigned int myid = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD); + const unsigned int myid = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD); const unsigned int nproc = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD); - if (myid != 0) { - deallog.detach(); - deallogfile.close(); - } + if (myid != 0) + { + deallog.detach(); + deallogfile.close(); + } MPI_Barrier(MPI_COMM_WORLD); -#ifdef DEAL_II_WITH_PETSC +# ifdef DEAL_II_WITH_PETSC check_petsc_allocations(); MPI_Barrier(MPI_COMM_WORLD); -#endif +# endif - if (myid == 0) { - for (unsigned int i = 1; i < nproc; ++i) { - std::string filename = "output" + Utilities::int_to_string(i); - cat_file(filename.c_str()); + if (myid == 0) + { + for (unsigned int i = 1; i < nproc; ++i) + { + std::string filename = "output" + Utilities::int_to_string(i); + cat_file(filename.c_str()); + } } - } MPI_Barrier(MPI_COMM_WORLD); #endif } @@ -490,17 +569,19 @@ struct MPILogInitAll { // cards for different processes even if only one node is used. The choice below // is based on the MPI proccess id. // MPI needs to be initialized before using this function. -void init_cuda(const bool use_mpi = false) { -#ifndef DEAL_II_WITH_MPI +void +init_cuda(const bool use_mpi = false) +{ +# ifndef DEAL_II_WITH_MPI Assert(use_mpi == false, ExcInternalError()); -#endif +# endif const unsigned int my_id = - use_mpi ? Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) : 0; - int n_devices = 0; + use_mpi ? Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) : 0; + int n_devices = 0; cudaError_t cuda_error_code = cudaGetDeviceCount(&n_devices); AssertCuda(cuda_error_code); const int device_id = my_id % n_devices; - cuda_error_code = cudaSetDevice(device_id); + cuda_error_code = cudaSetDevice(device_id); AssertCuda(cuda_error_code); // In principle, we should be able to distribute the load better by @@ -538,18 +619,24 @@ void init_cuda(const bool use_mpi = false) { #ifdef TBB_DO_ASSERT -#include +# include DEAL_II_NAMESPACE_OPEN -namespace deal_II_exceptions { -namespace internals { -extern bool show_stacktrace; -} +namespace deal_II_exceptions +{ + namespace internals + { + extern bool show_stacktrace; + } } // namespace deal_II_exceptions DEAL_II_NAMESPACE_CLOSE -void new_tbb_assertion_handler(const char *file, int line, const char *expr, - const char *comment) { +void +new_tbb_assertion_handler(const char *file, + int line, + const char *expr, + const char *comment) +{ // Print out the original assertion message std::cerr << "TBB assertion:" << std::endl; std::cerr << "Assertion " << expr << " failed on line " << line << " of file " @@ -558,14 +645,16 @@ void new_tbb_assertion_handler(const char *file, int line, const char *expr, // Reenable abort and stacktraces: deal_II_exceptions::internals::allow_abort_on_exception = true; - deal_II_exceptions::internals::show_stacktrace = true; + deal_II_exceptions::internals::show_stacktrace = true; // And abort with a deal.II exception: Assert(false, ExcMessage("TBB Exception, see above")); } -struct SetTBBAssertionHandler { - SetTBBAssertionHandler() { +struct SetTBBAssertionHandler +{ + SetTBBAssertionHandler() + { ::tbb::set_assertion_handler(new_tbb_assertion_handler); } } set_tbb_assertion_handler; @@ -581,8 +670,10 @@ DEAL_II_NAMESPACE_OPEN /* Disable stack traces: */ -struct SwitchOffStacktrace { - SwitchOffStacktrace() { +struct SwitchOffStacktrace +{ + SwitchOffStacktrace() + { deal_II_exceptions::suppress_stacktrace_in_exceptions(); } } deal_II_stacktrace_dummy; @@ -590,8 +681,10 @@ struct SwitchOffStacktrace { /* Enable floating point exceptions in debug mode and if we have detected that they are usable: */ -struct EnableFPE { - EnableFPE() { +struct EnableFPE +{ + EnableFPE() + { #if defined(DEBUG) && defined(DEAL_II_HAVE_FP_EXCEPTIONS) // enable floating point exceptions feenableexcept(FE_DIVBYZERO | FE_INVALID); @@ -603,18 +696,23 @@ struct EnableFPE { * This is used to test that the parallel algorithms in lac/ work alright: */ -namespace internal { -namespace VectorImplementation { -extern unsigned int minimum_parallel_grain_size; -} -namespace SparseMatrixImplementation { -extern unsigned int minimum_parallel_grain_size; -} +namespace internal +{ + namespace VectorImplementation + { + extern unsigned int minimum_parallel_grain_size; + } + namespace SparseMatrixImplementation + { + extern unsigned int minimum_parallel_grain_size; + } } // namespace internal -struct SetGrainSizes { - SetGrainSizes() { - internal::VectorImplementation::minimum_parallel_grain_size = 2; +struct SetGrainSizes +{ + SetGrainSizes() + { + internal::VectorImplementation::minimum_parallel_grain_size = 2; internal::SparseMatrixImplementation::minimum_parallel_grain_size = 2; } } set_grain_sizes; @@ -627,30 +725,39 @@ DEAL_II_NAMESPACE_CLOSE * * - Maier 2013 */ -LogStream &operator<<(LogStream &out, const std::vector &v) { +LogStream & +operator<<(LogStream &out, const std::vector &v) +{ for (unsigned int i = 0; i < v.size(); ++i) out << v[i] << (i == v.size() - 1 ? "" : " "); return out; } -LogStream &operator<<(LogStream &out, - const std::vector &v) { +LogStream & +operator<<(LogStream &out, const std::vector &v) +{ for (unsigned int i = 0; i < v.size(); ++i) out << v[i] << (i == v.size() - 1 ? "" : " "); return out; } -LogStream &operator<<(LogStream &out, const std::vector &v) { +LogStream & +operator<<(LogStream &out, const std::vector &v) +{ for (unsigned int i = 0; i < v.size(); ++i) out << v[i] << (i == v.size() - 1 ? "" : " "); return out; } -bool approximatelyEqual(float a, float b, float epsilon) { +bool +approximatelyEqual(float a, float b, float epsilon) +{ return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon); } -bool approximatelyEqual(double a, double b, double epsilon) { +bool +approximatelyEqual(double a, double b, double epsilon) +{ return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon); }