libMesh
Loading...
Searching...
No Matches
adaptivity_ex2.C
Go to the documentation of this file.
1// The libMesh Finite Element Library.
2// Copyright (C) 2002-2026 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
3
4// This library is free software; you can redistribute it and/or
5// modify it under the terms of the GNU Lesser General Public
6// License as published by the Free Software Foundation; either
7// version 2.1 of the License, or (at your option) any later version.
8
9// This library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// Lesser General Public License for more details.
13
14// You should have received a copy of the GNU Lesser General Public
15// License along with this library; if not, write to the Free Software
16// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
18
19
20// <h1>Adaptivity Example 2 - Solving a Transient System with Adaptive Mesh Refinement</h1>
21// \author Benjamin S. Kirk
22// \date 2003
23//
24// This example shows how a simple, linear transient
25// system can be solved in parallel. The system is simple
26// scalar convection-diffusion with a specified external
27// velocity. The initial condition is given, and the
28// solution is advanced in time with a standard Crank-Nicolson
29// time-stepping strategy.
30//
31// Also, we use this example to demonstrate writing out and reading
32// in of solutions. We do 25 time steps, then save the solution
33// and do another 25 time steps starting from the saved solution.
34
35// C++ include files that we need
36#include <iostream>
37#include <algorithm>
38#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
39#include <cmath>
40
41// Basic include file needed for the mesh functionality.
42#include "libmesh/libmesh.h"
43#include "libmesh/replicated_mesh.h"
44#include "libmesh/mesh_refinement.h"
45#include "libmesh/exodusII_io.h"
46#include "libmesh/equation_systems.h"
47#include "libmesh/fe.h"
48#include "libmesh/quadrature_gauss.h"
49#include "libmesh/dof_map.h"
50#include "libmesh/static_condensation.h"
51#include "libmesh/sparse_matrix.h"
52#include "libmesh/numeric_vector.h"
53#include "libmesh/dense_matrix.h"
54#include "libmesh/dense_vector.h"
55#include "libmesh/getpot.h"
56#include "libmesh/enum_solver_package.h"
57#include "libmesh/enum_xdr_mode.h"
58#include "libmesh/enum_norm_type.h"
59
60// This example will solve a linear transient system,
61// so we need to include the TransientLinearImplicitSystem definition.
62#include "libmesh/transient_system.h"
63#include "libmesh/linear_implicit_system.h"
64#include "libmesh/vector_value.h"
65
66// To refine the mesh we need an ErrorEstimator
67// object to figure out which elements to refine.
68#include "libmesh/error_vector.h"
69#include "libmesh/kelly_error_estimator.h"
70
71// The definition of a geometric element
72#include "libmesh/elem.h"
73
74// Bring in everything from the libMesh namespace
75using namespace libMesh;
76
77// Function prototype. This function will assemble the system
78// matrix and right-hand-side at each time step. Note that
79// since the system is linear we technically do not need to
80// assemble the matrix at each time step, but we will anyway.
81// In subsequent examples we will employ adaptive mesh refinement,
82// and with a changing mesh it will be necessary to rebuild the
83// system matrix.
84#ifdef LIBMESH_ENABLE_AMR
86 const std::string & system_name);
87#endif
88
89// Function prototype. This function will initialize the system.
90// Initialization functions are optional for systems. They allow
91// you to specify the initial values of the solution. If an
92// initialization function is not provided then the default (0)
93// solution is provided.
95 const std::string & system_name);
96
97// Exact solution function prototype. This gives the exact
98// solution as a function of space and time. In this case the
99// initial condition will be taken as the exact solution at time 0,
100// as will the Dirichlet boundary conditions at time t.
101Real exact_solution (const Real x,
102 const Real y,
103 const Real t);
104
106 const Parameters & parameters,
107 const std::string &,
108 const std::string &)
109{
110 return exact_solution(p(0), p(1), parameters.get<Real> ("time"));
111}
112
113
114
115// Begin the main program. Note that the first
116// statement in the program throws an error if
117// you are in complex number mode, since this
118// example is only intended to work with real
119// numbers.
120int main (int argc, char ** argv)
121{
122 // Initialize libMesh.
123 LibMeshInit init (argc, argv);
124
125 // This example requires a linear solver package.
126 libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
127 "--enable-petsc, --enable-trilinos, or --enable-eigen");
128
129#ifndef LIBMESH_ENABLE_AMR
130 libmesh_example_requires(false, "--enable-amr");
131#else
132
133 // Our Trilinos interface does not yet support adaptive transient
134 // problems
135 libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc");
136
137 // Our static condensation code relies on PETSc and Eigen
138#if !defined(LIBMESH_HAVE_EIGEN) || !defined(LIBMESH_HAVE_PETSC)
139 libmesh_example_requires
140 (!libMesh::on_command_line("--Convection-Diffusion-static-condensation"),
141 "--enable-eigen and --enable-petsc");
142#endif
143
144 // Brief message to the user regarding the program name
145 // and command line arguments.
146
147 // Use commandline parameter to specify if we are to
148 // read in an initial solution or generate it ourself
149 libMesh::out << "Usage:\n"
150 <<"\t " << argv[0] << " -init_timestep 0 -n_timesteps 25 [-n_refinements 5]\n"
151 << "OR\n"
152 <<"\t " << argv[0] << " -read_solution -init_timestep 26 -n_timesteps 25\n"
153 << std::endl;
154
155 libMesh::out << "Running: " << argv[0];
156
157 for (int i=1; i<argc; i++)
158 libMesh::out << " " << argv[i];
159
160 libMesh::out << std::endl << std::endl;
161
162 // This boolean value is obtained from the command line, it is true
163 // if the flag "-read_solution" is present, false otherwise.
164 // It indicates whether we are going to read in
165 // the mesh and solution files "saved_mesh.xda" and "saved_solution.xda"
166 // or whether we are going to start from scratch by just reading
167 // "mesh.xda"
168 const bool read_solution = libMesh::on_command_line("-read_solution");
169
170 // This value is also obtained from the commandline and it specifies the
171 // initial value for the t_step looping variable. We must
172 // distinguish between the two cases here, whether we read in the
173 // solution or we started from scratch, so that we do not overwrite the
174 // gmv output files.
175 const unsigned int init_timestep =
176 libMesh::command_line_next("-init_timestep",
178
179 if (init_timestep == libMesh::invalid_uint)
180 {
181 // This handy function will print the file name, line number,
182 // specified message, and then throw an exception.
183 libmesh_error_msg("ERROR: Initial timestep not specified!");
184 }
185
186 // This command line value specifies how many time steps to take.
187 const unsigned int n_timesteps =
188 libMesh::command_line_next("-n_timesteps",
190
191 if (n_timesteps == libMesh::invalid_uint)
192 libmesh_error_msg("ERROR: Number of timesteps not specified");
193
194 // This command line value specifies how far to allow refinement
195 const unsigned int max_h_level =
196 libMesh::command_line_next("-max_h_level", 5);
197
198 // Skip this 2D example if libMesh was compiled as 1D-only.
199 libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
200
201 // Create a new mesh on the default MPI communicator.
202 // We still need some work on automatic parallel restarts with
203 // DistributedMesh
204 ReplicatedMesh mesh(init.comm());
205
206 // Create an equation systems object.
207 EquationSystems equation_systems (mesh);
208 MeshRefinement mesh_refinement (mesh);
209
210 // First we process the case where we do not read in the solution
211 if (!read_solution)
212 {
213 // Read the mesh from file.
214 mesh.read ("mesh.xda");
215
216 // Again do a search on the command line for an argument
217 const int order =
218 libMesh::command_line_next("-order", 1);
219
220 // If we need a higher-order variable, we'll need second-order
221 // geometric elements to store edge DoFs. In 2D every
222 // second-order geometric can support every polynomial degree
223 // (even higher-than-second), but we'll leave the 3D-compatible
224 // thing in comments here for didactic purposes.
225 //if (order > 2)
226 // mesh.all_complete_order();
227 //else
228 if (order > 1)
230
231 const unsigned int n_refinements =
232 libMesh::command_line_next("-n_refinements", 5);
233
234 // Uniformly refine the mesh n times
235 if (!read_solution)
236 mesh_refinement.uniformly_refine (n_refinements);
237
238 // Print information about the mesh to the screen.
240
241 // Declare the system and its variables.
242 // Begin by creating a transient system
243 // named "Convection-Diffusion".
245 equation_systems.add_system<TransientLinearImplicitSystem>("Convection-Diffusion");
246
247 // Adds the variable "u" to "Convection-Diffusion". "u"
248 // will be approximated using first- or second-order
249 // approximation. For higher than second-order FE we need a
250 // non-Lagrange type.
251 system.add_variable ("u", Order(order), order > 2 ? HIERARCHIC : LAGRANGE);
252
253 // Give the system a pointer to the matrix assembly
254 // and initialization functions.
255 system.attach_assemble_function (assemble_cd);
256 system.attach_init_function (init_cd);
257
258 // Initialize the data structures for the equation system.
259 equation_systems.init ();
260 }
261 // Otherwise we read in the solution and mesh
262 else
263 {
264 // Read in the mesh stored in "saved_mesh.xda"
265 mesh.read("saved_mesh.xda");
266
267 // Print information about the mesh to the screen.
269
270 // Read in the solution stored in "saved_solution.xda"
271 equation_systems.read("saved_solution.xda", READ);
272
273 // Get a reference to the system so that we can call update() on it
275 equation_systems.get_system<TransientLinearImplicitSystem>("Convection-Diffusion");
276
277 // We need to call update to put system in a consistent state
278 // with the solution that was read in
279 system.update();
280
281 // Attach the same matrix assembly function as above. Note, we do not
282 // have to attach an init() function since we are initializing the
283 // system by reading in "saved_solution.xda"
284 system.attach_assemble_function (assemble_cd);
285
286 // Print out the H1 norm of the saved solution, for verification purposes:
287 Real H1norm = system.calculate_norm(*system.solution, SystemNorm(H1));
288
289 libMesh::out << "Initial H1 norm = " << H1norm << std::endl << std::endl;
290 }
291
292 // Prints information about the system to the screen.
293 equation_systems.print_info();
294
295 equation_systems.parameters.set<unsigned int>("linear solver maximum iterations") = 250;
296 equation_systems.parameters.set<Real>("linear solver tolerance") = TOLERANCE;
297
298 // Get some output to visualize
299#ifdef LIBMESH_HAVE_EXODUS_API
300 if (!read_solution)
301 // Write out the initial condition
302 ExodusII_IO(mesh).write_equation_systems ("out.e.000", equation_systems);
303 else
304 // Write out the solution that was read in
305 ExodusII_IO(mesh).write_equation_systems ("solution_read_in.e", equation_systems);
306#endif // LIBMESH_HAVE_EXODUS_API
307
308 // The Convection-Diffusion system requires that we specify
309 // the flow velocity. We will specify it as a RealVectorValue
310 // data type and then use the Parameters object to pass it to
311 // the assemble function.
312 equation_systems.parameters.set<RealVectorValue>("velocity") =
313 RealVectorValue (0.8, 0.8);
314
315 // The Convection-Diffusion system also requires a specified
316 // diffusivity. We use an isotropic (hence Real) value.
317 equation_systems.parameters.set<Real>("diffusivity") = 0.01;
318
319 // Solve the system "Convection-Diffusion". This will be done by
320 // looping over the specified time interval and calling the
321 // solve() member at each time step. This will assemble the
322 // system and call the linear solver.
323
324 // Since only TransientLinearImplicitSystems (and systems
325 // derived from them) contain old solutions, to use the
326 // old_local_solution later we now need to specify the system
327 // type when we ask for it.
329 equation_systems.get_system<TransientLinearImplicitSystem>("Convection-Diffusion");
330
331 const Real dt = 0.025;
332 system.time = init_timestep*dt;
333
334 // We're going to refine and coarsen based on some heuristics.
335 const Real refine_fraction =
336 libMesh::command_line_next("-refine_fraction", 0.80);
337
338 const Real coarsen_fraction =
339 libMesh::command_line_next("-coarsen_fraction", 0.07);
340
341 // We do 25 timesteps both before and after writing out the
342 // intermediate solution
343 for (unsigned int t_step=init_timestep; t_step<(init_timestep+n_timesteps); t_step++)
344 {
345 // Increment the time counter, set the time and the
346 // time step size as parameters in the EquationSystem.
347 system.time += dt;
348
349 equation_systems.parameters.set<Real> ("time") = system.time;
350 equation_systems.parameters.set<Real> ("dt") = dt;
351
352 // A pretty update message
353 libMesh::out << " Solving time step ";
354
355 // Add a set of scope braces to enforce data locality.
356 {
357 std::ostringstream out;
358
359 out << std::setw(2)
360 << std::right
361 << t_step
362 << ", time="
363 << std::fixed
364 << std::setw(6)
365 << std::setprecision(3)
366 << std::setfill('0')
367 << std::left
368 << system.time
369 << "...";
370
371 libMesh::out << out.str() << std::endl;
372 }
373
374 // At this point we need to update the old
375 // solution vector. The old solution vector
376 // will be the current solution vector from the
377 // previous time step.
378
379 *system.old_local_solution = *system.current_local_solution;
380
381 // The number of refinement steps per time step.
382 const unsigned int max_r_steps = 2;
383
384 // A refinement loop.
385 for (unsigned int r_step=0; r_step<max_r_steps; r_step++)
386 {
387 // Assemble & solve the linear system
388 system.solve();
389
390 // Print out the H1 norm, for verification purposes:
391 Real H1norm = system.calculate_norm(*system.solution, SystemNorm(H1));
392
393 libMesh::out << "H1 norm = " << H1norm << std::endl;
394
395 // Possibly refine the mesh
396 if (r_step+1 != max_r_steps)
397 {
398 libMesh::out << " Refining the mesh..." << std::endl;
399
400 // The ErrorVector is a particular StatisticsVector
401 // for computing error information on a finite element mesh.
402 ErrorVector error;
403
404 // The ErrorEstimator class interrogates a finite element
405 // solution and assigns to each element a positive error value.
406 // This value is used for deciding which elements to refine
407 // and which to coarsen.
408 KellyErrorEstimator error_estimator;
409
410 // This is a subclass of JumpErrorEstimator, based on
411 // measuring discontinuities across sides between
412 // elements, and we can tell it to use a cheaper
413 // "unweighted" quadrature rule when numerically
414 // integrating those discontinuities.
415 error_estimator.use_unweighted_quadrature_rules = true;
416
417 // Compute the error for each active element using the provided
418 // flux_jump indicator. Note in general you will need to
419 // provide an error estimator specifically designed for your
420 // application.
421 error_estimator.estimate_error (system,
422 error);
423
424 // This takes the error in error and decides which elements
425 // will be coarsened or refined. Any element within 20% of the
426 // maximum error on any element will be refined, and any
427 // element within 7% of the minimum error on any element might
428 // be coarsened. Note that the elements flagged for refinement
429 // will be refined, but those flagged for coarsening _might_ be
430 // coarsened.
431 mesh_refinement.refine_fraction() = refine_fraction;
432 mesh_refinement.coarsen_fraction() = coarsen_fraction;
433 mesh_refinement.max_h_level() = max_h_level;
434 mesh_refinement.flag_elements_by_error_fraction (error);
435
436 // This call actually refines and coarsens the flagged
437 // elements.
438 mesh_refinement.refine_and_coarsen_elements();
439
440 // This call reinitializes the EquationSystems object for
441 // the newly refined mesh. One of the steps in the
442 // reinitialization is projecting the solution,
443 // old_solution, etc... vectors from the old mesh to
444 // the current one.
445 equation_systems.reinit ();
446 }
447 }
448
449 // Again do a search on the command line for an argument
450 const unsigned int output_freq =
451 libMesh::command_line_next("-output_freq", 10);
452
453 // Every N timesteps, output solutions to file and summaries to
454 // the console.
455 if ((t_step+1)%output_freq == 0)
456 {
457 equation_systems.print_info();
458
459 std::ostringstream file_name;
460
461 file_name << "out.e."
462 << std::setw(3)
463 << std::setfill('0')
464 << std::right
465 << t_step+1;
466
467 // Get some output to visualize
468#ifdef LIBMESH_HAVE_EXODUS_API
469 ExodusII_IO(mesh).write_equation_systems (file_name.str(),
470 equation_systems);
471#endif // LIBMESH_HAVE_EXODUS_API
472 }
473 }
474
475 if (!read_solution)
476 {
477 // Print out the H1 norm of the saved solution, for verification purposes:
478 Real H1norm = system.calculate_norm(*system.solution, SystemNorm(H1));
479
480 libMesh::out << "Final H1 norm = " << H1norm << std::endl << std::endl;
481
482 mesh.write("saved_mesh.xda");
483 equation_systems.write("saved_solution.xda", WRITE);
484#ifdef LIBMESH_HAVE_EXODUS_API
485 ExodusII_IO(mesh).write_equation_systems ("saved_solution.e",
486 equation_systems);
487#endif // LIBMESH_HAVE_EXODUS_API
488 }
489#endif // #ifndef LIBMESH_ENABLE_AMR
490
491 return 0;
492}
493
494// Here we define the initialization routine for the
495// Convection-Diffusion system. This routine is
496// responsible for applying the initial conditions to
497// the system.
499 const std::string & libmesh_dbg_var(system_name))
500{
501 // It is a good idea to make sure we are initializing
502 // the proper system.
503 libmesh_assert_equal_to (system_name, "Convection-Diffusion");
504
505 // Get a reference to the Convection-Diffusion system object.
507 es.get_system<TransientLinearImplicitSystem>("Convection-Diffusion");
508
509 // Project initial conditions at time 0
510 es.parameters.set<Real> ("time") = system.time = 0;
511
512 system.project_solution(exact_value, nullptr, es.parameters);
513}
514
515
516
517// This function defines the assembly routine which
518// will be called at each time step. It is responsible
519// for computing the proper matrix entries for the
520// element stiffness matrices and right-hand sides.
521#ifdef LIBMESH_ENABLE_AMR
523 const std::string & libmesh_dbg_var(system_name))
524{
525 // It is a good idea to make sure we are assembling
526 // the proper system.
527 libmesh_assert_equal_to (system_name, "Convection-Diffusion");
528
529 // Get a constant reference to the mesh object.
530 const MeshBase & mesh = es.get_mesh();
531
532 // The dimension that we are running
533 const unsigned int dim = mesh.mesh_dimension();
534
535 // Get a reference to the Convection-Diffusion system object.
537 es.get_system<TransientLinearImplicitSystem> ("Convection-Diffusion");
538
539 // Get a pointer to the StaticCondensation class if it exists
540 StaticCondensation * sc = nullptr;
541 if (system.has_static_condensation())
542 sc = &system.get_static_condensation();
543
544 // Get the Finite Element type for the first (and only)
545 // variable in the system.
546 FEType fe_type = system.variable_type(0);
547
548 // Build a Finite Element object of the specified type. Since the
549 // FEBase::build() member dynamically creates memory we will
550 // store the object as a std::unique_ptr<FEBase>. This can be thought
551 // of as a pointer that will clean up after itself.
552 std::unique_ptr<FEBase> fe (FEBase::build(dim, fe_type));
553 std::unique_ptr<FEBase> fe_face (FEBase::build(dim, fe_type));
554
555 // A Gauss quadrature rule for numerical integration.
556 // Let the FEType object decide what order rule is appropriate.
557 QGauss qrule (dim, fe_type.default_quadrature_order());
558 QGauss qface (dim-1, fe_type.default_quadrature_order());
559
560 // Tell the finite element object to use our quadrature rule.
561 fe->attach_quadrature_rule (&qrule);
562 fe_face->attach_quadrature_rule (&qface);
563
564 // Here we define some references to cell-specific data that
565 // will be used to assemble the linear system. We will start
566 // with the element Jacobian * quadrature weight at each integration point.
567 const std::vector<Real> & JxW = fe->get_JxW();
568 const std::vector<Real> & JxW_face = fe_face->get_JxW();
569
570 // The element shape functions evaluated at the quadrature points.
571 const std::vector<std::vector<Real>> & phi = fe->get_phi();
572 const std::vector<std::vector<Real>> & psi = fe_face->get_phi();
573
574 // The element shape function gradients evaluated at the quadrature
575 // points.
576 const std::vector<std::vector<RealGradient>> & dphi = fe->get_dphi();
577
578 // The XY locations of the quadrature points used for face integration
579 const std::vector<Point> & qface_points = fe_face->get_xyz();
580
581 // A reference to the DofMap object for this system. The DofMap
582 // object handles the index translation from node and element numbers
583 // to degree of freedom numbers. We will talk more about the DofMap
584 // in future examples.
585 const DofMap & dof_map = system.get_dof_map();
586
587 // Define data structures to contain the element matrix
588 // and right-hand-side vector contribution. Following
589 // basic finite element terminology we will denote these
590 // "Ke" and "Fe".
593
594 // This vector will hold the degree of freedom indices for
595 // the element. These define where in the global system
596 // the element degrees of freedom get mapped.
597 std::vector<dof_id_type> dof_indices;
598
599 // Here we extract the velocity & parameters that we put in the
600 // EquationSystems object.
601 const RealVectorValue velocity =
602 es.parameters.get<RealVectorValue> ("velocity");
603
604 const Real diffusivity =
605 es.parameters.get<Real> ("diffusivity");
606
607 const Real dt = es.parameters.get<Real> ("dt");
608
609 // The global system matrix
610 SparseMatrix<Number> & matrix = system.get_system_matrix();
611
612 // Now we will loop over all the elements in the mesh that
613 // live on the local processor. We will compute the element
614 // matrix and right-hand-side contribution. Since the mesh
615 // will be refined we want to only consider the ACTIVE elements,
616 // hence we use a variant of the active_elem_iterator.
617 for (const auto & elem : mesh.active_local_element_ptr_range())
618 {
619 // Get the degree of freedom indices for the
620 // current element. These define where in the global
621 // matrix and right-hand-side this element will
622 // contribute to.
623 dof_map.dof_indices (elem, dof_indices);
624
625 // Compute the element-specific data for the current
626 // element. This involves computing the location of the
627 // quadrature points (q_point) and the shape functions
628 // (phi, dphi) for the current element.
629 fe->reinit (elem);
630
631 const unsigned int n_dofs =
632 cast_int<unsigned int>(dof_indices.size());
633 libmesh_assert_equal_to (n_dofs, phi.size());
634
635 // Zero the element matrix and right-hand side before
636 // summing them. We use the resize member here because
637 // the number of degrees of freedom might have changed from
638 // the last element. Note that this will be the case if the
639 // element type is different (i.e. the last element was a
640 // triangle, now we are on a quadrilateral).
641 Ke.resize (n_dofs, n_dofs);
642
643 Fe.resize (n_dofs);
644
645 // Now we will build the element matrix and right-hand-side.
646 // Constructing the RHS requires the solution and its
647 // gradient from the previous timestep. This myst be
648 // calculated at each quadrature point by summing the
649 // solution degree-of-freedom values by the appropriate
650 // weight functions.
651 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
652 {
653 // Values to hold the old solution & its gradient.
654 Number u_old = 0.;
655 Gradient grad_u_old;
656
657 // Compute the old solution & its gradient.
658 for (unsigned int l=0; l != n_dofs; l++)
659 {
660 u_old += phi[l][qp]*system.old_solution (dof_indices[l]);
661
662 // This will work,
663 // grad_u_old += dphi[l][qp]*system.old_solution (dof_indices[l]);
664 // but we can do it without creating a temporary like this:
665 grad_u_old.add_scaled (dphi[l][qp], system.old_solution (dof_indices[l]));
666 }
667
668 // Now compute the element matrix and RHS contributions.
669 for (unsigned int i=0; i != n_dofs; i++)
670 {
671 // The RHS contribution
672 Fe(i) += JxW[qp]*(
673 // Mass matrix term
674 u_old*phi[i][qp] +
675 -.5*dt*(
676 // Convection term
677 // (grad_u_old may be complex, so the
678 // order here is important!)
679 (grad_u_old*velocity)*phi[i][qp] +
680
681 // Diffusion term
682 diffusivity*(grad_u_old*dphi[i][qp]))
683 );
684
685 for (unsigned int j=0; j != n_dofs; j++)
686 {
687 // The matrix contribution
688 Ke(i,j) += JxW[qp]*(
689 // Mass-matrix
690 phi[i][qp]*phi[j][qp] +
691 .5*dt*(
692 // Convection term
693 (velocity*dphi[j][qp])*phi[i][qp] +
694 // Diffusion term
695 diffusivity*(dphi[i][qp]*dphi[j][qp]))
696 );
697 }
698 }
699 }
700
701 // At this point the interior element integration has
702 // been completed. However, we have not yet addressed
703 // boundary conditions. For this example we will only
704 // consider simple Dirichlet boundary conditions imposed
705 // via the penalty method.
706 //
707 // The following loops over the sides of the element.
708 // If the element has no neighbor on a side then that
709 // side MUST live on a boundary of the domain.
710 {
711 // The penalty value.
712 const Real penalty = 1.e10;
713
714 // The following loops over the sides of the element.
715 // If the element has no neighbor on a side then that
716 // side MUST live on a boundary of the domain.
717 for (auto s : elem->side_index_range())
718 if (elem->neighbor_ptr(s) == nullptr)
719 {
720 fe_face->reinit(elem, s);
721
722 libmesh_assert_equal_to (n_dofs, psi.size());
723
724 for (unsigned int qp=0; qp<qface.n_points(); qp++)
725 {
726 const Number value = exact_solution (qface_points[qp](0),
727 qface_points[qp](1),
728 system.time);
729
730 // RHS contribution
731 for (unsigned int i=0; i != n_dofs; i++)
732 Fe(i) += penalty*JxW_face[qp]*value*psi[i][qp];
733
734 // Matrix contribution
735 for (unsigned int i=0; i != n_dofs; i++)
736 for (unsigned int j=0; j != n_dofs; j++)
737 Ke(i,j) += penalty*JxW_face[qp]*psi[i][qp]*psi[j][qp];
738 }
739 }
740 }
741
742
743 // We have now built the element matrix and RHS vector in terms
744 // of the element degrees of freedom. However, it is possible
745 // that some of the element DOFs are constrained to enforce
746 // solution continuity, i.e. they are not really "free". We need
747 // to constrain those DOFs in terms of non-constrained DOFs to
748 // ensure a continuous solution. The
749 // DofMap::constrain_element_matrix_and_vector() method does
750 // just that.
751 dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
752
753 if (sc)
754 sc->set_current_elem(*elem);
755
756 // The element matrix and right-hand-side are now built
757 // for this element. Add them to the global matrix and
758 // right-hand-side vector. The SparseMatrix::add_matrix()
759 // and NumericVector::add_vector() members do this for us.
760 matrix.add_matrix (Ke, dof_indices);
761 system.rhs->add_vector (Fe, dof_indices);
762
763 }
764 // Finished computing the system matrix and right-hand side.
765}
766#endif // #ifdef LIBMESH_ENABLE_AMR
Number exact_value(const Point &p, const Parameters &parameters, const std::string &, const std::string &)
void assemble_cd(EquationSystems &es, const std::string &system_name)
void init_cd(EquationSystems &es, const std::string &system_name)
unsigned int dim
Number(* exact_solution)(const Point &p, const Parameters &, const std::string &, const std::string &)
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
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
Definition dof_map.C:2231
void constrain_element_matrix_and_vector(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true) const
Constrains the element matrix and vector.
Definition dof_map.h:2582
This is the EquationSystems class.
virtual void reinit()
Handle any mesh changes and reinitialize all the systems on the updated mesh.
void print_info(std::ostream &os=libMesh::out) const
Prints information about the equation systems, by default to libMesh::out.
void write(std::string_view name, const XdrMODE, const unsigned int write_flags=(WRITE_DATA), bool partition_agnostic=true) const
Write the systems to disk using the XDR data format.
void read(std::string_view name, const XdrMODE, const unsigned int read_flags=(READ_HEADER|READ_DATA), bool partition_agnostic=true)
Read & initialize the systems from disk using the XDR data format.
const MeshBase & get_mesh() const
Parameters parameters
Data structure holding arbitrary parameters.
virtual void init()
Initialize all the systems.
virtual System & add_system(std::string_view system_type, std::string_view name)
Add the system of type system_type named name to the systems array.
const T_sys & get_system(std::string_view name) const
The ErrorVector is a specialization of the StatisticsVector for error data computed on a finite eleme...
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.
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
bool use_unweighted_quadrature_rules
This boolean flag allows you to use "unweighted" quadrature rules (sized to exactly integrate unweigh...
virtual void estimate_error(const System &system, ErrorVector &error_per_cell, const NumericVector< Number > *solution_vector=nullptr, bool estimate_parent_error=false) override
This function uses the derived class's jump error estimate formula to estimate the error on each cell...
This class implements the Kelly error indicator which is based on the flux jumps between elements.
The LibMeshInit class, when constructed, initializes the dependent libraries (e.g.
Definition libmesh.h:92
This is the MeshBase class.
Definition mesh_base.h:81
unsigned int mesh_dimension() const
Definition mesh_base.C:515
void all_second_order(const bool full_ordered=true)
Calls the range-based version of this function with a range consisting of all elements in the mesh.
Definition mesh_base.C:1922
virtual void write(const std::string &name) const =0
virtual void read(const std::string &name, void *mesh_data=nullptr, bool skip_renumber_nodes_and_elements=false, bool skip_find_neighbors=false, bool skip_detect_interior_parents=false)=0
Interfaces for reading/writing a mesh to/from a file.
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:1874
Implements (adaptive) mesh refinement algorithms for a MeshBase.
void uniformly_refine(unsigned int n=1)
Uniformly refines the mesh n times.
void flag_elements_by_error_fraction(const ErrorVector &error_per_cell, const Real refine_fraction=0.3, const Real coarsen_fraction=0.0, const unsigned int max_level=libMesh::invalid_uint)
Flags elements for coarsening and refinement based on the computed error passed in error_per_cell.
unsigned int & max_h_level()
The max_h_level is the greatest refinement level an element should reach.
bool refine_and_coarsen_elements()
Refines and coarsens user-requested elements.
Real & refine_fraction()
The refine_fraction sets either a desired target or a desired maximum number of elements to flag for ...
Real & coarsen_fraction()
The coarsen_fraction sets either a desired target or a desired maximum number of elements to flag for...
This class provides the ability to map between arbitrary, user-defined strings and several data types...
Definition parameters.h:75
T & set(const std::string &)
Definition parameters.h:494
const T & get(std::string_view) const
Definition parameters.h:451
A Point defines a location in LIBMESH_DIM dimensional Real space.
Definition point.h:41
unsigned int n_points() const
Definition quadrature.h:131
This class implements specific orders of Gauss quadrature.
The ReplicatedMesh class is derived from the MeshBase class, and is used to store identical copies of...
Generic sparse matrix.
This class defines a norm/seminorm to be applied to a NumericVector which contains coefficients in a ...
Definition system_norm.h:50
Manages storage and variables for transient systems.
Number old_solution(const dof_id_type global_dof_number) const
LIBMESH_DEVICE_INLINE void add_scaled(const TypeVector< T2 > &, const T &)
Add a scaled value to this vector without creating a temporary.
MeshBase & mesh
The libMesh namespace provides an interface to certain functionality in the library.
SolverPackage default_solver_package()
Definition libmesh.C:1064
const unsigned int invalid_uint
A number which is used quite often to represent an invalid or uninitialized value for an unsigned int...
Definition libmesh.h:303
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
static constexpr Real TOLERANCE
bool on_command_line(std::string arg)
Definition libmesh.C:934
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
int main()
static const bool value
Definition xdr_io.C:55