407 *
double return_value = 0.0;
408 *
for (
unsigned int i = 0; i < dim; ++i)
409 * return_value += 4.0 * std::pow(p(i), 4.0);
411 *
return return_value;
417 * As boundary values, we choose @f$x^2+y^2@f$ in 2D, and @f$x^2+y^2+z^2@f$ in 3D. This
418 * happens to be
equal to the square of the vector from the origin to the
419 *
point at which we would like to evaluate the
function, irrespective of the
420 * dimension. So that is what we
return:
425 *
const unsigned int )
const
435 * <a name=
"ImplementationofthecodeStep4codeclass"></a>
436 * <h3>Implementation of the <code>Step4</code>
class</h3>
440 * Next
for the implementation of the
class template that makes use of the
441 *
functions above. As before, we will write everything as templates that have
442 * a formal parameter <code>dim</code> that we assume unknown at the time we
443 * define the
template functions. Only later, the compiler will find a
444 * declaration of <code>Step4@<2@></code> (in the <code>main</code>
function,
445 * actually) and compile the entire
class with <code>dim</code> replaced by 2,
446 * a process referred to as `instantiation of a
template'. When doing so, it
447 * will also replace instances of <code>RightHandSide@<dim@></code> by
448 * <code>RightHandSide@<2@></code> and instantiate the latter class from the
453 * In fact, the compiler will also find a declaration <code>Step4@<3@></code>
454 * in <code>main()</code>. This will cause it to again go back to the general
455 * <code>Step4@<dim@></code> template, replace all occurrences of
456 * <code>dim</code>, this time by 3, and compile the class a second time. Note
457 * that the two instantiations <code>Step4@<2@></code> and
458 * <code>Step4@<3@></code> are completely independent classes; their only
459 * common feature is that they are both instantiated from the same general
460 * template, but they are not convertible into each other, for example, and
461 * share no code (both instantiations are compiled completely independently).
469 * <a name="Step4Step4"></a>
470 * <h4>Step4::Step4</h4>
474 * After this introduction, here is the constructor of the <code>Step4</code>
475 * class. It specifies the desired polynomial degree of the finite elements
476 * and associates the DoFHandler to the triangulation just as in the previous
477 * example program, @ref step_3 "step-3":
481 * Step4<dim>::Step4()
483 * , dof_handler(triangulation)
490 * <a name="Step4make_grid"></a>
491 * <h4>Step4::make_grid</h4>
495 * Grid creation is something inherently dimension dependent. However, as long
496 * as the domains are sufficiently similar in 2D or 3D, the library can
497 * abstract for you. In our case, we would like to again solve on the square
498 * @f$[-1,1]\times [-1,1]@f$ in 2D, or on the cube @f$[-1,1] \times [-1,1] \times
499 * [-1,1]@f$ in 3D; both can be termed GridGenerator::hyper_cube(), so we may
500 * use the same function in whatever dimension we are. Of course, the
501 * functions that create a hypercube in two and three dimensions are very much
502 * different, but that is something you need not care about. Let the library
503 * handle the difficult things.
507 * void Step4<dim>::make_grid()
509 * GridGenerator::hyper_cube(triangulation, -1, 1);
510 * triangulation.refine_global(4);
512 * std::cout << " Number of active cells: " << triangulation.n_active_cells()
514 * << " Total number of cells: " << triangulation.n_cells()
521 * <a name="Step4setup_system"></a>
522 * <h4>Step4::setup_system</h4>
526 * This function looks exactly like in the previous example, although it
527 * performs actions that in their details are quite different if
528 * <code>dim</code> happens to be 3. The only significant difference from a
529 * user's perspective is the number of cells resulting, which is much higher
530 * in three than in two space dimensions!
534 *
void Step4<dim>::setup_system()
536 * dof_handler.distribute_dofs(fe);
538 * std::cout <<
" Number of degrees of freedom: " << dof_handler.n_dofs()
543 * sparsity_pattern.copy_from(dsp);
545 * system_matrix.reinit(sparsity_pattern);
547 * solution.reinit(dof_handler.n_dofs());
548 * system_rhs.reinit(dof_handler.n_dofs());
555 * <a name=
"Step4assemble_system"></a>
556 * <h4>Step4::assemble_system</h4>
560 * Unlike in the previous example, we would now like to use a non-constant
561 * right hand side
function and non-
zero boundary values. Both are tasks that
562 * are readily achieved with only a few
new lines of code in the assemblage of
563 * the
matrix and right hand side.
567 * More interesting, though, is the way we
assemble matrix and right hand side
568 * vector dimension independently: there is simply no difference to the
569 * two-dimensional
case. Since the important objects used in
this function
570 * (quadrature formula,
FEValues) depend on the dimension by way of a
template
571 * parameter as well, they can take care of setting up properly everything
for
572 * the dimension
for which
this function is compiled. By declaring all classes
573 * which might depend on the dimension
using a
template parameter, the library
574 * can make nearly all work
for you and you don
't have to care about most
579 * void Step4<dim>::assemble_system()
581 * QGauss<dim> quadrature_formula(fe.degree + 1);
585 * We wanted to have a non-constant right hand side, so we use an object of
586 * the class declared above to generate the necessary data. Since this right
587 * hand side object is only used locally in the present function, we declare
588 * it here as a local variable:
591 * RightHandSide<dim> right_hand_side;
595 * Compared to the previous example, in order to evaluate the non-constant
596 * right hand side function we now also need the quadrature points on the
597 * cell we are presently on (previously, we only required values and
598 * gradients of the shape function from the FEValues object, as well as the
599 * quadrature weights, FEValues::JxW() ). We can tell the FEValues object to
600 * do for us by also giving it the #update_quadrature_points flag:
603 * FEValues<dim> fe_values(fe,
604 * quadrature_formula,
605 * update_values | update_gradients |
606 * update_quadrature_points | update_JxW_values);
610 * We then again define the same abbreviation as in the previous program.
611 * The value of this variable of course depends on the dimension which we
612 * are presently using, but the FiniteElement class does all the necessary
613 * work for you and you don't have to care about the dimension dependent
617 *
const unsigned int dofs_per_cell = fe.dofs_per_cell;
622 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
626 * Next, we again have to
loop over all cells and
assemble local
627 * contributions. Note, that a cell is a quadrilateral in two space
628 * dimensions, but a hexahedron in 3D. In fact, the
629 * <code>active_cell_iterator</code> data type is something different,
630 * depending on the dimension we are in, but to the outside world they look
631 * alike and you will probably never see a difference. In any
case, the real
632 * type is hidden by
using `
auto`:
635 *
for (
const auto &cell : dof_handler.active_cell_iterators())
637 * fe_values.reinit(cell);
643 * Now we have to
assemble the local
matrix and right hand side. This is
644 * done exactly like in the previous example, but now we revert the
645 * order of the loops (which we can safely
do since they are independent
646 * of each other) and
merge the loops
for the local
matrix and the local
647 * vector as far as possible to make things a bit faster.
651 * Assembling the right hand side presents the only significant
652 * difference to how we did things in @ref step_3
"step-3": Instead of
using a
653 * constant right hand side with
value 1, we use the
object representing
654 * the right hand side and evaluate it at the quadrature points:
657 *
for (
const unsigned int q_index : fe_values.quadrature_point_indices())
658 *
for (
const unsigned int i : fe_values.dof_indices())
660 *
for (
const unsigned int j : fe_values.dof_indices())
662 * (fe_values.shape_grad(i, q_index) *
663 * fe_values.shape_grad(j, q_index) *
664 * fe_values.JxW(q_index));
666 *
const auto x_q = fe_values.quadrature_point(q_index);
667 * cell_rhs(i) += (fe_values.shape_value(i, q_index) *
668 * right_hand_side.value(x_q) *
669 * fe_values.JxW(q_index));
673 * As a
final remark to these loops: when we
assemble the local
674 * contributions into <code>
cell_matrix(i,j)</code>, we have to multiply
675 * the gradients of shape
functions @f$i@f$ and @f$j@f$ at
point number
677 * multiply it with the scalar weights JxW. This is what actually
678 * happens: <code>fe_values.shape_grad(i,q_index)</code> returns a
679 * <code>dim</code> dimensional vector, represented by a
680 * <code>
Tensor@<1,dim@></code> object, and the
operator* that
681 * multiplies it with the result of
682 * <code>fe_values.shape_grad(j,q_index)</code> makes sure that the
683 * <code>dim</code> components of the two vectors are properly
684 * contracted, and the result is a scalar floating
point number that
685 * then is multiplied with the weights. Internally,
this operator* makes
686 * sure that
this happens correctly
for all <code>dim</code> components
687 * of the vectors, whether <code>dim</code> be 2, 3, or any other space
688 * dimension; from a user
's perspective, this is not something worth
689 * bothering with, however, making things a lot simpler if one wants to
690 * write code dimension independently.
694 * With the local systems assembled, the transfer into the global matrix
695 * and right hand side is done exactly as before, but here we have again
696 * merged some loops for efficiency:
699 * cell->get_dof_indices(local_dof_indices);
700 * for (const unsigned int i : fe_values.dof_indices())
702 * for (const unsigned int j : fe_values.dof_indices())
703 * system_matrix.add(local_dof_indices[i],
704 * local_dof_indices[j],
705 * cell_matrix(i, j));
707 * system_rhs(local_dof_indices[i]) += cell_rhs(i);
713 * As the final step in this function, we wanted to have non-homogeneous
714 * boundary values in this example, unlike the one before. This is a simple
715 * task, we only have to replace the Functions::ZeroFunction used there by an
716 * object of the class which describes the boundary values we would like to
717 * use (i.e. the <code>BoundaryValues</code> class declared above):
721 * The function VectorTools::interpolate_boundary_values() will only work
722 * on faces that have been marked with boundary indicator 0 (because that's
723 * what we say the
function should work on with the
second argument below).
724 * If there are faces with boundary
id other than 0, then the
function
726 * the Laplace equation doing nothing is equivalent to assuming that
727 * on those parts of the boundary a
zero Neumann boundary condition holds.
730 * std::map<types::global_dof_index, double> boundary_values;
733 * BoundaryValues<dim>(),
745 * <a name=
"Step4solve"></a>
746 * <h4>Step4::solve</h4>
750 * Solving the linear system of equations is something that looks almost
751 * identical in most programs. In particular, it is dimension independent, so
752 *
this function is copied verbatim from the previous example.
756 *
void Step4<dim>::solve()
764 * We have made
one addition, though: since we suppress output from the
765 * linear solvers, we have to print the number of iterations by hand.
768 * std::cout <<
" " << solver_control.last_step()
769 * <<
" CG iterations needed to obtain convergence." << std::endl;
776 * <a name=
"Step4output_results"></a>
777 * <h4>Step4::output_results</h4>
781 * This
function also does what the respective
one did in @ref step_3
"step-3". No changes
782 * here
for dimension independence either.
786 * Since the program will
run both 2
d and 3
d versions of the Laplace solver,
787 * we use the dimension in the filename to generate distinct filenames
for
788 * each
run (in a better program,
one would check whether <code>dim</code> can
789 * have other values than 2 or 3, but we neglect
this here
for the sake of
794 *
void Step4<dim>::output_results() const
803 * std::ofstream output(dim == 2 ?
"solution-2d.vtk" :
"solution-3d.vtk");
812 * <a name=
"Step4run"></a>
817 * This is the
function which has the top-
level control over everything. Apart
818 * from
one line of additional output, it is the same as
for the previous
825 * std::cout <<
"Solving problem in " << dim <<
" space dimensions."
839 * <a name=
"Thecodemaincodefunction"></a>
840 * <h3>The <code>main</code>
function</h3>
844 * And
this is the main
function. It also looks mostly like in @ref step_3
"step-3", but
if
845 * you look at the code below, note how we
first create a variable of type
846 * <code>Step4@<2@></code> (forcing the compiler to compile the
class template
847 * with <code>dim</code> replaced by <code>2</code>) and
run a 2
d simulation,
848 * and then we
do the whole thing over in 3
d.
852 * In practice,
this is probably not what you would
do very frequently (you
853 * probably either want to solve a 2
d problem, or
one in 3
d, but not both at
854 * the same time). However, it demonstrates the mechanism by which we can
855 * simply change which dimension we want in a single place, and thereby force
856 * the compiler to recompile the dimension independent
class templates for the
857 * dimension we request. The emphasis here lies on the fact that we only need
858 * to change a single place. This makes it rather trivial to debug the program
859 * in 2
d where computations are fast, and then
switch a single place to a 3 to
860 *
run the much more computing intensive program in 3
d for `real
'
865 * Each of the two blocks is enclosed in braces to make sure that the
866 * <code>laplace_problem_2d</code> variable goes out of scope (and releases
867 * the memory it holds) before we move on to allocate memory for the 3d
868 * case. Without the additional braces, the <code>laplace_problem_2d</code>
869 * variable would only be destroyed at the end of the function, i.e. after
870 * running the 3d problem, and would needlessly hog memory while the 3d run
871 * could actually use it.
876 * deallog.depth_console(0);
878 * Step4<2> laplace_problem_2d;
879 * laplace_problem_2d.run();
883 * Step4<3> laplace_problem_3d;
884 * laplace_problem_3d.run();
890 <a name="Results"></a><h1>Results</h1>
894 The output of the program looks as follows (the number of iterations
895 may vary by one or two, depending on your computer, since this is
896 often dependent on the round-off accuracy of floating point
897 operations, which differs between processors):
899 Solving problem in 2 space dimensions.
900 Number of active cells: 256
901 Total number of cells: 341
902 Number of degrees of freedom: 289
903 26 CG iterations needed to obtain convergence.
904 Solving problem in 3 space dimensions.
905 Number of active cells: 4096
906 Total number of cells: 4681
907 Number of degrees of freedom: 4913
908 30 CG iterations needed to obtain convergence.
910 It is obvious that in three spatial dimensions the number of cells and
911 therefore also the number of degrees of freedom is
912 much higher. What cannot be seen here, is that besides this higher
913 number of rows and columns in the matrix, there are also significantly
914 more entries per row of the matrix in three space
915 dimensions. Together, this leads to a much higher numerical effort for
916 solving the system of equation, which you can feel in the run time of the two
917 solution steps when you actually run the program.
921 The program produces two files: <code>solution-2d.vtk</code> and
922 <code>solution-3d.vtk</code>, which can be viewed using the programs
923 VisIt or Paraview (in case you do not have these programs, you can easily
925 output format in the program to something which you can view more
926 easily). Visualizing solutions is a bit of an art, but it can also be fun, so
927 you should play around with your favorite visualization tool to get familiar
928 with its functionality. Here's what I have come up with
for the 2
d solution:
931 <img src=
"https://www.dealii.org/images/steps/developer/step-4.solution-2d.png" alt=
"">
934 (See also <a href=
"http://www.math.colostate.edu/~bangerth/videos.676.11.html">video lecture 11</a>, <a href=
"http://www.math.colostate.edu/~bangerth/videos.676.32.html">video lecture 32</a>.)
935 The picture shows the solution of the problem under consideration as
936 a 3D plot. As can be seen, the solution is almost flat in the interior
937 of the domain and has a higher curvature near the boundary. This, of
938 course, is due to the fact that for Laplace's equation the curvature
939 of the solution is
equal to the right hand side and that was chosen as
940 a quartic polynomial which is nearly
zero in the interior and is only
941 rising sharply when approaching the boundaries of the domain; the
942 maximal values of the right hand side function are at the corners of
943 the domain, where also the solution is moving most rapidly.
944 It is also nice to see that the solution follows the desired quadratic
945 boundary values along the boundaries of the domain.
946 It can also be useful to verify a computed solution against an analytical
947 solution. For an explanation of this technique, see @ref step_7 "step-7".
949 On the other hand, even though the picture does not show the mesh lines
950 explicitly, you can see them as little kinks in the solution. This clearly
951 indicates that the solution hasn't been computed to very high accuracy and
952 that to get a better solution, we may have to compute on a finer mesh.
954 In three spatial dimensions, visualization is a bit more difficult. The left
955 picture shows the solution and the mesh it was computed on on the surface of
956 the domain. This is nice, but it has the drawback that it completely hides
957 what is happening on the inside. The picture on the right is an attempt at
958 visualizing the interior as well, by showing surfaces where the solution has
959 constant values (as indicated by the legend at the top left). Isosurface
960 pictures look best if
one makes the individual surfaces slightly transparent
961 so that it is possible to see through them and see what's behind.
963 <table width="60%" align="
center">
975 A final remark on visualization: the idea of visualization is to give insight,
976 which is not the same as displaying information. In particular, it is easy to
977 overload a picture with information, but while it shows more information it
978 makes it also more difficult to glean insight. As an example, the program I
979 used to generate these pictures, VisIt, by default puts tick marks on every
980 axis, puts a big fat label "X Axis" on the @f$x@f$ axis and similar for the other
981 axes, shows the file name from which the data was taken in the top left and
982 the name of the user doing so and the time and date on the bottom right. None
984 here: the axes are equally easy to make out because the tripod at the bottom
985 left is still visible, and we know from the program that the domain is
986 @f$[-1,1]^3@f$, so there is no need for tick marks. As a consequence, I have
987 switched off all the extraneous stuff in the picture: the art of visualization
988 is to reduce the picture to those parts that are important to see what
one
989 wants to see, but no more.
993 <a name="extensions"></a>
994 <a name="Possibilitiesforextensions"></a><h3>Possibilities for extensions</h3>
998 Essentially the possibilities for playing around with the program are the same
999 as for the previous
one, except that they will now also
apply to the 3
d
1000 case. For inspiration read up on <a href="step_3.html
#extensions"
1001 target=
"body">possible extensions in the documentation of step 3</a>.
1005 <a name=
"PlainProg"></a>
1006 <h1> The plain program</h1>
1007 @include
"step-4.cc"