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

Go to the source code of this file.

Functions

void assemble_cd (EquationSystems &es, const std::string &system_name)
 
void init_cd (EquationSystems &es, const std::string &system_name)
 
Real exact_solution (const Real x, const Real y, const Real t)
 This is the exact solution that we are trying to obtain.
 
Number exact_value (const Point &p, const Parameters &parameters, const std::string &, const std::string &)
 
int main (int argc, char **argv)
 
void init_cd (EquationSystems &es, const std::string &libmesh_dbg_var(system_name))
 
void assemble_cd (EquationSystems &es, const std::string &libmesh_dbg_var(system_name))
 

Function Documentation

◆ assemble_cd() [1/2]

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

Definition at line 522 of file adaptivity_ex2.C.

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}
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
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:515
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
LIBMESH_DEVICE_INLINE void add_scaled(const TypeVector< T2 > &, const T &)
Add a scaled value to this vector without creating a temporary.
MeshBase & mesh
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
static const bool value
Definition xdr_io.C:55

References libMesh::TypeVector< T >::add_scaled(), libMesh::FEGenericBase< OutputType >::build(), libMesh::DofMap::constrain_element_matrix_and_vector(), libMesh::FEType::default_quadrature_order(), dim, libMesh::DofMap::dof_indices(), exact_solution, libMesh::Parameters::get(), libMesh::EquationSystems::get_mesh(), libMesh::EquationSystems::get_system(), mesh, libMesh::MeshBase::mesh_dimension(), libMesh::QBase::n_points(), libMesh::TransientSystem< Base >::old_solution(), libMesh::EquationSystems::parameters, libMesh::Real, libMesh::DenseVector< T >::resize(), libMesh::DenseMatrix< T >::resize(), and value.

◆ assemble_cd() [2/2]

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

Definition at line 296 of file transient_ex1.C.

298{
299 // Ignore unused parameter warnings when !LIBMESH_ENABLE_AMR.
300 libmesh_ignore(es, system_name);
301
302#ifdef LIBMESH_ENABLE_AMR
303 // It is a good idea to make sure we are assembling
304 // the proper system.
305 libmesh_assert_equal_to (system_name, "Convection-Diffusion");
306
307 // Get a constant reference to the mesh object.
308 const MeshBase & mesh = es.get_mesh();
309
310 // The dimension that we are running
311 const unsigned int dim = mesh.mesh_dimension();
312
313 // Get a reference to the Convection-Diffusion system object.
315 es.get_system<TransientLinearImplicitSystem> ("Convection-Diffusion");
316
317 // Get a constant reference to the Finite Element type
318 // for the first (and only) variable in the system.
319 FEType fe_type = system.variable_type(0);
320
321 // Build a Finite Element object of the specified type. Since the
322 // FEBase::build() member dynamically creates memory we will
323 // store the object as a std::unique_ptr<FEBase>. This can be thought
324 // of as a pointer that will clean up after itself.
325 std::unique_ptr<FEBase> fe (FEBase::build(dim, fe_type));
326 std::unique_ptr<FEBase> fe_face (FEBase::build(dim, fe_type));
327
328 // A Gauss quadrature rule for numerical integration.
329 // Let the FEType object decide what order rule is appropriate.
330 QGauss qrule (dim, fe_type.default_quadrature_order());
331 QGauss qface (dim-1, fe_type.default_quadrature_order());
332
333 // Tell the finite element object to use our quadrature rule.
334 fe->attach_quadrature_rule (&qrule);
335 fe_face->attach_quadrature_rule (&qface);
336
337 // Here we define some references to cell-specific data that
338 // will be used to assemble the linear system. We will start
339 // with the element Jacobian * quadrature weight at each integration point.
340 const std::vector<Real> & JxW = fe->get_JxW();
341 const std::vector<Real> & JxW_face = fe_face->get_JxW();
342
343 // The element shape functions evaluated at the quadrature points.
344 const std::vector<std::vector<Real>> & phi = fe->get_phi();
345 const std::vector<std::vector<Real>> & psi = fe_face->get_phi();
346
347 // The element shape function gradients evaluated at the quadrature
348 // points.
349 const std::vector<std::vector<RealGradient>> & dphi = fe->get_dphi();
350
351 // The XY locations of the quadrature points used for face integration
352 const std::vector<Point> & qface_points = fe_face->get_xyz();
353
354 // A reference to the DofMap object for this system. The DofMap
355 // object handles the index translation from node and element numbers
356 // to degree of freedom numbers. We will talk more about the DofMap
357 // in future examples.
358 const DofMap & dof_map = system.get_dof_map();
359
360 // Define data structures to contain the element matrix
361 // and right-hand-side vector contribution. Following
362 // basic finite element terminology we will denote these
363 // "Ke" and "Fe".
366
367 // This vector will hold the degree of freedom indices for
368 // the element. These define where in the global system
369 // the element degrees of freedom get mapped.
370 std::vector<dof_id_type> dof_indices;
371
372 // Here we extract the velocity & parameters that we put in the
373 // EquationSystems object.
374 const RealVectorValue velocity =
375 es.parameters.get<RealVectorValue> ("velocity");
376
377 const Real dt = es.parameters.get<Real> ("dt");
378
379 SparseMatrix<Number> & matrix = system.get_system_matrix();
380
381 // Now we will loop over all the elements in the mesh that
382 // live on the local processor. We will compute the element
383 // matrix and right-hand-side contribution. Since the mesh
384 // will be refined we want to only consider the ACTIVE elements,
385 // hence we use a variant of the active_elem_iterator.
386 for (const auto & elem : mesh.active_local_element_ptr_range())
387 {
388 // Get the degree of freedom indices for the
389 // current element. These define where in the global
390 // matrix and right-hand-side this element will
391 // contribute to.
392 dof_map.dof_indices (elem, dof_indices);
393
394 // Compute the element-specific data for the current
395 // element. This involves computing the location of the
396 // quadrature points (q_point) and the shape functions
397 // (phi, dphi) for the current element.
398 fe->reinit (elem);
399
400 // Zero the element matrix and right-hand side before
401 // summing them. We use the resize member here because
402 // the number of degrees of freedom might have changed from
403 // the last element. Note that this will be the case if the
404 // element type is different (i.e. the last element was a
405 // triangle, now we are on a quadrilateral).
406 Ke.resize (dof_indices.size(),
407 dof_indices.size());
408
409 Fe.resize (dof_indices.size());
410
411 // Now we will build the element matrix and right-hand-side.
412 // Constructing the RHS requires the solution and its
413 // gradient from the previous timestep. This myst be
414 // calculated at each quadrature point by summing the
415 // solution degree-of-freedom values by the appropriate
416 // weight functions.
417 for (unsigned int qp=0; qp<qrule.n_points(); qp++)
418 {
419 // Values to hold the old solution & its gradient.
420 Number u_old = 0.;
421 Gradient grad_u_old;
422
423 // Compute the old solution & its gradient.
424 for (std::size_t l=0; l<phi.size(); l++)
425 {
426 u_old += phi[l][qp]*system.old_solution (dof_indices[l]);
427
428 // This will work,
429 // grad_u_old += dphi[l][qp]*system.old_solution (dof_indices[l]);
430 // but we can do it without creating a temporary like this:
431 grad_u_old.add_scaled (dphi[l][qp], system.old_solution (dof_indices[l]));
432 }
433
434 // Now compute the element matrix and RHS contributions.
435 for (std::size_t i=0; i<phi.size(); i++)
436 {
437 // The RHS contribution
438 Fe(i) += JxW[qp]*(
439 // Mass matrix term
440 u_old*phi[i][qp] +
441 -.5*dt*(
442 // Convection term
443 // (grad_u_old may be complex, so the
444 // order here is important!)
445 (grad_u_old*velocity)*phi[i][qp] +
446
447 // Diffusion term
448 0.01*(grad_u_old*dphi[i][qp]))
449 );
450
451 for (std::size_t j=0; j<phi.size(); j++)
452 {
453 // The matrix contribution
454 Ke(i,j) += JxW[qp]*(
455 // Mass-matrix
456 phi[i][qp]*phi[j][qp] +
457
458 .5*dt*(
459 // Convection term
460 (velocity*dphi[j][qp])*phi[i][qp] +
461
462 // Diffusion term
463 0.01*(dphi[i][qp]*dphi[j][qp]))
464 );
465 }
466 }
467 }
468
469 // At this point the interior element integration has
470 // been completed. However, we have not yet addressed
471 // boundary conditions. For this example we will only
472 // consider simple Dirichlet boundary conditions imposed
473 // via the penalty method.
474 //
475 // The following loops over the sides of the element.
476 // If the element has no neighbor on a side then that
477 // side MUST live on a boundary of the domain.
478 {
479 // The penalty value.
480 const Real penalty = 1.e10;
481
482 // The following loops over the sides of the element.
483 // If the element has no neighbor on a side then that
484 // side MUST live on a boundary of the domain.
485 for (auto s : elem->side_index_range())
486 if (elem->neighbor_ptr(s) == nullptr)
487 {
488 fe_face->reinit(elem, s);
489
490 for (unsigned int qp=0; qp<qface.n_points(); qp++)
491 {
492 const Number value = exact_solution (qface_points[qp](0),
493 qface_points[qp](1),
494 system.time);
495
496 // RHS contribution
497 for (std::size_t i=0; i<psi.size(); i++)
498 Fe(i) += penalty*JxW_face[qp]*value*psi[i][qp];
499
500 // Matrix contribution
501 for (std::size_t i=0; i<psi.size(); i++)
502 for (std::size_t j=0; j<psi.size(); j++)
503 Ke(i,j) += penalty*JxW_face[qp]*psi[i][qp]*psi[j][qp];
504 }
505 }
506 }
507
508 // If this assembly program were to be used on an adaptive mesh,
509 // we would have to apply any hanging node constraint equations
510 dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
511
512 // The element matrix and right-hand-side are now built
513 // for this element. Add them to the global matrix and
514 // right-hand-side vector. The SparseMatrix::add_matrix()
515 // and NumericVector::add_vector() members do this for us.
516 matrix.add_matrix (Ke, dof_indices);
517 system.rhs->add_vector (Fe, dof_indices);
518 }
519
520 // That concludes the system matrix assembly routine.
521#endif // #ifdef LIBMESH_ENABLE_AMR
522}
void libmesh_ignore(const Args &...)

References libMesh::TypeVector< T >::add_scaled(), libMesh::FEGenericBase< OutputType >::build(), libMesh::DofMap::constrain_element_matrix_and_vector(), dim, libMesh::DofMap::dof_indices(), exact_solution, libMesh::Parameters::get(), libMesh::EquationSystems::get_mesh(), libMesh::EquationSystems::get_system(), libMesh::libmesh_ignore(), mesh, libMesh::MeshBase::mesh_dimension(), libMesh::QBase::n_points(), libMesh::TransientSystem< Base >::old_solution(), libMesh::EquationSystems::parameters, libMesh::Real, libMesh::DenseVector< T >::resize(), libMesh::DenseMatrix< T >::resize(), and value.

Referenced by main().

◆ exact_solution()

Real exact_solution ( const Real  x,
const Real  y,
const Real  z = 0. 
)

This is the exact solution that we are trying to obtain.

We will solve

  • (u_xx + u_yy) = f

and take a finite difference approximation using this function to get f. This is the well-known "method of manufactured solutions".

Definition at line 43 of file exact_solution.C.

46{
47 static const Real pi = acos(-1.);
48
49 return cos(.5*pi*x)*sin(.5*pi*y)*cos(.5*pi*z);
50}
const Real pi
.
Definition libmesh.h:292

References libMesh::pi, and libMesh::Real.

◆ exact_value()

Number exact_value ( const Point &  p,
const Parameters &  parameters,
const std::string &  ,
const std::string &   
)

Definition at line 105 of file adaptivity_ex2.C.

109{
110 return exact_solution(p(0), p(1), parameters.get<Real> ("time"));
111}

References exact_solution, libMesh::Parameters::get(), and libMesh::Real.

Referenced by init_cd(), and libMesh::DofMap::max_constraint_error().

◆ init_cd() [1/2]

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

Definition at line 498 of file adaptivity_ex2.C.

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}
Number exact_value(const Point &p, const Parameters &parameters, const std::string &, const std::string &)
T & set(const std::string &)
Definition parameters.h:494

References exact_value(), libMesh::EquationSystems::get_system(), libMesh::EquationSystems::parameters, libMesh::Real, and libMesh::Parameters::set().

◆ init_cd() [2/2]

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

Referenced by main().

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 120 of file adaptivity_ex2.C.

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}
void assemble_cd(EquationSystems &es, const std::string &system_name)
void init_cd(EquationSystems &es, const std::string &system_name)
This is the EquationSystems class.
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.
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
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.
The ReplicatedMesh class is derived from the MeshBase class, and is used to store identical copies of...
This class defines a norm/seminorm to be applied to a NumericVector which contains coefficients in a ...
Definition system_norm.h:50
void init(triangulateio &t)
Initializes the fields of t to nullptr/0 as necessary.
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

References libMesh::EquationSystems::add_system(), libMesh::MeshBase::all_second_order(), assemble_cd(), libMesh::MeshRefinement::coarsen_fraction(), libMesh::command_line_next(), libMesh::default_solver_package(), libMesh::JumpErrorEstimator::estimate_error(), libMesh::MeshRefinement::flag_elements_by_error_fraction(), libMesh::EquationSystems::get_system(), libMesh::H1, libMesh::HIERARCHIC, libMesh::EquationSystems::init(), init_cd(), libMesh::INVALID_SOLVER_PACKAGE, libMesh::invalid_uint, libMesh::LAGRANGE, main(), libMesh::MeshRefinement::max_h_level(), mesh, libMesh::on_command_line(), libMesh::out, libMesh::EquationSystems::parameters, libMesh::EquationSystems::print_info(), libMesh::MeshBase::print_info(), libMesh::READ, libMesh::MeshBase::read(), libMesh::EquationSystems::read(), libMesh::Real, libMesh::MeshRefinement::refine_and_coarsen_elements(), libMesh::MeshRefinement::refine_fraction(), libMesh::EquationSystems::reinit(), libMesh::Parameters::set(), libMesh::TOLERANCE, libMesh::TRILINOS_SOLVERS, libMesh::MeshRefinement::uniformly_refine(), libMesh::JumpErrorEstimator::use_unweighted_quadrature_rules, libMesh::WRITE, libMesh::MeshBase::write(), libMesh::EquationSystems::write(), and libMesh::ExodusII_IO::write_equation_systems().