libMesh
Functions
vector_fe_ex10.C File Reference

Go to the source code of this file.

Functions

void assemble_graddiv (EquationSystems &es, const std::string &system_name)
 
int main (int argc, char **argv)
 
void assemble_graddiv (EquationSystems &es, const std::string &libmesh_dbg_var(system_name))
 

Function Documentation

◆ assemble_graddiv() [1/2]

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

Referenced by main().

◆ assemble_graddiv() [2/2]

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

Definition at line 238 of file vector_fe_ex10.C.

References libMesh::SparseMatrix< T >::add_matrix(), libMesh::NumericVector< T >::add_vector(), libMesh::FEGenericBase< OutputType >::build(), libMesh::FEType::default_quadrature_order(), dim, GradDivExactSolution::forcing(), libMesh::System::get_dof_map(), libMesh::EquationSystems::get_mesh(), libMesh::EquationSystems::get_system(), libMesh::ImplicitSystem::get_system_matrix(), mesh, libMesh::MeshBase::mesh_dimension(), libMesh::Real, libMesh::DenseVector< T >::resize(), libMesh::DenseMatrix< T >::resize(), libMesh::ExplicitSystem::rhs, and libMesh::System::variable_number().

240 {
241 
242  // It is a good idea to make sure we are assembling
243  // the proper system.
244  libmesh_assert_equal_to (system_name, "GradDiv");
245 
246  // Get a constant reference to the mesh object.
247  const MeshBase & mesh = es.get_mesh();
248 
249  // The dimension that we are running.
250  const unsigned int dim = mesh.mesh_dimension();
251 
252  // Get a reference to the LinearImplicitSystem we are solving.
253  LinearImplicitSystem & system = es.get_system<LinearImplicitSystem>("GradDiv");
254 
255  // A reference to the DofMap object for this system. The DofMap
256  // object handles the index translation from node and element numbers
257  // to degree of freedom numbers.
258  const DofMap & dof_map = system.get_dof_map();
259 
260  // Get a constant reference to the Finite Element type
261  // for the variable in the system.
262  FEType vector_fe_type = dof_map.variable_type(system.variable_number("u"));
263 
264  // Build the Finite Element object. Since the
265  // FEBase::build() member dynamically creates memory we will
266  // store the object as a std::unique_ptr<FEBase>. This can be thought
267  // of as a pointer that will clean up after itself. Introduction Example 4
268  // describes some advantages of std::unique_ptr's in the context of
269  // quadrature rules.
270  std::unique_ptr<FEVectorBase> vector_fe (FEVectorBase::build(dim, vector_fe_type));
271 
272  // A just-high-enough Gauss quadrature rule for numerical integration.
273  QGauss qrule (dim, vector_fe_type.default_quadrature_order());
274 
275  // Tell the finite element object to use our quadrature rule.
276  vector_fe->attach_quadrature_rule (&qrule);
277 
278  // Declare a special finite element object for boundary integration.
279  std::unique_ptr<FEVectorBase> vector_fe_face (FEVectorBase::build(dim, vector_fe_type));
280 
281  // Boundary integration requires one quadrature rule with dimensionality one
282  // less than the dimensionality of the element.
283  QGauss qface(dim-1, vector_fe_type.default_quadrature_order());
284 
285  // Tell the finite element object to use our quadrature rule.
286  vector_fe_face->attach_quadrature_rule (&qface);
287 
288  // Here we define some references to cell-specific data that
289  // will be used to assemble the linear system.
290  //
291  // The element Jacobian * quadrature weight at each integration point.
292  const std::vector<Real> & JxW = vector_fe->get_JxW();
293 
294  // The physical XY locations of the quadrature points on the element.
295  // These might be useful for evaluating spatially varying material
296  // properties at the quadrature points.
297  const std::vector<Point> & q_point = vector_fe->get_xyz();
298 
299  // The element shape functions evaluated at the quadrature points.
300  const std::vector<std::vector<RealGradient>> & vector_phi = vector_fe->get_phi();
301 
302  // The divergence of the element vector shape functions evaluated at the
303  // quadrature points.
304  const std::vector<std::vector<Real>> & div_vector_phi = vector_fe->get_div_phi();
305 
306  // Define data structures to contain the element matrix
307  // and right-hand-side vector contribution. Following
308  // basic finite element terminology we will denote these
309  // "Ke" and "Fe". These datatypes are templated on
310  // Number, which allows the same code to work for real
311  // or complex numbers.
314 
315  // These vectors will hold the degree of freedom indices for
316  // the element. These define where in the global system
317  // the element degrees of freedom get mapped.
318  std::vector<dof_id_type> dof_indices;
319 
320  // The global system matrix
321  SparseMatrix<Number> & matrix = system.get_system_matrix();
322 
323  // Now we will loop over all the elements in the mesh.
324  // We will compute the element matrix and right-hand-side
325  // contribution.
326  //
327  // Element ranges are a nice way to iterate through all the
328  // elements, or all the elements that have some property. The
329  // range will iterate from the first to the last element on
330  // the local processor.
331  // It is smart to make this one const so that we don't accidentally
332  // mess it up! In case users later modify this program to include
333  // refinement, we will be safe and will only consider the active
334  // elements; hence we use a variant of the
335  // active_local_element_ptr_range.
336  for (const auto & elem : mesh.active_local_element_ptr_range())
337  {
338  // Get the degree of freedom indices for the
339  // current element. These define where in the global
340  // matrix and right-hand-side this element will
341  // contribute to.
342  dof_map.dof_indices (elem, dof_indices);
343 
344  // Cache the total number of degrees of freedom on this element,
345  // for use as array and loop bounds later.
346  // We use cast_int to explicitly convert from size() (which may be
347  // 64-bit) to unsigned int (which may be 32-bit but which is definitely
348  // enough to count *local* degrees of freedom.
349  const unsigned int n_dofs =
350  cast_int<unsigned int>(dof_indices.size());
351 
352  // Compute the element-specific data for the current
353  // element. This involves computing the location of the
354  // quadrature points (q_point) and the shape functions
355  // and their divergences for the current element.
356  vector_fe->reinit (elem);
357 
358  // We should also have the same number of degrees of freedom as
359  // shape functions for our variable.
360  libmesh_assert_equal_to (n_dofs, vector_phi.size());
361 
362  // Zero the element matrix and right-hand side before
363  // summing them. We use the resize member here because
364  // the number of degrees of freedom might have changed from
365  // the last element. Note that this will be the case if the
366  // element type is different (i.e. the last element was a
367  // triangle, now we are on a quadrilateral).
368 
369  // The DenseMatrix::resize() and the DenseVector::resize()
370  // members will automatically zero out the matrix and vector.
371  Ke.resize (n_dofs, n_dofs);
372  Fe.resize (n_dofs);
373 
374  // Now loop over the quadrature points. This handles
375  // the numeric integration.
376  for (unsigned int qp=0; qp<qrule.n_points(); qp++)
377  {
378 
379  // Now we will build the element matrix.
380  // This a double loop to integrate the vector test functions (i)
381  // against the vector trial functions (j) and their divergences
382  for (unsigned int i = 0; i != n_dofs; i++)
383  for (unsigned int j = 0; j != n_dofs; j++)
384  {
385  Ke(i, j) += JxW[qp]*(div_vector_phi[i][qp]*div_vector_phi[j][qp]+
386  vector_phi[i][qp]*vector_phi[j][qp]);
387  }
388 
389  // This is the end of the matrix summation loop
390  // Now we build the element right-hand-side contribution.
391  // This involves a single loop in which we integrate the "forcing
392  // function" in the PDE against the vector test functions (k).
393  {
394  // "f" is the forcing function, given by the well-known
395  // "method of manufactured solutions".
396  RealGradient f = GradDivExactSolution().forcing(q_point[qp]);
397 
398  // Loop to integrate the vector test functions (k) against the
399  // forcing function.
400  for (unsigned int k = 0; k != n_dofs; k++)
401  {
402  Fe(k) += JxW[qp]*f*vector_phi[k][qp];
403  }
404  }
405  }
406 
407  // We have now reached the end of the quadrature point loop, so
408  // the interior element integration has been completed. However, we have
409  // not yet addressed boundary conditions.
410  {
411 
412  // The following loop is over the sides of the element.
413  // If the element has no neighbor on a side then that
414  // side MUST live on a boundary of the domain.
415  for (auto side : elem->side_index_range())
416  if (elem->neighbor_ptr(side) == nullptr)
417  {
418  // The value of the shape functions at the quadrature points.
419  const std::vector<std::vector<RealGradient>> & vector_phi_face = vector_fe_face->get_phi();
420 
421  // The Jacobian * Quadrature Weight at the quadrature
422  // points on the face.
423  const std::vector<Real> & JxW_face = vector_fe_face->get_JxW();
424 
425  // The XYZ locations (in physical space) of, and the normals at,
426  // the quadrature points on the face. This is where
427  // we will interpolate the boundary value function.
428  const std::vector<Point> & qface_point = vector_fe_face->get_xyz();
429  const std::vector<Point> & normals = vector_fe_face->get_normals();
430 
431  // Compute the vector shape function values on the element face.
432  vector_fe_face->reinit(elem, side);
433 
434  // Some shape functions will be 0 on the face, but for ease of
435  // indexing and generality of code we loop over them anyway.
436  libmesh_assert_equal_to (n_dofs, vector_phi_face.size());
437 
438  // Loop over the face quadrature points for integration.
439  for (unsigned int qp=0; qp<qface.n_points(); qp++)
440  {
441  // The boundary value for the vector variable.
442  RealGradient vector_value = GradDivExactSolution()(qface_point[qp]);
443 
444  // We use the penalty method to set the flux of the vector
445  // variable at the boundary, i.e. the RT vector boundary dof.
446  const Real penalty = 1.e10;
447 
448  // A double loop to integrate the normal component of the
449  // vector test functions (i) against the normal component of
450  // the vector trial functions (j).
451  for (unsigned int i = 0; i != n_dofs; i++)
452  for (unsigned int j = 0; j != n_dofs; j++)
453  {
454  Ke(i, j) += JxW_face[qp]*penalty*vector_phi_face[i][qp]*
455  normals[qp]*vector_phi_face[j][qp]*normals[qp];
456  }
457 
458  // Loop to integrate the normal component of the vector test
459  // functions (i) against the normal component of the
460  // exact solution for the vector variable.
461  for (unsigned int i = 0; i != n_dofs; i++)
462  {
463  Fe(i) += JxW_face[qp]*penalty*vector_phi_face[i][qp]*normals[qp]*
464  vector_value*normals[qp];
465  }
466  }
467  }
468  }
469 
470  // We have now finished the quadrature point loop,
471  // and have therefore applied all the boundary conditions.
472 
473  // If this assembly program were to be used on an adaptive mesh,
474  // we would have to apply any hanging node constraint equations.
475  dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
476 
477  // The element matrix and right-hand-side are now built
478  // for this element. Add them to the global matrix and
479  // right-hand-side vector. The SparseMatrix::add_matrix()
480  // and NumericVector::add_vector() members do this for us.
481  matrix.add_matrix (Ke, dof_indices);
482  system.rhs->add_vector (Fe, dof_indices);
483  }
484 
485  // All done!
486 }
class FEType hides (possibly multiple) FEFamily and approximation orders, thereby enabling specialize...
Definition: fe_type.h:196
unsigned int dim
Manages consistently variables, degrees of freedom, coefficient vectors, matrices and linear solvers ...
void resize(const unsigned int n)
Resize the vector.
Definition: dense_vector.h:396
virtual void add_vector(const T *v, const std::vector< numeric_index_type > &dof_indices)
Computes , where v is a pointer and each dof_indices[i] specifies where to add value v[i]...
MeshBase & mesh
NumericVector< Number > * rhs
The system matrix.
Order default_quadrature_order() const
Definition: fe_type.h:415
const T_sys & get_system(std::string_view name) const
This is the MeshBase class.
Definition: mesh_base.h:80
unsigned int variable_number(std::string_view var) const
Definition: system.C:1398
This class handles the numbering of degrees of freedom on a mesh.
Definition: dof_map.h:179
virtual void add_matrix(const DenseMatrix< T > &dm, const std::vector< numeric_index_type > &rows, const std::vector< numeric_index_type > &cols)=0
Add the full matrix dm to the SparseMatrix.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
const MeshBase & get_mesh() const
void resize(const unsigned int new_m, const unsigned int new_n)
Resizes the matrix to the specified size and calls zero().
Definition: dense_matrix.h:895
This class implements specific orders of Gauss quadrature.
unsigned int mesh_dimension() const
Definition: mesh_base.C:430
RealGradient forcing(Point p)
const DofMap & get_dof_map() const
Definition: system.h:2417
const SparseMatrix< Number > & get_system_matrix() const

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 84 of file vector_fe_ex10.C.

References libMesh::EquationSystems::add_system(), libMesh::System::add_variable(), assemble_graddiv(), libMesh::System::attach_assemble_function(), libMesh::ExactSolution::attach_exact_derivs(), libMesh::ExactSolution::attach_exact_values(), libMesh::MeshTools::Generation::build_cube(), libMesh::MeshTools::Generation::build_square(), libMesh::ExactSolution::compute_error(), libMesh::default_solver_package(), libMesh::ExactSolution::error_norm(), libMesh::ExactSolution::extra_quadrature_order(), libMesh::FIFTH, libMesh::FIRST, libMesh::ExactSolution::hdiv_error(), libMesh::HDIV_SEMINORM, libMesh::TriangleWrapper::init(), libMesh::EquationSystems::init(), libMesh::INVALID_SOLVER_PACKAGE, libMesh::ExactSolution::l2_error(), mesh, libMesh::out, libMesh::MeshTools::Modification::permute_elements(), libMesh::EquationSystems::print_info(), libMesh::MeshBase::print_info(), libMesh::RAVIART_THOMAS, libMesh::Real, GradDivExactSolution::RM(), libMesh::MeshTools::Modification::rotate(), libMesh::LinearImplicitSystem::solve(), and libMesh::ExodusII_IO::write_equation_systems().

85 {
86  // Initialize libMesh.
87  LibMeshInit init (argc, argv);
88 
89  // This example requires a linear solver package.
90  libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
91  "--enable-petsc, --enable-trilinos, or --enable-eigen");
92 
93  // Parse the input file.
94  GetPot infile("vector_fe_ex10.in");
95 
96  // But allow the command line to override it.
97  infile.parse_command_line(argc, argv);
98 
99  // hypre AMS/ADS requires PETSc 3.12.2 or above with hypre support enabled
100 #if PETSC_VERSION_LESS_THAN(3, 12, 2) || !defined(LIBMESH_HAVE_PETSC_HYPRE)
101  libmesh_example_requires(!infile.search("ams") && !infile.search("ads"),
102  "PETSc 3.12.2 or above with hypre support enabled");
103 #endif
104 
105  // Read in parameters from the command line and the input file.
106  const unsigned int dimension = infile("dim", 2);
107  const unsigned int grid_size = infile("grid_size", 15);
108 
109  // Skip higher-dimensional examples on a lower-dimensional libMesh build.
110  libmesh_example_requires(dimension <= LIBMESH_DIM, dimension << "D support");
111 
112  // Create a mesh, with dimension to be overridden later, distributed
113  // across the default MPI communicator.
114  Mesh mesh(init.comm());
115 
116  // Use the MeshTools::Generation mesh generator to create a uniform
117  // grid on the cube [-1,1]^D. To accomodate Raviart-Thomas elements, we must
118  // use TRI6/7 or QUAD8/9 elements in 2d, or TET14 or HEX27 in 3d.
119  const std::string elem_str = infile("element_type", std::string("TRI6"));
120 
121  libmesh_error_msg_if((dimension == 2 && elem_str != "TRI6" && elem_str != "TRI7" && elem_str != "QUAD8" && elem_str != "QUAD9") ||
122  (dimension == 3 && elem_str != "TET14" && elem_str != "HEX27"),
123  "You selected " << elem_str <<
124  " but this example must be run with TRI6, TRI7, QUAD8, or QUAD9 in 2d" <<
125  " or with TET14, or HEX27 in 3d.");
126 
127  if (dimension == 2)
129  grid_size,
130  grid_size,
131  -1., 1.,
132  -1., 1.,
133  Utility::string_to_enum<ElemType>(elem_str));
134  else if (dimension == 3)
136  grid_size,
137  grid_size,
138  grid_size,
139  -1., 1.,
140  -1., 1.,
141  -1., 1.,
142  Utility::string_to_enum<ElemType>(elem_str));
143 
144  // Make sure the code is robust against nodal reorderings.
146 
147  // Make sure the code is robust against solves on 2d meshes rotated out of
148  // the xy plane. By default, all Euler angles are zero, the rotation matrix
149  // is the identity, and the mesh stays in place.
150  const Real phi = infile("phi", 0.), theta = infile("theta", 0.), psi = infile("psi", 0.);
152 
153  // Print information about the mesh to the screen.
154  mesh.print_info();
155 
156  // Create an equation systems object.
157  EquationSystems equation_systems (mesh);
158 
159  // Declare the system "GradDiv" and its variable.
160  LinearImplicitSystem & system = equation_systems.add_system<LinearImplicitSystem>("GradDiv");
161 
162  // Set the FE approximation order for the vector field variable.
163  const Order vector_order = static_cast<Order>(infile("order", 1u));
164 
165  libmesh_error_msg_if(vector_order < FIRST || vector_order > ((dimension == 3) ? FIRST : FIFTH),
166  "You selected: " << vector_order <<
167  " but this example must be run with either 1 <= order <= 5 in 2d"
168  " or with order 1 in 3d.");
169 
170  // Adds the variable "u" to "GradDiv". "u" will be our vector field.
171  system.add_variable("u", vector_order, RAVIART_THOMAS);
172 
173  // Give the system a pointer to the matrix assembly
174  // function. This will be called when needed by the library.
176 
177  // Initialize the data structures for the equation system.
178  equation_systems.init();
179 
180  // Prints information about the system to the screen.
181  equation_systems.print_info();
182 
183  // Solve the system "GradDiv". Note that calling this
184  // member will assemble the linear system and invoke
185  // the default numerical solver.
186  system.solve();
187 
188  ExactSolution exact_sol(equation_systems);
189 
190  SolutionFunction soln_func;
191  SolutionGradient soln_grad;
192 
193  // Build FunctionBase* containers to attach to the ExactSolution object.
194  std::vector<FunctionBase<Number> *> sols(1, &soln_func);
195  std::vector<FunctionBase<Gradient> *> grads(1, &soln_grad);
196 
197  exact_sol.attach_exact_values(sols);
198  exact_sol.attach_exact_derivs(grads);
199 
200  // Use higher quadrature order for more accurate error results.
201  int extra_error_quadrature = infile("extra_error_quadrature", 2);
202  exact_sol.extra_quadrature_order(extra_error_quadrature);
203 
204  // Compute the error.
205  exact_sol.compute_error("GradDiv", "u");
206 
207  // Print out the error values.
208  libMesh::out << "~~ Vector field (u) ~~"
209  << std::endl;
210  libMesh::out << "L2 error is: "
211  << exact_sol.l2_error("GradDiv", "u")
212  << std::endl;
213  libMesh::out << "HDiv semi-norm error is: "
214  << exact_sol.error_norm("GradDiv", "u", HDIV_SEMINORM)
215  << std::endl;
216  libMesh::out << "HDiv error is: "
217  << exact_sol.hdiv_error("GradDiv", "u")
218  << std::endl;
219 
220 #ifdef LIBMESH_HAVE_EXODUS_API
221 
222  // We write the file in the ExodusII format.
223  ExodusII_IO(mesh).write_equation_systems("out.e", equation_systems);
224 
225 #endif // #ifdef LIBMESH_HAVE_EXODUS_API
226 
227  // All done.
228  return 0;
229 }
This class handles the computation of the L2 and/or H1 error for the Systems in the EquationSystems o...
This is the EquationSystems class.
Order
defines an enum for polynomial orders.
Definition: enum_order.h:40
The ExodusII_IO class implements reading meshes in the ExodusII file format from Sandia National Labs...
Definition: exodusII_io.h:50
void assemble_graddiv(EquationSystems &es, const std::string &system_name)
Manages consistently variables, degrees of freedom, coefficient vectors, matrices and linear solvers ...
MeshBase & mesh
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.
The LibMeshInit class, when constructed, initializes the dependent libraries (e.g.
Definition: libmesh.h:91
virtual void solve() override
Assembles & solves the linear system A*x=b.
void permute_elements(MeshBase &mesh)
Randomly permute the nodal ordering of each element (without twisting the element mapping)...
SolverPackage default_solver_package()
Definition: libmesh.C:1064
virtual void write_equation_systems(const std::string &fname, const EquationSystems &es, const std::set< std::string > *system_names=nullptr) override
Writes out the solution for no specific time or timestep.
Definition: exodusII_io.C:2050
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:1748
void init(triangulateio &t)
Initializes the fields of t to nullptr/0 as necessary.
unsigned int add_variable(std::string_view var, const FEType &type, const std::set< subdomain_id_type > *const active_subdomains=nullptr)
Adds the variable var to the list of variables for this system.
Definition: system.C:1344
static void RM(RealTensor T)
void attach_assemble_function(void fptr(EquationSystems &es, const std::string &name))
Register a user function to use in assembling the system matrix and RHS.
Definition: system.C:1959
RealTensorValue rotate(MeshBase &mesh, const Real phi, const Real theta=0., const Real psi=0.)
Rotates the mesh in the xy plane.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
OStreamProxy out
The Mesh class is a thin wrapper, around the ReplicatedMesh class by default.
Definition: mesh.h:50
void build_cube(UnstructuredMesh &mesh, const unsigned int nx=0, const unsigned int ny=0, const unsigned int nz=0, const Real xmin=0., const Real xmax=1., const Real ymin=0., const Real ymax=1., const Real zmin=0., const Real zmax=1., const ElemType type=INVALID_ELEM, const bool gauss_lobatto_grid=false)
Builds a (elements) cube.