libMesh
Loading...
Searching...
No Matches
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 &  libmesh_dbg_varsystem_name 
)

Definition at line 241 of file vector_fe_ex10.C.

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

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::QBase::n_points(), libMesh::Real, libMesh::DenseVector< T >::resize(), libMesh::DenseMatrix< T >::resize(), libMesh::ExplicitSystem::rhs, and libMesh::System::variable_number().

◆ assemble_graddiv() [2/2]

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

Referenced by main().

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 84 of file vector_fe_ex10.C.

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 // Rotation can leave a mesh's caches unprepared
155
156 // Print information about the mesh to the screen.
158
159 // Create an equation systems object.
160 EquationSystems equation_systems (mesh);
161
162 // Declare the system "GradDiv" and its variable.
163 LinearImplicitSystem & system = equation_systems.add_system<LinearImplicitSystem>("GradDiv");
164
165 // Set the FE approximation order for the vector field variable.
166 const Order vector_order = static_cast<Order>(infile("order", 1u));
167
168 libmesh_error_msg_if(vector_order < FIRST || vector_order > ((dimension == 3) ? FIRST : FIFTH),
169 "You selected: " << vector_order <<
170 " but this example must be run with either 1 <= order <= 5 in 2d"
171 " or with order 1 in 3d.");
172
173 // Adds the variable "u" to "GradDiv". "u" will be our vector field.
174 system.add_variable("u", vector_order, RAVIART_THOMAS);
175
176 // Give the system a pointer to the matrix assembly
177 // function. This will be called when needed by the library.
179
180 // Initialize the data structures for the equation system.
181 equation_systems.init();
182
183 // Prints information about the system to the screen.
184 equation_systems.print_info();
185
186 // Solve the system "GradDiv". Note that calling this
187 // member will assemble the linear system and invoke
188 // the default numerical solver.
189 system.solve();
190
191 ExactSolution exact_sol(equation_systems);
192
193 SolutionFunction soln_func;
194 SolutionGradient soln_grad;
195
196 // Build FunctionBase* containers to attach to the ExactSolution object.
197 std::vector<FunctionBase<Number> *> sols(1, &soln_func);
198 std::vector<FunctionBase<Gradient> *> grads(1, &soln_grad);
199
200 exact_sol.attach_exact_values(sols);
201 exact_sol.attach_exact_derivs(grads);
202
203 // Use higher quadrature order for more accurate error results.
204 int extra_error_quadrature = infile("extra_error_quadrature", 2);
205 exact_sol.extra_quadrature_order(extra_error_quadrature);
206
207 // Compute the error.
208 exact_sol.compute_error("GradDiv", "u");
209
210 // Print out the error values.
211 libMesh::out << "~~ Vector field (u) ~~"
212 << std::endl;
213 libMesh::out << "L2 error is: "
214 << exact_sol.l2_error("GradDiv", "u")
215 << std::endl;
216 libMesh::out << "HDiv semi-norm error is: "
217 << exact_sol.error_norm("GradDiv", "u", HDIV_SEMINORM)
218 << std::endl;
219 libMesh::out << "HDiv error is: "
220 << exact_sol.hdiv_error("GradDiv", "u")
221 << std::endl;
222
223#ifdef LIBMESH_HAVE_EXODUS_API
224
225 // We write the file in the ExodusII format.
226 ExodusII_IO(mesh).write_equation_systems("out.e", equation_systems);
227
228#endif // #ifdef LIBMESH_HAVE_EXODUS_API
229
230 // All done.
231 return 0;
232}
static void RM(RealTensor T)
This is the EquationSystems class.
This class handles the computation of the L2 and/or H1 error for the Systems in the EquationSystems o...
The ExodusII_IO class implements reading meshes in the ExodusII file format from Sandia National Labs...
Definition exodusII_io.h:53
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.
The LibMeshInit class, when constructed, initializes the dependent libraries (e.g.
Definition libmesh.h:92
virtual void solve() override
Assembles & solves the linear system A*x=b.
void complete_preparation()
Definition mesh_base.C:874
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
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
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
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.
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.
RealTensorValue rotate(MeshBase &mesh, const Real phi, const Real theta=0., const Real psi=0.)
Rotates the mesh in 3D space.
void permute_elements(MeshBase &mesh)
Randomly permute the nodal ordering of each element (without twisting the element mapping).
void init(triangulateio &t)
Initializes the fields of t to nullptr/0 as necessary.
SolverPackage default_solver_package()
Definition libmesh.C:1064
OStreamProxy out
void assemble_graddiv(EquationSystems &es, const std::string &system_name)

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::MeshBase::complete_preparation(), 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::EquationSystems::init(), libMesh::INVALID_SOLVER_PACKAGE, libMesh::ExactSolution::l2_error(), main(), 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().