libMesh
Loading...
Searching...
No Matches
Functions
systems_of_equations_ex2.C File Reference

Go to the source code of this file.

Functions

void assemble_stokes (EquationSystems &es, const std::string &system_name)
 
void set_lid_driven_bcs (TransientLinearImplicitSystem &system)
 
void set_stagnation_bcs (TransientLinearImplicitSystem &system)
 
void set_poiseuille_bcs (TransientLinearImplicitSystem &system)
 
int main (int argc, char **argv)
 
void assemble_stokes (EquationSystems &es, const std::string &libmesh_dbg_var(system_name))
 

Function Documentation

◆ assemble_stokes() [1/2]

void assemble_stokes ( EquationSystems es,
const std::string &  libmesh_dbg_varsystem_name 
)

Definition at line 345 of file systems_of_equations_ex2.C.

347{
348 // It is a good idea to make sure we are assembling
349 // the proper system.
350 libmesh_assert_equal_to (system_name, "Navier-Stokes");
351
352#if LIBMESH_DIM > 1
353 // Get a constant reference to the mesh object.
354 const MeshBase & mesh = es.get_mesh();
355
356 // The dimension that we are running
357 const unsigned int dim = mesh.mesh_dimension();
358
359 // Get a reference to the Stokes system object.
360 TransientLinearImplicitSystem & navier_stokes_system =
361 es.get_system<TransientLinearImplicitSystem> ("Navier-Stokes");
362
363 // Numeric ids corresponding to each variable in the system
364 const unsigned int u_var = navier_stokes_system.variable_number ("vel_x");
365 const unsigned int v_var = navier_stokes_system.variable_number ("vel_y");
366 const unsigned int p_var = navier_stokes_system.variable_number ("p");
367
368 // Get the Finite Element type for "u". Note this will be
369 // the same as the type for "v".
370 FEType fe_vel_type = navier_stokes_system.variable_type(u_var);
371
372 // Get the Finite Element type for "p".
373 FEType fe_pres_type = navier_stokes_system.variable_type(p_var);
374
375 // Build a Finite Element object of the specified type for
376 // the velocity variables.
377 std::unique_ptr<FEBase> fe_vel (FEBase::build(dim, fe_vel_type));
378
379 // Build a Finite Element object of the specified type for
380 // the pressure variables.
381 std::unique_ptr<FEBase> fe_pres (FEBase::build(dim, fe_pres_type));
382
383 // A Gauss quadrature rule for numerical integration.
384 // Let the FEType object decide what order rule is appropriate.
385 QGauss qrule (dim, fe_vel_type.default_quadrature_order());
386
387 // Tell the finite element objects to use our quadrature rule.
388 fe_vel->attach_quadrature_rule (&qrule);
389 fe_pres->attach_quadrature_rule (&qrule);
390
391 // Here we define some references to cell-specific data that
392 // will be used to assemble the linear system.
393 //
394 // The element Jacobian * quadrature weight at each integration point.
395 const std::vector<Real> & JxW = fe_vel->get_JxW();
396
397 // The element shape functions evaluated at the quadrature points.
398 const std::vector<std::vector<Real>> & phi = fe_vel->get_phi();
399
400 // The element shape function gradients for the velocity
401 // variables evaluated at the quadrature points.
402 const std::vector<std::vector<RealGradient>> & dphi = fe_vel->get_dphi();
403
404 // The element shape functions for the pressure variable
405 // evaluated at the quadrature points.
406 const std::vector<std::vector<Real>> & psi = fe_pres->get_phi();
407
408 // The value of the linear shape function gradients at the quadrature points
409 // const std::vector<std::vector<RealGradient>> & dpsi = fe_pres->get_dphi();
410
411 // A reference to the DofMap object for this system. The DofMap
412 // object handles the index translation from node and element numbers
413 // to degree of freedom numbers. We will talk more about the DofMap
414 // in future examples.
415 const DofMap & dof_map = navier_stokes_system.get_dof_map();
416
417 // Define data structures to contain the element matrix
418 // and right-hand-side vector contribution. Following
419 // basic finite element terminology we will denote these
420 // "Ke" and "Fe".
423
425 Kuu(Ke), Kuv(Ke), Kup(Ke),
426 Kvu(Ke), Kvv(Ke), Kvp(Ke),
427 Kpu(Ke), Kpv(Ke), Kpp(Ke);
428
430 Fu(Fe),
431 Fv(Fe),
432 Fp(Fe);
433
434 // References to momentum equation right hand sides
435 std::reference_wrapper<DenseSubVector<Number>> F[2] = {Fu, Fv};
436
437 // References to velocity-velocity coupling blocks
438 std::reference_wrapper<DenseSubMatrix<Number>> K[2][2] = {{Kuu, Kuv}, {Kvu, Kvv}};
439
440 // References to velocity-pressure coupling blocks
441 std::reference_wrapper<DenseSubMatrix<Number>> B[2] = {Kup, Kvp};
442 std::reference_wrapper<DenseSubMatrix<Number>> BT[2] = {Kpu, Kpv};
443
444 // This vector will hold the degree of freedom indices for
445 // the element. These define where in the global system
446 // the element degrees of freedom get mapped.
447 std::vector<dof_id_type> dof_indices;
448 std::vector<dof_id_type> dof_indices_u;
449 std::vector<dof_id_type> dof_indices_v;
450 std::vector<dof_id_type> dof_indices_p;
451
452 // Find out what the timestep size parameter is from the system, and
453 // the value of theta for the theta method. We use implicit Euler (theta=1)
454 // for this simulation even though it is only first-order accurate in time.
455 // The reason for this decision is that the second-order Crank-Nicolson
456 // method is notoriously oscillatory for problems with discontinuous
457 // initial data such as the lid-driven cavity. Therefore,
458 // we sacrifice accuracy in time for stability, but since the solution
459 // reaches steady state relatively quickly we can afford to take small
460 // timesteps. If you monitor the initial nonlinear residual for this
461 // simulation, you should see that it is monotonically decreasing in time.
462 const Real dt = es.parameters.get<Real>("dt");
463 const Real theta = 1.;
464
465 // The kinematic viscosity, multiplies the "viscous" terms.
466 const Real nu = es.parameters.get<Real>("nu");
467
468 // The system knows whether or not we need to do a pressure pin.
469 // This is only required for problems with all-Dirichlet boundary
470 // conditions on the velocity.
471 const bool pin_pressure = es.parameters.get<bool>("pin_pressure");
472
473 // The global system matrix
474 SparseMatrix<Number> & matrix = navier_stokes_system.get_system_matrix();
475
476 // Now we will loop over all the elements in the mesh that
477 // live on the local processor. We will compute the element
478 // matrix and right-hand-side contribution. Since the mesh
479 // will be refined we want to only consider the ACTIVE elements,
480 // hence we use a variant of the active_elem_iterator.
481 for (const auto & elem : mesh.active_local_element_ptr_range())
482 {
483 // Get the degree of freedom indices for the
484 // current element. These define where in the global
485 // matrix and right-hand-side this element will
486 // contribute to.
487 dof_map.dof_indices (elem, dof_indices);
488 dof_map.dof_indices (elem, dof_indices_u, u_var);
489 dof_map.dof_indices (elem, dof_indices_v, v_var);
490 dof_map.dof_indices (elem, dof_indices_p, p_var);
491
492 const unsigned int n_dofs = dof_indices.size();
493 const unsigned int n_u_dofs = dof_indices_u.size();
494 const unsigned int n_v_dofs = dof_indices_v.size();
495 const unsigned int n_p_dofs = dof_indices_p.size();
496
497 // Compute the element-specific data for the current
498 // element. This involves computing the location of the
499 // quadrature points (q_point) and the shape functions
500 // (phi, dphi) for the current element.
501 fe_vel->reinit (elem);
502 fe_pres->reinit (elem);
503
504 // Zero the element matrix and right-hand side before
505 // summing them. We use the resize member here because
506 // the number of degrees of freedom might have changed from
507 // the last element. Note that this will be the case if the
508 // element type is different (i.e. the last element was a
509 // triangle, now we are on a quadrilateral).
510 Ke.resize (n_dofs, n_dofs);
511 Fe.resize (n_dofs);
512
513 // Reposition the submatrices... The idea is this:
514 //
515 // - - - -
516 // | Kuu Kuv Kup | | Fu |
517 // Ke = | Kvu Kvv Kvp |; Fe = | Fv |
518 // | Kpu Kpv Kpp | | Fp |
519 // - - - -
520 //
521 // The DenseSubMatrix.reposition () member takes the
522 // (row_offset, column_offset, row_size, column_size).
523 //
524 // Similarly, the DenseSubVector.reposition () member
525 // takes the (row_offset, row_size)
526 Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
527 Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
528 Kup.reposition (u_var*n_u_dofs, p_var*n_u_dofs, n_u_dofs, n_p_dofs);
529
530 Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
531 Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
532 Kvp.reposition (v_var*n_v_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
533
534 Kpu.reposition (p_var*n_u_dofs, u_var*n_u_dofs, n_p_dofs, n_u_dofs);
535 Kpv.reposition (p_var*n_u_dofs, v_var*n_u_dofs, n_p_dofs, n_v_dofs);
536 Kpp.reposition (p_var*n_u_dofs, p_var*n_u_dofs, n_p_dofs, n_p_dofs);
537
538 Fu.reposition (u_var*n_u_dofs, n_u_dofs);
539 Fv.reposition (v_var*n_u_dofs, n_v_dofs);
540 Fp.reposition (p_var*n_u_dofs, n_p_dofs);
541
542 // Now we will build the element matrix and right-hand-side.
543 // Constructing the RHS requires the solution and its
544 // gradient from the previous timestep. This must be
545 // calculated at each quadrature point by summing the
546 // solution degree-of-freedom values by the appropriate
547 // weight functions.
548 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
549 {
550 // Values to hold the solution & its gradient at the previous timestep.
551 NumberVectorValue U_old;
553 Number p_old = 0.;
554
555 // {grad_u, grad_v}, initialized to zero
556 std::array<Gradient, 2> grad_uv{};
557
558 // {grad_u_old, grad_v_old}, initialized to zero
559 std::array<Gradient, 2> grad_uv_old{};
560
561 // Compute the velocity & its gradient from the previous timestep
562 // and the old Newton iterate.
563 for (unsigned int l=0; l<n_u_dofs; l++)
564 {
565 // From the old timestep:
566 U_old(0) += phi[l][qp]*navier_stokes_system.old_solution (dof_indices_u[l]);
567 U_old(1) += phi[l][qp]*navier_stokes_system.old_solution (dof_indices_v[l]);
568 grad_uv_old[0].add_scaled (dphi[l][qp],navier_stokes_system.old_solution (dof_indices_u[l]));
569 grad_uv_old[1].add_scaled (dphi[l][qp],navier_stokes_system.old_solution (dof_indices_v[l]));
570
571 // From the previous Newton iterate:
572 U(0) += phi[l][qp]*navier_stokes_system.current_solution (dof_indices_u[l]);
573 U(1) += phi[l][qp]*navier_stokes_system.current_solution (dof_indices_v[l]);
574 grad_uv[0].add_scaled (dphi[l][qp],navier_stokes_system.current_solution (dof_indices_u[l]));
575 grad_uv[1].add_scaled (dphi[l][qp],navier_stokes_system.current_solution (dof_indices_v[l]));
576 }
577
578 // Compute the old pressure value at this quadrature point.
579 for (unsigned int l=0; l<n_p_dofs; l++)
580 p_old += psi[l][qp]*navier_stokes_system.old_solution (dof_indices_p[l]);
581
582 // First, an i-loop over the velocity degrees of freedom.
583 // We know that n_u_dofs == n_v_dofs so we can compute contributions
584 // for both at the same time.
585 for (unsigned int i=0; i<n_u_dofs; i++)
586 {
587 for (unsigned int k=0; k<2; ++k)
588 F[k](i) += JxW[qp] *
589 (U_old(k) * phi[i][qp] - // mass-matrix term
590 (1.-theta) * dt * (U_old * grad_uv_old[k]) * phi[i][qp] + // convection term
591 (1.-theta) * dt * p_old * dphi[i][qp](k) - // pressure term on rhs
592 (1.-theta) * dt * nu * (grad_uv_old[k] * dphi[i][qp]) + // diffusion term on rhs
593 theta * dt * (U * grad_uv[k]) * phi[i][qp]); // Newton term
594
595 // Matrix contributions for the uu and vv couplings.
596 for (unsigned int j=0; j<n_u_dofs; j++)
597 for (unsigned int k=0; k<2; ++k)
598 for (unsigned int l=0; l<2; ++l)
599 {
600 // "Diagonal" contribution
601 if (k==l)
602 K[k][k](i,j) += JxW[qp]*(phi[i][qp]*phi[j][qp] + // mass matrix term
603 theta*dt*nu*(dphi[i][qp]*dphi[j][qp]) + // diffusion term
604 theta*dt*(U*dphi[j][qp])*phi[i][qp]); // convection term
605
606 // Newton term
607 K[k][l](i,j) += JxW[qp] * theta * dt * grad_uv[k](l) * phi[i][qp] * phi[j][qp];
608 }
609
610 // Matrix contributions for the up and vp couplings.
611 for (unsigned int j=0; j<n_p_dofs; j++)
612 for (unsigned int k=0; k<2; ++k)
613 B[k](i,j) += JxW[qp] * -theta * dt * psi[j][qp] * dphi[i][qp](k);
614 }
615
616 // Now an i-loop over the pressure degrees of freedom. This code computes
617 // the matrix entries due to the continuity equation. Note: To maintain a
618 // symmetric matrix, we may (or may not) multiply the continuity equation by
619 // negative one. Here we do not.
620 for (unsigned int i=0; i<n_p_dofs; i++)
621 for (unsigned int j=0; j<n_u_dofs; j++)
622 for (unsigned int k=0; k<2; ++k)
623 BT[k](i,j) += JxW[qp] * psi[i][qp] * dphi[j][qp](k);
624 } // end of the quadrature point qp-loop
625
626
627 // At this point the interior element integration has been
628 // completed. We now need to pin the pressure to zero at global
629 // node number "pressure_node". This effectively removes the
630 // non-trivial null space of constant pressure solutions. The
631 // pressure pin is not necessary in problems that have "outflow"
632 // BCs, like Poiseuille flow with natural BCs. In fact it is
633 // actually wrong to do so, since the pressure is not
634 // under-specified in that situation.
635 if (pin_pressure)
636 {
637 const Real penalty = 1.e10;
638 const unsigned int pressure_node = 0;
639 const Real p_value = 0.0;
640 for (auto c : elem->node_index_range())
641 if (elem->node_id(c) == pressure_node)
642 {
643 Kpp(c,c) += penalty;
644 Fp(c) += penalty*p_value;
645 }
646 }
647
648 // Since we're using heterogeneous DirichletBoundary objects for
649 // the boundary conditions, we need to call a specific function
650 // to constrain the element stiffness matrix.
651 dof_map.heterogenously_constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
652
653 // The element matrix and right-hand-side are now built
654 // for this element. Add them to the global matrix and
655 // right-hand-side vector. The SparseMatrix::add_matrix()
656 // and NumericVector::add_vector() members do this for us.
657 matrix.add_matrix (Ke, dof_indices);
658 navier_stokes_system.rhs->add_vector (Fe, dof_indices);
659 } // end of element loop
660#else
661 libmesh_ignore(es);
662#endif
663}
unsigned int dim
Defines a dense matrix for use in Finite Element-type computations.
void resize(const unsigned int new_m, const unsigned int new_n)
Resizes the matrix to the specified size and calls zero().
Defines a dense submatrix for use in Finite Element-type computations.
Defines a dense subvector for use in finite element computations.
Defines a dense vector for use in Finite Element-type computations.
void resize(const unsigned int n)
Resize the vector.
This class handles the numbering of degrees of freedom on a mesh.
Definition dof_map.h:181
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
Definition dof_map.C:2201
void heterogenously_constrain_element_matrix_and_vector(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true, int qoi_index=-1) const
Definition dof_map.h:1388
const MeshBase & get_mesh() const
Parameters parameters
Data structure holding arbitrary parameters.
const T_sys & get_system(std::string_view name) const
static std::unique_ptr< FEGenericBase > build(const unsigned int dim, const FEType &type)
Builds a specific finite element type.
class FEType hides (possibly multiple) FEFamily and approximation orders, thereby enabling specialize...
Definition fe_type.h:197
Order default_quadrature_order() const
Definition fe_type.h:415
This is the MeshBase class.
Definition mesh_base.h:81
unsigned int mesh_dimension() const
Definition mesh_base.C:430
const T & get(std::string_view) const
Definition parameters.h:451
This class implements specific orders of Gauss quadrature.
Generic sparse matrix.
Manages storage and variables for transient systems.
Number old_solution(const dof_id_type global_dof_number) const
This class defines a vector in LIBMESH_DIM dimensional Real or Complex space.
MeshBase & mesh
void libmesh_ignore(const Args &...)
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
Definition assembly.h:39

References libMesh::FEGenericBase< OutputType >::build(), libMesh::FEType::default_quadrature_order(), dim, libMesh::DofMap::dof_indices(), libMesh::Parameters::get(), libMesh::EquationSystems::get_mesh(), libMesh::EquationSystems::get_system(), libMesh::DofMap::heterogenously_constrain_element_matrix_and_vector(), libMesh::libmesh_ignore(), mesh, libMesh::MeshBase::mesh_dimension(), libMesh::QBase::n_points(), libMesh::TransientSystem< Base >::old_solution(), libMesh::EquationSystems::parameters, libMesh::Real, libMesh::DenseSubMatrix< T >::reposition(), libMesh::DenseSubVector< T >::reposition(), libMesh::DenseVector< T >::resize(), and libMesh::DenseMatrix< T >::resize().

◆ assemble_stokes() [2/2]

void assemble_stokes ( EquationSystems es,
const std::string &  system_name 
)

Referenced by main().

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 94 of file systems_of_equations_ex2.C.

95{
96 // Initialize libMesh.
97 LibMeshInit init (argc, argv);
98
99 // This example requires a linear solver package.
100 libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
101 "--enable-petsc, --enable-trilinos, or --enable-eigen");
102
103 // Skip this 2D example if libMesh was compiled as 1D-only.
104 libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
105
106 // We use Dirichlet boundary conditions here
107#ifndef LIBMESH_ENABLE_DIRICHLET
108 libmesh_example_requires(false, "--enable-dirichlet");
109#endif
110
111 // This example NaNs with the Trilinos solvers
112 libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc or --enable-laspack");
113
114 // Create a mesh, with dimension to be overridden later, distributed
115 // across the default MPI communicator.
116 Mesh mesh(init.comm());
117
118 // Get the mesh size from the command line.
119 const int n_elem = libMesh::command_line_next("-n_elem", 20);
120
121 // Use the MeshTools::Generation mesh generator to create a uniform
122 // 2D grid on the square [-1,1]^2. We instruct the mesh generator
123 // to build a mesh of 8x8 Quad9 elements in 2D. Building these
124 // higher-order elements allows us to use higher-order polynomial
125 // approximations for the velocity.
127 n_elem, n_elem,
128 0., 1.,
129 0., 1.,
130 QUAD9);
131
132 // Print information about the mesh to the screen.
134
135 // Create an equation systems object.
136 EquationSystems equation_systems (mesh);
137
138 // Declare the system and its variables.
139 // Creates a transient system named "Navier-Stokes"
141 equation_systems.add_system<TransientLinearImplicitSystem> ("Navier-Stokes");
142
143 // Add the variables "vel_x" & "vel_y" to "Navier-Stokes". They
144 // will be approximated using second-order approximation.
145 system.add_variable ("vel_x", SECOND);
146 system.add_variable ("vel_y", SECOND);
147
148 // Add the variable "p" to "Navier-Stokes". This will
149 // be approximated with a first-order basis,
150 // providing an LBB-stable pressure-velocity pair.
151 system.add_variable ("p", FIRST);
152
153 // Give the system a pointer to the matrix assembly
154 // function.
155 system.attach_assemble_function (assemble_stokes);
156
157 // Note: only pick one set of BCs!
158 set_lid_driven_bcs(system);
159 // set_stagnation_bcs(system);
160 // set_poiseuille_bcs(system);
161
162 // Initialize the data structures for the equation system.
163 equation_systems.init ();
164
165 // Prints information about the system to the screen.
166 equation_systems.print_info();
167
168 // Create a performance-logging object for this example
169 PerfLog perf_log("Systems Example 2");
170
171 // Get a reference to the Stokes system to use later.
172 TransientLinearImplicitSystem & navier_stokes_system =
173 equation_systems.get_system<TransientLinearImplicitSystem>("Navier-Stokes");
174
175 // Now we begin the timestep loop to compute the time-accurate
176 // solution of the equations.
177 const Real dt = 0.1;
178 navier_stokes_system.time = 0.0;
179 const unsigned int n_timesteps = 15;
180
181 // The number of steps and the stopping criterion are also required
182 // for the nonlinear iterations.
183 const unsigned int n_nonlinear_steps = 15;
184 const Real nonlinear_tolerance = 1.e-5;
185
186 // We also set a standard linear solver flag in the EquationSystems object
187 // which controls the maximum number of linear solver iterations allowed.
188 const int max_iter = libMesh::command_line_next("-max_iter", 25);
189
190 equation_systems.parameters.set<unsigned int>("linear solver maximum iterations") = max_iter;
191
192 // Tell the system of equations what the timestep is by using
193 // the set_parameter function. The matrix assembly routine can
194 // then reference this parameter.
195 equation_systems.parameters.set<Real> ("dt") = dt;
196
197 // The kinematic viscosity, nu = mu/rho, units of length**2/time.
198 equation_systems.parameters.set<Real> ("nu") = .007;
199
200 // The first thing to do is to get a copy of the solution at
201 // the current nonlinear iteration. This value will be used to
202 // determine if we can exit the nonlinear loop.
203 std::unique_ptr<NumericVector<Number>>
204 last_nonlinear_soln (navier_stokes_system.solution->clone());
205
206 // Since we are not doing adaptivity, write all solutions to a single Exodus file.
207 ExodusII_IO exo_io(mesh);
208
209 for (unsigned int t_step=1; t_step<=n_timesteps; ++t_step)
210 {
211 // Increment the time counter, set the time step size as
212 // a parameter in the EquationSystem.
213 navier_stokes_system.time += dt;
214
215 // A pretty update message
216 libMesh::out << "\n\n*** Solving time step "
217 << t_step
218 << ", time = "
219 << navier_stokes_system.time
220 << " ***"
221 << std::endl;
222
223 // Now we need to update the solution vector from the
224 // previous time step. This is done directly through
225 // the reference to the Stokes system.
226 *navier_stokes_system.old_local_solution = *navier_stokes_system.current_local_solution;
227
228 // At the beginning of each solve, reset the linear solver tolerance
229 // to a "reasonable" starting value.
230 const Real initial_linear_solver_tol = 1.e-6;
231 equation_systems.parameters.set<Real> ("linear solver tolerance") = initial_linear_solver_tol;
232
233 // We'll set this flag when convergence is (hopefully) achieved.
234 bool converged = false;
235
236 // Now we begin the nonlinear loop
237 for (unsigned int l=0; l<n_nonlinear_steps; ++l)
238 {
239 // Update the nonlinear solution.
240 last_nonlinear_soln->zero();
241 last_nonlinear_soln->add(*navier_stokes_system.solution);
242
243 // Assemble & solve the linear system.
244 perf_log.push("linear solve");
245 equation_systems.get_system("Navier-Stokes").solve();
246 perf_log.pop("linear solve");
247
248 // Compute the difference between this solution and the last
249 // nonlinear iterate.
250 last_nonlinear_soln->add (-1., *navier_stokes_system.solution);
251
252 // Close the vector before computing its norm
253 last_nonlinear_soln->close();
254
255 // Compute the l2 norm of the difference
256 const Real norm_delta = last_nonlinear_soln->l2_norm();
257
258 // How many iterations were required to solve the linear system?
259 const unsigned int n_linear_iterations = navier_stokes_system.n_linear_iterations();
260
261 // What was the final residual of the linear system?
262 const Real final_linear_residual = navier_stokes_system.final_linear_residual();
263
264 // If the solver did no work (sometimes -ksp_converged_reason
265 // says "Linear solve converged due to CONVERGED_RTOL
266 // iterations 0") but the nonlinear residual norm is above
267 // the tolerance, we need to pick an even lower linear
268 // solver tolerance and try again. Note that the tolerance
269 // is relative to the norm of the RHS, which for this
270 // particular problem does not go to zero, since we are
271 // solving for the full solution rather than the update.
272 //
273 // Similarly, if the solver did no work and this is the 0th
274 // nonlinear step, it means that the delta between solutions
275 // is being inaccurately measured as "0" since the solution
276 // did not change. Decrease the tolerance and try again.
277 if (n_linear_iterations == 0 &&
278 (navier_stokes_system.final_linear_residual() >= nonlinear_tolerance || l==0))
279 {
280 Real old_linear_solver_tolerance = equation_systems.parameters.get<Real> ("linear solver tolerance");
281 equation_systems.parameters.set<Real> ("linear solver tolerance") = 1.e-3 * old_linear_solver_tolerance;
282 continue;
283 }
284
285 // Print out convergence information for the linear and
286 // nonlinear iterations.
287 libMesh::out << "Linear solver converged at step: "
288 << n_linear_iterations
289 << ", final residual: "
290 << final_linear_residual
291 << " Nonlinear convergence: ||u - u_old|| = "
292 << norm_delta
293 << std::endl;
294
295 // Terminate the solution iteration if the difference between
296 // this nonlinear iterate and the last is sufficiently small, AND
297 // if the most recent linear system was solved to a sufficient tolerance.
298 if ((norm_delta < nonlinear_tolerance) &&
299 (navier_stokes_system.final_linear_residual() < nonlinear_tolerance))
300 {
301 libMesh::out << " Nonlinear solver converged at step "
302 << l
303 << std::endl;
304 converged = true;
305 break;
306 }
307
308 // Otherwise, decrease the linear system tolerance. For the inexact Newton
309 // method, the linear solver tolerance needs to decrease as we get closer to
310 // the solution to ensure quadratic convergence. The new linear solver tolerance
311 // is chosen (heuristically) as the square of the previous linear system residual norm.
312 //Real flr2 = final_linear_residual*final_linear_residual;
313 Real new_linear_solver_tolerance = std::min(Utility::pow<2>(final_linear_residual), initial_linear_solver_tol);
314 equation_systems.parameters.set<Real> ("linear solver tolerance") = new_linear_solver_tolerance;
315 } // end nonlinear loop
316
317 // Don't keep going if we failed to converge.
318 libmesh_error_msg_if(!converged, "Error: Newton iterations failed to converge!");
319
320#ifdef LIBMESH_HAVE_EXODUS_API
321 // Write out every nth timestep to file.
322 const unsigned int write_interval = 1;
323
324 if ((t_step+1)%write_interval == 0)
325 {
326 exo_io.write_timestep("out.e",
327 equation_systems,
328 t_step+1, // we're off by one since we wrote the IC and the Exodus numbering is 1-based.
329 navier_stokes_system.time);
330 }
331#endif // #ifdef LIBMESH_HAVE_EXODUS_API
332 } // end timestep loop.
333
334 // All done.
335 return 0;
336}
This is the EquationSystems class.
The ExodusII_IO class implements reading meshes in the ExodusII file format from Sandia National Labs...
Definition exodusII_io.h:53
The LibMeshInit class, when constructed, initializes the dependent libraries (e.g.
Definition libmesh.h:92
void print_info(std::ostream &os=libMesh::out, const unsigned int verbosity=0, const bool global=true) const
Prints relevant information about the mesh.
Definition mesh_base.C:1755
The Mesh class is a thin wrapper, around the ReplicatedMesh class by default.
Definition mesh.h:51
The PerfLog class allows monitoring of specific events.
Definition perf_log.h:154
NumericVector< Number > * old_local_solution
All the values I need to compute my contribution to the simulation at hand.
void build_square(UnstructuredMesh &mesh, const unsigned int nx, const unsigned int ny, const Real xmin=0., const Real xmax=1., const Real ymin=0., const Real ymax=1., const ElemType type=INVALID_ELEM, const bool gauss_lobatto_grid=false)
A specialized build_cube() for 2D meshes.
dof_id_type n_elem(const MeshBase::const_element_iterator &begin, const MeshBase::const_element_iterator &end)
Count up the number of elements of a specific type (as defined by an iterator range).
void init(triangulateio &t)
Initializes the fields of t to nullptr/0 as necessary.
SolverPackage default_solver_package()
Definition libmesh.C:1064
OStreamProxy out
T command_line_next(std::string name, T default_value)
Use GetPot's search()/next() functions to get following arguments from the command line.
Definition libmesh.C:1025
void assemble_stokes(EquationSystems &es, const std::string &system_name)
void set_lid_driven_bcs(TransientLinearImplicitSystem &system)

References libMesh::EquationSystems::add_system(), assemble_stokes(), libMesh::MeshTools::Generation::build_square(), libMesh::command_line_next(), libMesh::default_solver_package(), libMesh::FIRST, libMesh::Parameters::get(), libMesh::EquationSystems::get_system(), libMesh::EquationSystems::init(), libMesh::INVALID_SOLVER_PACKAGE, main(), mesh, libMesh::TransientSystem< Base >::old_local_solution, libMesh::out, libMesh::EquationSystems::parameters, libMesh::PerfLog::pop(), libMesh::EquationSystems::print_info(), libMesh::MeshBase::print_info(), libMesh::PerfLog::push(), libMesh::QUAD9, libMesh::Real, libMesh::SECOND, libMesh::Parameters::set(), set_lid_driven_bcs(), libMesh::TRILINOS_SOLVERS, and libMesh::ExodusII_IO::write_timestep().

◆ set_lid_driven_bcs()

void set_lid_driven_bcs ( TransientLinearImplicitSystem system)

Definition at line 667 of file systems_of_equations_ex2.C.

668{
669 // This problem *does* require a pressure pin, there are Dirichlet
670 // boundary conditions for u and v on the entire boundary.
671 system.get_equation_systems().parameters.set<bool>("pin_pressure") = true;
672
673#ifdef LIBMESH_ENABLE_DIRICHLET
674 unsigned short int
675 u_var = system.variable_number("vel_x"),
676 v_var = system.variable_number("vel_y");
677
678 // Get a convenient reference to the System's DofMap
679 DofMap & dof_map = system.get_dof_map();
680
681 // u=v=0 on bottom, left, right
683 {u_var, v_var},
685 // u=1 on top
686 dof_map.add_dirichlet_boundary(DirichletBoundary({2}, {u_var},
688 // v=0 on top
689 dof_map.add_dirichlet_boundary(DirichletBoundary({2}, {v_var},
691#endif // LIBMESH_ENABLE_DIRICHLET
692}
Function that returns a single value that never changes.
This class allows one to associate Dirichlet boundary values with a given set of mesh boundary ids an...
void add_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary)
Adds a copy of the specified Dirichlet boundary to the system.
ConstFunction that simply returns 0.

References libMesh::DofMap::add_dirichlet_boundary().

Referenced by main().

◆ set_poiseuille_bcs()

void set_poiseuille_bcs ( TransientLinearImplicitSystem system)

Definition at line 749 of file systems_of_equations_ex2.C.

750{
751 // This problem does not require a pressure pin, the Neumann outlet
752 // BCs are sufficient to set the value of the pressure.
753 system.get_equation_systems().parameters.set<bool>("pin_pressure") = false;
754
755#ifdef LIBMESH_ENABLE_DIRICHLET
756 unsigned short int
757 u_var = system.variable_number("vel_x"),
758 v_var = system.variable_number("vel_y");
759
760 // Get a convenient reference to the System's DofMap
761 DofMap & dof_map = system.get_dof_map();
762
763 {
764 // u=v=0 on top, bottom
765 std::set<boundary_id_type> boundary_ids;
766 boundary_ids.insert(0);
767 boundary_ids.insert(2);
768
769 std::vector<unsigned int> variables;
770 variables.push_back(u_var);
771 variables.push_back(v_var);
772
773 dof_map.add_dirichlet_boundary(DirichletBoundary(boundary_ids,
774 variables,
776 }
777 {
778 // u=quadratic on left
779 std::set<boundary_id_type> boundary_ids;
780 boundary_ids.insert(3);
781
782 std::vector<unsigned int> variables;
783 variables.push_back(u_var);
784
785 dof_map.add_dirichlet_boundary(DirichletBoundary(boundary_ids,
786 variables,
787 ParsedFunction<Number>("4*y*(1-y)")));
788 }
789 {
790 // v=0 on left
791 std::set<boundary_id_type> boundary_ids;
792 boundary_ids.insert(3);
793
794 std::vector<unsigned int> variables;
795 variables.push_back(v_var);
796
797 dof_map.add_dirichlet_boundary(DirichletBoundary(boundary_ids,
798 variables,
800 }
801#endif // LIBMESH_ENABLE_DIRICHLET
802}
A Function generated (via FParser) by parsing a mathematical expression.

References libMesh::DofMap::add_dirichlet_boundary().

◆ set_stagnation_bcs()

void set_stagnation_bcs ( TransientLinearImplicitSystem system)

Definition at line 696 of file systems_of_equations_ex2.C.

697{
698 // This problem does not require a pressure pin, the Neumann outlet
699 // BCs are sufficient to set the value of the pressure.
700 system.get_equation_systems().parameters.set<bool>("pin_pressure") = false;
701
702#ifdef LIBMESH_ENABLE_DIRICHLET
703 unsigned short int
704 u_var = system.variable_number("vel_x"),
705 v_var = system.variable_number("vel_y");
706
707 // Get a convenient reference to the System's DofMap
708 DofMap & dof_map = system.get_dof_map();
709
710 // u=v=0 on bottom (boundary 0)
711 dof_map.add_dirichlet_boundary(DirichletBoundary({0}, {u_var, v_var},
713 // u=0 on left (boundary 3) (symmetry)
714 dof_map.add_dirichlet_boundary(DirichletBoundary({3}, {u_var},
716 {
717 // u = k*x on top (boundary 2)
718
719 // Set up ParsedFunction parameters
720 std::vector<std::string> additional_vars {"k"};
721 std::vector<Number> initial_vals {1.};
722
723 dof_map.add_dirichlet_boundary(DirichletBoundary({2}, {u_var},
725 &additional_vars,
726 &initial_vals)));
727 }
728 {
729 // v = -k*y on top (boundary 2)
730
731 // Set up ParsedFunction parameters
732 std::vector<std::string> additional_vars {"k"};
733 std::vector<Number> initial_vals {1.};
734
735 // Note: we have to specify LOCAL_VARIABLE_ORDER here, since we're
736 // using a ParsedFunction to set the value of v_var, which is
737 // actually the second variable in the system.
738 dof_map.add_dirichlet_boundary(DirichletBoundary({2}, {v_var},
740 &additional_vars,
741 &initial_vals),
743 }
744#endif // LIBMESH_ENABLE_DIRICHLET
745}

References libMesh::DofMap::add_dirichlet_boundary(), and libMesh::LOCAL_VARIABLE_ORDER.