638 * <a name=
"step_6-Step6setup_system"></a>
639 * <h4>Step6::setup_system</h4>
643 * The next function sets up all the variables that describe the linear
644 * finite element problem, such as the
DoFHandler, matrices, and
645 * vectors. The difference to what we did in @ref step_5
"step-5" is only that we now also
646 * have to take care of hanging node constraints. These constraints are
647 * handled almost exclusively by the library, i.e. you only need to know
648 * that they exist and how to get them, but you
do not have to know how they
649 * are formed or what exactly is done with them.
653 * At the beginning of the function, you find all the things that are the same
654 * as in @ref step_5
"step-5": setting up the degrees of freedom (
this time we have
655 * quadratic elements, but there is no difference from a user code perspective
656 * to the linear -- or any other degree,
for that matter --
case), generating
657 * the sparsity pattern, and initializing the solution and right hand side
658 * vectors. Note that the sparsity pattern will have significantly more
659 * entries per row now, since there are now 9 degrees of freedom per cell
660 * (rather than only four), that can couple with each other.
664 *
void Step6<dim>::setup_system()
668 * solution.reinit(dof_handler.n_dofs());
669 * system_rhs.reinit(dof_handler.n_dofs());
674 * constraints. Since we will call
this function in a
loop we
first clear
675 * the current set of constraints from the last system and then compute
new
679 * constraints.
clear();
686 * whole boundary) and store the resulting constraints in our
687 * <code>constraints</code>
object. Note that we
do not to apply the
688 * boundary conditions after assembly, like we did in earlier steps: instead
691 * order: if two constraints conflict then the constraint
matrix either
abort
692 * or throw an exception via the
Assert macro.
702 * After all constraints have been added, they need to be
sorted and
703 * rearranged to perform some actions more efficiently. This postprocessing
704 * is done
using the <code>close()</code> function, after which no further
705 * constraints may be added any more:
708 * constraints.close();
712 * Now we
first build our compressed sparsity pattern like we did in the
713 * previous examples. Nevertheless, we
do not
copy it to the
final sparsity
714 * pattern immediately. Note that we call a variant of
716 * argument. We are letting the routine know that we will never write into
717 * the locations given by <code>constraints</code> by setting the argument
718 * <code>keep_constrained_dofs</code> to
false (in other words, that we will
719 * never write into entries of the
matrix that correspond to constrained
720 * degrees of freedom). If we were to condense the
721 * constraints after assembling, we would have to pass <code>true</code>
722 * instead because then we would
first write into these locations only to
723 * later set them to zero again during condensation.
734 * Now all non-zero entries of the
matrix are known (i.e. those from
735 * regularly assembling the matrix and those that were introduced by
736 * eliminating constraints). We may
copy our intermediate
object to the
740 * sparsity_pattern.copy_from(dsp);
744 * We may now,
finally, initialize the sparse
matrix:
747 * system_matrix.reinit(sparsity_pattern);
754 * <a name=
"step_6-Step6assemble_system"></a>
755 * <h4>Step6::assemble_system</h4>
760 * vector on each cell into the global system, we are no longer
using a
761 * hand-written
loop. Instead, we use
763 * this loop while performing Gaussian elimination on rows and columns
764 * corresponding to constrained degrees on freedom.
768 * The rest of the code that forms the local contributions remains
769 * unchanged. It is worth noting, however, that under the hood several things
770 * are different than before. First, the variable <code>dofs_per_cell</code>
771 * and return value of <code>quadrature_formula.
size()</code> now are 9 each,
772 * where they were 4 before. Introducing such variables as abbreviations is a
773 * good strategy to make code work with different elements without having to
774 * change too much code. Secondly, the <code>fe_values</code>
object of course
775 * needs to do other things as well, since the shape functions are now
776 * quadratic, rather than linear, in each coordinate variable. Again, however,
777 * this is something that is completely handled by the library.
781 *
void Step6<dim>::assemble_system()
783 *
const QGauss<dim> quadrature_formula(fe.degree + 1);
786 * quadrature_formula,
790 *
const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
795 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
797 *
for (
const auto &cell : dof_handler.active_cell_iterators())
804 *
for (
const unsigned int q_index : fe_values.quadrature_point_indices())
806 * const double current_coefficient =
807 * coefficient(fe_values.quadrature_point(q_index));
808 *
for (
const unsigned int i : fe_values.dof_indices())
810 * for (const unsigned
int j : fe_values.dof_indices())
812 * (current_coefficient *
813 * fe_values.shape_grad(i, q_index) *
814 * fe_values.shape_grad(j, q_index) *
815 * fe_values.JxW(q_index));
817 * cell_rhs(i) += (fe_values.shape_value(i, q_index) *
819 * fe_values.JxW(q_index));
825 * Finally, transfer the contributions from @p
cell_matrix and
826 * @p cell_rhs into the global objects.
829 * cell->get_dof_indices(local_dof_indices);
830 * constraints.distribute_local_to_global(
831 * cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs);
835 * Now we are done assembling the linear system. The constraint
matrix took
836 * care of applying the boundary conditions and also eliminated hanging node
837 * constraints. The constrained nodes are still in the linear system (there
838 * is a nonzero entry, chosen in a way that the matrix is well conditioned,
839 * on the diagonal of the matrix and all other entries
for this line are set
840 * to zero) but the computed
values are
invalid (i.e., the corresponding
841 * entries in <code>system_rhs</code> are currently meaningless). We compute
842 * the correct
values for these nodes at the
end of the <code>solve</code>
852 * <a name=
"step_6-Step6solve"></a>
853 * <h4>Step6::solve</h4>
857 * We
continue with gradual improvements. The function that solves the linear
858 * system again uses the SSOR preconditioner, and is again unchanged except
859 * that we have to incorporate hanging node constraints. As mentioned above,
861 * hanging node constraints and boundary
values have been removed from the
862 * linear system by giving the rows and columns of the
matrix a special
863 * treatment. This way, the
values for these degrees of freedom have wrong,
864 * but well-defined
values after solving the linear system. What we then have
865 * to
do is to use the constraints to assign to them the
values that they
866 * should have. This process, called <code>distributing</code> constraints,
867 * computes the
values of constrained nodes from the
values of the
868 *
unconstrained ones, and
requires only a single additional function call
869 * that you find at the
end of
this function:
876 *
void Step6<dim>::solve()
878 *
SolverControl solver_control(1000, 1e-6 * system_rhs.l2_norm());
882 * preconditioner.
initialize(system_matrix, 1.2);
884 * solver.solve(system_matrix, solution, system_rhs, preconditioner);
886 * constraints.distribute(solution);
893 * <a name=
"step_6-Step6refine_grid"></a>
894 * <h4>Step6::refine_grid</h4>
898 * We use a sophisticated error estimation scheme to
refine the mesh instead
900 * implements an error estimator
for the Laplace equation; it can in principle
901 * handle variable coefficients, but we will not use these advanced features,
902 * but rather use its most simple form since we are not interested in
903 * quantitative results but only in a quick way to generate locally refined
908 * Although the error estimator derived by Kelly et al. was originally
909 * developed
for the Laplace equation, we have found that it is also well
910 * suited to quickly generate locally refined grids
for a wide
class of
911 * problems. This error estimator uses the solution
gradient's jump at
912 * cell faces (which is a measure for the second derivatives) and
913 * scales it by the size of the cell. It is therefore a measure for the local
914 * smoothness of the solution at the place of each cell and it is thus
915 * understandable that it yields reasonable grids also for hyperbolic
916 * transport problems or the wave equation as well, although these grids are
917 * certainly suboptimal compared to approaches specially tailored to the
918 * problem. This error estimator may therefore be understood as a quick way to
919 * test an adaptive program.
923 * The way the estimator works is to take a <code>DoFHandler</code> object
924 * describing the degrees of freedom and a vector of values for each degree of
925 * freedom as input and compute a single indicator value for each active cell
926 * of the triangulation (i.e. one value for each of the active cells). To do
927 * so, it needs two additional pieces of information: a face quadrature formula,
928 * i.e., a quadrature formula on <code>dim-1</code> dimensional objects. We use
929 * a 3-point Gauss rule again, a choice that is consistent and appropriate with
930 * the bi-quadratic finite element shape functions in this program.
931 * (What constitutes a suitable quadrature rule here of course depends on
932 * knowledge of the way the error estimator evaluates the solution field. As
933 * said above, the jump of the gradient is integrated over each face, which
934 * would be a quadratic function on each face for the quadratic elements in
935 * use in this example. In fact, however, it is the square of the jump of the
936 * gradient, as explained in the documentation of that class, and that is a
937 * quartic function, for which a 3 point Gauss formula is sufficient since it
938 * integrates polynomials up to order 5 exactly.)
942 * Secondly, the function wants a list of boundary indicators for those
943 * boundaries where we have imposed Neumann values of the kind
944 * @f$\partial_n u(\mathbf x) = h(\mathbf x)@f$, along with a function @f$h(\mathbf
945 * x)@f$ for each such boundary. This information is represented by a map from
946 * boundary indicators to function objects describing the Neumann boundary
947 * values. In the present example program, we do not use Neumann boundary
948 * values, so this map is empty, and in fact constructed using the default
949 * constructor of the map in the place where the function call expects the
950 * respective function argument.
954 * The output is a vector of values for all active cells. While it may
955 * make sense to compute the <b>value</b> of a solution degree of freedom
956 * very accurately, it is usually not necessary to compute the <b>error
957 * indicator</b> corresponding to the solution on a cell particularly
958 * accurately. We therefore typically use a vector of floats instead of a vector
959 * of doubles to represent error indicators.
963 * void Step6<dim>::refine_grid()
965 * Vector<float> estimated_error_per_cell(triangulation.n_active_cells());
967 * KellyErrorEstimator<dim>::estimate(dof_handler,
968 * QGauss<dim - 1>(fe.degree + 1),
971 * estimated_error_per_cell);
975 * The above function returned one error indicator value for each cell in
976 * the <code>estimated_error_per_cell</code> array. Refinement is now done
977 * as follows: refine those 30 per cent of the cells with the highest error
978 * values, and coarsen the 3 per cent of cells with the lowest values.
982 * One can easily verify that if the second number were zero, this would
983 * approximately result in a doubling of cells in each step in two space
984 * dimensions, since for each of the 30 per cent of cells, four new would be
985 * replaced, while the remaining 70 per cent of cells remain untouched. In
986 * practice, some more cells are usually produced since it is disallowed
987 * that a cell is refined twice while the neighbor cell is not refined; in
988 * that case, the neighbor cell would be refined as well.
992 * In many applications, the number of cells to be coarsened would be set to
993 * something larger than only three per cent. A non-zero value is useful
994 * especially if for some reason the initial (coarse) grid is already rather
995 * refined. In that case, it might be necessary to refine it in some
996 * regions, while coarsening in some other regions is useful. In our case
997 * here, the initial grid is very coarse, so coarsening is only necessary in
998 * a few regions where over-refinement may have taken place. Thus a small,
999 * non-zero value is appropriate here.
1003 * The following function now takes these refinement indicators and flags
1004 * some cells of the triangulation for refinement or coarsening using the
1005 * method described above. It is from a class that implements several
1006 * different algorithms to refine a triangulation based on cell-wise error
1010 * GridRefinement::refine_and_coarsen_fixed_number(triangulation,
1011 * estimated_error_per_cell,
1017 * After the previous function has exited, some cells are flagged for
1018 * refinement, and some other for coarsening. The refinement or coarsening
1019 * itself is not performed by now, however, since there are cases where
1020 * further modifications of these flags is useful. Here, we don't want to
do
1021 * any such thing, so we can tell the
triangulation to perform the actions
1022 *
for which the cells are flagged:
1032 * <a name=
"step_6-Step6output_results"></a>
1033 * <h4>Step6::output_results</h4>
1037 * At the
end of computations on each grid, and just before we
continue the
1038 * next cycle with mesh refinement, we want to output the results from
this
1043 * We have already seen in @ref step_1
"step-1" how
this can be achieved
for the
1044 * mesh itself. Here, we change a few things:
1046 * <li>We use two different formats:
gnuplot and VTU.</li>
1047 * <li>We embed the cycle number in the output file name.</li>
1049 * provide a few extra visualization arguments so that edges appear
1050 * curved. This is explained in further detail in @ref step_10
"step-10".</li>
1054 *
template <
int dim>
1055 *
void Step6<dim>::output_results(
const unsigned int cycle)
const
1059 * std::ofstream output(
"grid-" + std::to_string(cycle) +
".gnuplot");
1061 * grid_out.set_flags(gnuplot_flags);
1069 * data_out.add_data_vector(solution,
"solution");
1070 * data_out.build_patches();
1072 * std::ofstream output(
"solution-" + std::to_string(cycle) +
".vtu");
1073 * data_out.write_vtu(output);
1081 * <a name=
"step_6-Step6run"></a>
1082 * <h4>Step6::run</h4>
1086 * The
final function before <code>main()</code> is again the main driver of
1087 * the
class, <code>
run()</code>. It is similar to the one of @ref step_5
"step-5", except
1088 * that we generate a file in the program again instead of reading it from
1089 * disk, in that we adaptively instead of globally
refine the mesh, and that
1090 * we output the solution on the
final mesh in the present function.
1094 * The
first block in the main
loop of the function deals with mesh generation.
1095 * If
this is the
first cycle of the program, instead of reading the grid from
1096 * a file on disk as in the previous example, we now again create it
using a
1097 * library function. The domain is again a circle with center at the origin and
1098 * a radius of one (these are the two hidden arguments to the function, which
1099 * have
default values).
1103 * You will notice by looking at the coarse grid that it is of inferior
1104 * quality than the one which we read from the file in the previous example:
1105 * the cells are less equally formed. However,
using the library function
this
1106 * program works in any space dimension, which was not the
case before.
1110 * In
case we find that
this is not the
first cycle, we want to
refine the
1111 * grid. Unlike the global refinement employed in the last example program, we
1112 * now use the adaptive procedure described above.
1116 * The rest of the
loop looks as before:
1119 *
template <
int dim>
1120 *
void Step6<dim>::run()
1122 *
for (
unsigned int cycle = 0; cycle < 8; ++cycle)
1124 * std::cout <<
"Cycle " << cycle <<
':' << std::endl;
1135 * std::cout <<
" Number of active cells: "
1140 * std::cout <<
" Number of degrees of freedom: " << dof_handler.n_dofs()
1143 * assemble_system();
1145 * output_results(cycle);
1153 * <a name=
"step_6-Thecodemaincodefunction"></a>
1154 * <h3>The <code>main</code> function</h3>
1158 * The main function is unaltered in its functionality from the previous
1159 * example, but we have taken a step of additional caution. Sometimes,
1160 * something goes wrong (such as insufficient disk space upon writing an
1161 * output file, not enough memory when trying to allocate a vector or a
1162 * matrix, or
if we can
't read from or write to a file for whatever reason),
1163 * and in these cases the library will throw exceptions. Since these are
1164 * run-time problems, not programming errors that can be fixed once and for
1165 * all, this kind of exceptions is not switched off in optimized mode, in
1166 * contrast to the <code>Assert</code> macro which we have used to test
1167 * against programming errors. If uncaught, these exceptions propagate the
1168 * call tree up to the <code>main</code> function, and if they are not caught
1169 * there either, the program is aborted. In many cases, like if there is not
1170 * enough memory or disk space, we can't
do anything but we can at least print
1171 * some text trying to explain the reason why the program failed. A way to
do
1172 * so is shown in the following. It is certainly useful to write any larger
1173 * program in
this way, and you can
do so by more or less copying
this
1174 * function except
for the <code>try</code> block that actually encodes the
1175 * functionality particular to the present application.
1182 * The
general idea behind the layout of
this function is as follows: let
's
1183 * try to run the program as we did before...
1188 * Step6<2> laplace_problem_2d;
1189 * laplace_problem_2d.run();
1193 * ...and if this should fail, try to gather as much information as
1194 * possible. Specifically, if the exception that was thrown is an object of
1195 * a class that is derived from the C++ standard class
1196 * <code>exception</code>, then we can use the <code>what</code> member
1197 * function to get a string which describes the reason why the exception was
1202 * The deal.II exception classes are all derived from the standard class,
1203 * and in particular, the <code>exc.what()</code> function will return
1204 * approximately the same string as would be generated if the exception was
1205 * thrown using the <code>Assert</code> macro. You have seen the output of
1206 * such an exception in the previous example, and you then know that it
1207 * contains the file and line number of where the exception occurred, and
1208 * some other information. This is also what the following statements would
1213 * Apart from this, there isn't much that we can
do except exiting the
1214 * program with an error code (
this is what the <code>
return 1;</code>
1218 * catch (
std::exception &exc)
1222 * <<
"----------------------------------------------------"
1224 * std::cerr <<
"Exception on processing: " << std::endl
1225 * << exc.what() << std::endl
1226 * <<
"Aborting!" << std::endl
1227 * <<
"----------------------------------------------------"
1234 * If the exception that was thrown somewhere was not an
object of a
class
1235 * derived from the standard <code>exception</code>
class, then we can
't do
1236 * anything at all. We then simply print an error message and exit.
1241 * std::cerr << std::endl
1243 * << "----------------------------------------------------"
1245 * std::cerr << "Unknown exception!" << std::endl
1246 * << "Aborting!" << std::endl
1247 * << "----------------------------------------------------"
1254 * If we got to this point, there was no exception which propagated up to
1255 * the main function (there may have been exceptions, but they were caught
1256 * somewhere in the program or the library). Therefore, the program
1257 * performed as was expected and we can return without error.
1263<a name="step_6-Results"></a><h1>Results</h1>
1267The output of the program looks as follows:
1270 Number of active cells: 20
1271 Number of degrees of freedom: 89
1273 Number of active cells: 38
1274 Number of degrees of freedom: 183
1276 Number of active cells: 71
1277 Number of degrees of freedom: 325
1279 Number of active cells: 146
1280 Number of degrees of freedom: 689
1282 Number of active cells: 284
1283 Number of degrees of freedom: 1373
1285 Number of active cells: 599
1286 Number of degrees of freedom: 2769
1288 Number of active cells: 1241
1289 Number of degrees of freedom: 5833
1291 Number of active cells: 2507
1292 Number of degrees of freedom: 11916
1297As intended, the number of cells roughly doubles in each cycle. The
1298number of degrees is slightly more than four times the number of
1299cells; one would expect a factor of exactly four in two spatial
1300dimensions on an infinite grid (since the spacing between the degrees
1301of freedom is half the cell width: one additional degree of freedom on
1302each edge and one in the middle of each cell), but it is larger than
1303that factor due to the finite size of the mesh and due to additional
1304degrees of freedom which are introduced by hanging nodes and local
1309The program outputs the solution and mesh in each cycle of the
1310refinement loop. The solution looks as follows:
1312<img src="https://www.dealii.org/images/steps/developer/step-6.solution.9.2.png" alt="">
1314It is interesting to follow how the program arrives at the final mesh:
1316<div class="twocolumn" style="width: 80%">
1318 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_0.svg"
1319 alt="Initial grid: the five-cell circle grid with one global refinement."
1320 width="300" height="300">
1323 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_1.svg"
1324 alt="First grid: the five-cell circle grid with two global refinements."
1325 width="300" height="300">
1328 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_2.svg"
1329 alt="Second grid: the five-cell circle grid with one adaptive refinement."
1330 width="300" height="300">
1333 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_3.svg"
1334 alt="Third grid: the five-cell circle grid with two adaptive
1335 refinements, showing clustering around the inner circle."
1336 width="300" height="300">
1339 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_4.svg"
1340 alt="Fourth grid: the five-cell circle grid with three adaptive
1341 refinements, showing clustering around the inner circle."
1342 width="300" height="300">
1345 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_5.svg"
1346 alt="Fifth grid: the five-cell circle grid with four adaptive
1347 refinements, showing clustering around the inner circle."
1348 width="300" height="300">
1351 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_6.svg"
1352 alt="Sixth grid: the five-cell circle grid with five adaptive
1353 refinements, showing clustering around the inner circle."
1354 width="300" height="300">
1357 <img src="https://www.dealii.org/images/steps/developer/step_6_grid_7.svg"
1358 alt="Last grid: the five-cell circle grid with six adaptive
1359 refinements, showing that most cells are clustered around the inner circle."
1360 width="300" height="300">
1365It is clearly visible that the region where the solution has a kink,
1366i.e. the circle at radial distance 0.5 from the center, is
1367refined most. Furthermore, the central region where the solution is
1368very smooth and almost flat, is almost not refined at all, but this
1369results from the fact that we did not take into account that the
1370coefficient is large there. The region outside is refined rather
1371arbitrarily, since the second derivative is constant there and refinement
1372is therefore mostly based on the size of the cells and their deviation
1373from the optimal square.
1377<a name="step-6-extensions"></a>
1378<a name="step_6-Possibilitiesforextensions"></a><h3>Possibilities for extensions</h3>
1381<a name="step_6-Solversandpreconditioners"></a><h4>Solvers and preconditioners</h4>
1384One thing that is always worth playing around with if one solves
1385problems of appreciable size (much bigger than the one we have here)
1386is to try different solvers or preconditioners. In the current case,
1387the linear system is symmetric and positive definite, which makes the
1388Conjugate Gradient (CG) algorithm pretty much the canonical choice for solving. However,
1389the SSOR preconditioner we use in the <code>solve()</code> function is
1392In deal.II, it is relatively simple to change the preconditioner.
1393Several simple preconditioner choices are accessible
1394by changing the following two lines
1396 PreconditionSSOR<SparseMatrix<double>> preconditioner;
1397 preconditioner.initialize(system_matrix, 1.2);
1399of code in the program. For example, switching this into
1401 PreconditionSSOR<SparseMatrix<double>> preconditioner;
1402 preconditioner.initialize(system_matrix, 1.0);
1404allows us to try out a different relaxation parameter for SSOR (1.0 instead
1405of the 1.2 in the original program). Similarly, by using
1407 PreconditionJacobi<SparseMatrix<double>> preconditioner;
1408 preconditioner.initialize(system_matrix);
1410we can use Jacobi as a preconditioner. And by using
1412 SparseILU<double> preconditioner;
1413 preconditioner.initialize(system_matrix);
1415we can use a simple incomplete LU decomposition without any thresholding or
1416strengthening of the diagonal (to use this preconditioner, you have to also
1417add the header file <code>deal.II/lac/sparse_ilu.h</code> to the include list
1418at the top of the file).
1420Using these various different preconditioners, we can compare the
1421number of CG iterations needed (available through the
1422<code>solver_control.last_step()</code> call, see
1423@ref step_4 "step-4") as well as CPU time needed (using the Timer class,
1424discussed, for example, in @ref step_28 "step-28") and get the
1425following results (left: iterations; right: CPU time):
1427<table width="60%" align="center">
1430 <img src="https://www.dealii.org/images/steps/developer/step-6.q2.dofs_vs_iterations.png" alt="">
1433 <img src="https://www.dealii.org/images/steps/developer/step-6.q2.dofs_vs_time.png" alt="">
1438As we can see, all preconditioners behave pretty much the same on this
1439simple problem, with the number of iterations growing like @f${\cal
1440O}(N^{1/2})@f$ and because each iteration requires around @f${\cal
1441O}(N)@f$ operations the total CPU time grows like @f${\cal
1442O}(N^{3/2})@f$ (for the few smallest meshes, the CPU time is so small
1443that it doesn't record). Note that even though it is the simplest
1444method, Jacobi is the fastest
for this problem.
1446The situation changes slightly when the finite element is not a
1447bi-quadratic one (i.e., polynomial degree two) as selected in the
1448constructor of
this program, but a bi-linear one (polynomial degree one).
1449If one makes
this change, the results are as follows:
1451<table width=
"60%" align=
"center">
1454 <img src=
"https://www.dealii.org/images/steps/developer/step-6.q1.dofs_vs_iterations.png" alt=
"">
1457 <img src=
"https://www.dealii.org/images/steps/developer/step-6.q1.dofs_vs_time.png" alt=
"">
1462In other words,
while the increase in iterations and CPU time is as
1463before, Jacobi is now the method that
requires the most iterations; it
1464is still the fastest one, however, owing to the simplicity of the
1465operations it has to perform. This is not to say that Jacobi
1466is actually a good preconditioner --
for problems of appreciable
size, it is
1467definitely not, and other methods will be substantially better -- but really
1468only that it is fast because its implementation is so simple that it can
1469compensate
for a larger number of iterations.
1471The message to take away from
this is not that simplicity in
1472preconditioners is
always best. While
this may be
true for the current
1473problem, it definitely is not once we move to more complicated
1474problems (elasticity or Stokes,
for examples @ref step_8
"step-8" or
1475@ref step_22
"step-22"). Secondly, all of these preconditioners still
1476lead to an increase in the number of iterations as the number @f$N@f$ of
1477degrees of freedom grows,
for example @f${\cal O}(N^\alpha)@f$;
this, in
1478turn, leads to a total growth in effort as @f${\cal O}(N^{1+\alpha})@f$
1479since each iteration takes @f${\cal O}(N)@f$ work. This behavior is
1480undesirable: we would really like to solve linear systems with @f$N@f$
1481unknowns in a total of @f${\cal O}(N)@f$ work; there is a
class
1482of preconditioners that can achieve
this, namely geometric (@ref step_16
"step-16",
1483@ref step_37
"step-37", @ref step_39
"step-39")
1484or algebraic multigrid (@ref step_31
"step-31", @ref step_40
"step-40", and several others)
1485preconditioners. They are, however, significantly more complex than
1486the preconditioners outlined above, and so we will leave their use
1487to these later tutorial programs. The
point to make, however, is
1488that
"real" finite element programs
do not use the preconditioners
1489we mention above: These are simply shown
for expository purposes.
1491Finally, the last message to take
1492home is that when the
data shown above was generated (in 2018), linear
1493systems with 100,000 unknowns are
1494easily solved on a desktop or laptop machine in about a
second, making
1495the solution of relatively simple 2
d problems even to very high
1496accuracy not that big a task as it used to be in the
1497past. At the same time, the situation
for 3
d problems continues to be
1498quite different: A uniform 2
d mesh with 100,000 unknowns corresponds to
1499a grid with about @f$300 \times 300@f$ nodes; the corresponding 3
d mesh has
1500@f$300 \times 300 \times 300@f$ nodes and 30 million unknowns. Because
1501finite element matrices in 3
d have many more
nonzero entries than in 2
d,
1502solving these linear systems will not only take 300 times as much CPU
1503time, but substantially longer. In other words, achieving the
1504same resolution in 3
d *is* quite a large problem, and solving it
1505within a reasonable amount of time *will* require much more work to
1506implement better linear solvers. As mentioned above, multigrid methods
1507and
matrix-free methods (see,
for example, @ref step_37
"step-37"), along with
1508parallelization (@ref step_40
"step-40") will be necessary, but are then also able
1509to comfortably solve such linear systems.
1513<a name=
"step_6-Abettermesh"></a><h4>A better mesh</h4>
1516If you look at the meshes above, you will see even though the domain is the
1517unit disk, and the jump in the coefficient lies along a circle, the cells
1518that make up the mesh
do not track
this geometry well. The reason, already hinted
1519at in @ref step_1
"step-1", is that in the absence of other information,
1521coarse grid cells but has, of course, no real idea what kind of geometry they
1522might represent when looked at together. For this reason, we need to tell
1523the
Triangulation what to do when a cell is refined: where should the new
1524vertices at the edge midpoints and the cell midpoint be located so that the
1525child cells better represent the desired geometry than the parent cell.
1527To visualize what the
triangulation actually knows about the geometry,
1528it is not enough to just output the location of vertices and draw a
1529straight line for each edge; instead, we have to output both interior
1530and boundary lines as multiple segments so that they look
1531curved. We can do this by making one change to the
gnuplot part of
1532<code>output_results</code>:
1536 std::ofstream output(
"grid-" + std::to_string(cycle) +
".gnuplot");
1544In the code above, we already
do this for faces that sit at the boundary:
this
1547<i>interior</i> also track a circular domain, we need to work a bit harder,
1548though. First, recall that our coarse mesh consists of a central square
1549cell and four cells around it. Now
first consider what would happen
if we
1551but also the four cells at the perimeter as well as all of their faces. We can
1552do this by adding the following snippet (testing that the center of a cell is
1553larger than a small multiple, say one tenth, of the cell diameter away from
1554center of the mesh only fails
for the central square of the mesh):
1560for (
const auto &cell :
triangulation.active_cell_iterators())
1561 if (mesh_center.distance (cell->center()) > cell->
diameter()/10)
1562 cell->set_all_manifold_ids(0);
1567After a few global refinement steps,
this would lead to a mesh of the following
1571 <div
class=
"onecolumn" style=
"width: 80%">
1573 <img src=
"https://www.dealii.org/images/steps/developer/step_6_bad_grid_4.svg"
1574 alt=
"Grid where some central cells are nearly triangular."
1575 width=
"300" height=
"300">
1579This is not a good mesh: the central cell has been refined in such a way that
1580the children located in the four corners of the original central cell
1581<i>degenerate</i>: they all tend towards triangles as mesh refinement
1582continues. This means that the Jacobian
matrix of the transformation from
1583reference cell to actual cell degenerates
for these cells, and because
1584all error estimates
for finite element solutions contain the
norm of the
1585inverse of the Jacobian
matrix, you will get very large errors on these
1586cells and, in the limit as mesh refinement, a loss of convergence order because
1587the cells in these corners become worse and worse under mesh refinement.
1589So we need something smarter. To
this end, consider the following solution
1590originally developed by Konstantin Ladutenko. We will use the following code:
1595const double core_radius = 1.0/5.0,
1596 inner_radius = 1.0/3.0;
1609for (
const auto &cell :
triangulation.active_cell_iterators())
1610 if (mesh_center.distance(cell->center()) < 1
e-5)
1613 cell->vertex(v) *= core_radius/mesh_center.distance(cell->vertex(v));
1617for (
const auto &cell :
triangulation.active_cell_iterators())
1618 if (mesh_center.distance(cell->center()) >= 1
e-5)
1619 cell->set_refine_flag();
1630for (
const auto &cell :
triangulation.active_cell_iterators())
1633 const double dist = mesh_center.
distance(cell->vertex(v));
1634 if (dist > core_radius*1.0001 && dist < 0.9999)
1635 cell->vertex(v) *= inner_radius/dist;
1649for (
const auto &cell :
triangulation.active_cell_iterators())
1651 bool is_in_inner_circle =
false;
1653 if (mesh_center.distance(cell->vertex(v)) < inner_radius)
1655 is_in_inner_circle =
true;
1659 if (is_in_inner_circle ==
false)
1664 cell->set_all_manifold_ids(0);
1668This code then generates the following, much better sequence of meshes:
1670<div
class=
"twocolumn" style=
"width: 80%">
1672 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_0_ladutenko.svg"
1673 alt=
"Initial grid: the Ladutenko grid with one global refinement."
1674 width=
"300" height=
"300">
1677 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_1_ladutenko.svg"
1678 alt=
"First adaptively refined Ladutenko grid."
1679 width=
"300" height=
"300">
1682 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_2_ladutenko.svg"
1683 alt=
"Second adaptively refined Ladutenko grid."
1684 width=
"300" height=
"300">
1687 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_3_ladutenko.svg"
1688 alt=
"Third adaptively refined Ladutenko grid."
1689 width=
"300" height=
"300">
1692 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_4_ladutenko.svg"
1693 alt=
"Fourth adaptively refined Ladutenko grid. The cells are clustered
1694 along the inner circle."
1695 width=
"300" height=
"300">
1698 <img src=
"https://www.dealii.org/images/steps/developer/step_6_grid_5_ladutenko.svg"
1699 alt=
"Fifth adaptively refined Ladutenko grid: the cells are clustered
1700 along the inner circle."
1701 width=
"300" height=
"300">
1705Creating good meshes, and in particular making them fit the geometry you
1706want, is a complex topic in itself. You can find much more on
this in
1707@ref step_49
"step-49", @ref step_53
"step-53", and @ref step_54
"step-54", among other tutorial programs that cover
1708the issue. @ref step_65
"step-65" shows another, less manual way to achieve a mesh
1709well fit to the problem here.
1710Information on curved domains can also be found in the
1711documentation topic on @ref manifold
"Manifold descriptions".
1713Why does it make sense to choose a mesh that tracks the
internal
1714interface? There are a number of reasons, but the most essential one
1715comes down to what we actually integrate in our bilinear
1716form. Conceptually, we want to integrate the term @f$A_{ij}^
K=\int_K
1717a(\mathbf x) \nabla \varphi_i(\mathbf x) \nabla \varphi_j(\mathbf x) ;
dx@f$ as the
1718contribution of cell @f$K@f$ to the
matrix entry @f$A_{ij}@f$. We can not
1719compute it exactly and have to resort to quadrature. We know that
1720quadrature is accurate
if the integrand is smooth. That is because
1721quadrature in essence computes a polynomial approximation to the
1722integrand that coincides with the integrand in the quadrature points,
1723and then computes the
volume under
this polynomial as an approximation
1724to the
volume under the original integrand. This polynomial
1725interpolant is accurate
if the integrand is smooth on a cell, but it
1726is usually rather inaccurate
if the integrand is discontinuous on a
1729Consequently, it is worthwhile to align cells in such a way that the
1730interfaces across which the coefficient is discontinuous are aligned
1731with cell interfaces. This way, the coefficient is
constant on each
1732cell, following which the integrand will be smooth, and its polynomial
1733approximation and the quadrature approximation of the integral will
1734both be accurate. Note that such an alignment is common in many
1735practical cases, so deal.II provides a number of
functions (such as
1736@ref GlossMaterialId
"material_id") to help manage such a scenario.
1737Refer to @ref step_28
"step-28" and @ref step_46
"step-46" for examples of how material ids can be
1740Finally, let us consider the
case of a coefficient that has a smooth
1741and non-uniform distribution in space. We can repeat once again all of
1742the above discussion on the representation of such a function with the
1743quadrature. So, to simulate it accurately there are a few readily
1744available options: you could
reduce the cell
size, increase the order
1745of the polynomial used in the quadrature formula, select a more
1746appropriate quadrature formula, or perform a combination of these
1747steps. The key is that providing the best fit of the coefficient
's
1748spatial dependence with the quadrature polynomial will lead to a more
1749accurate finite element solution of the PDE.
1751As a final note: The discussion in the previous paragraphs shows, we here
1752have a very concrete way of stating what we think of a good mesh -- it should
1753be aligned with the jump in the coefficient. But one could also have asked
1754this kind of question in a more general setting: Given some equation with
1755a smooth solution and smooth coefficients, can we say what a good mesh
1756would look like? This is a question for which the answer is easier to state
1757in intuitive terms than mathematically: A good mesh has cells that all,
1758by and large, look like squares (or cubes, in 3d). A bad mesh would contain
1759cells that are very elongated in some directions or, more generally, for which
1760there are cells that have both short and long edges. There are many ways
1761in which one could assign a numerical quality index to each cell that measures
1762whether the cell is "good" or "bad"; some of these are often chosen because
1763they are cheap and easy to compute, whereas others are based on what enters
1764into proofs of convergence. An example of the former would be the ratio of
1765the longest to the shortest edge of a cell: In the ideal case, that ratio
1766would be one; bad cells have values much larger than one. An example of the
1767latter kind would consider the gradient (the "Jacobian") of the mapping
1768from the reference cell @f$\hat K=[0,1]^d@f$ to the real cell @f$K@f$; this
1769gradient is a matrix, and a quantity that enters into error estimates
1770is the maximum over all points on the reference cell of the ratio of the
1771largest to the smallest eigenvalue of this matrix. It is again not difficult
1772to see that this ratio is constant if the cell @f$K@f$ is an affine image of
1773@f$\hat K@f$, and that it is one for squares and cubes.
1775In practice, it might be interesting to visualize such quality measures.
1776The function GridTools::compute_aspect_ratio_of_cells() provides one
1777way to get this kind of information. Even better, visualization tools
1778such as VisIt often allow you to visualize this sort of information
1779for a variety of measures from within the visualization software
1780itself; in the case of VisIt, just add a "pseudo-color" plot and select
1781one of the mesh quality measures instead of the solution field.
1784<a name="step_6-Playingwiththeregularityofthesolution"></a><h4>Playing with the regularity of the solution</h4>
1787From a mathematical perspective, solutions of the Laplace equation
1791on smoothly bounded, convex domains are known to be smooth themselves. The exact degree
1792of smoothness, i.e., the function space in which the solution lives, depends
1793on how smooth exactly the boundary of the domain is, and how smooth the right
1794hand side is. Some regularity of the solution may be lost at the boundary, but
1795one generally has that the solution is twice more differentiable in
1796compact subsets of the domain than the right hand side.
1797If, in particular, the right hand side satisfies @f$f\in C^\infty(\Omega)@f$, then
1798@f$u \in C^\infty(\Omega_i)@f$ where @f$\Omega_i@f$ is any compact subset of @f$\Omega@f$
1799(@f$\Omega@f$ is an open domain, so a compact subset needs to keep a positive distance
1800from @f$\partial\Omega@f$).
1802The situation we chose for the current example is different, however: we look
1803at an equation with a non-constant coefficient @f$a(\mathbf x)@f$:
1805 -\nabla \cdot (a \nabla u) = f.
1807Here, if @f$a@f$ is not smooth, then the solution will not be smooth either,
1808regardless of @f$f@f$. In particular, we expect that wherever @f$a@f$ is discontinuous
1809along a line (or along a plane in 3d),
1810the solution will have a kink. This is easy to see: if for example @f$f@f$
1811is continuous, then @f$f=-\nabla \cdot (a \nabla u)@f$ needs to be
1812continuous. This means that @f$a \nabla u@f$ must be continuously differentiable
1813(not have a kink). Consequently, if @f$a@f$ has a discontinuity, then @f$\nabla u@f$
1814must have an opposite discontinuity so that the two exactly cancel and their
1815product yields a function without a discontinuity. But for @f$\nabla u@f$ to have
1816a discontinuity, @f$u@f$ must have a kink. This is of course exactly what is
1817happening in the current example, and easy to observe in the pictures of the
1820In general, if the coefficient @f$a(\mathbf x)@f$ is discontinuous along a line in 2d,
1821or a plane in 3d, then the solution may have a kink, but the gradient of the
1822solution will not go to infinity. That means, that the solution is at least
1823still in the <a href="https://en.wikipedia.org/wiki/Sobolev_space">Sobolev space</a>
1824@f$W^{1,\infty}@f$ (i.e., roughly speaking, in the
1825space of functions whose derivatives are bounded). On the other hand,
1826we know that in the most
1827extreme cases -- i.e., where the domain has reentrant corners, the
1828right hand side only satisfies @f$f\in H^{-1}@f$, or the coefficient @f$a@f$ is only in
1829@f$L^\infty@f$ -- all we can expect is that @f$u\in H^1@f$ (i.e., the
1831href="https://en.wikipedia.org/wiki/Sobolev_space#Sobolev_spaces_with_integer_k">Sobolev
1832space</a> of functions whose derivative is square integrable), a much larger space than
1833@f$W^{1,\infty}@f$. It is not very difficult to create cases where
1834the solution is in a space @f$H^{1+s}@f$ where we can get @f$s@f$ to become as small
1835as we want. Such cases are often used to test adaptive finite element
1836methods because the mesh will have to resolve the singularity that causes
1837the solution to not be in @f$W^{1,\infty}@f$ any more.
1839The typical example one uses for this is called the <i>Kellogg problem</i>
1840(referring to @cite Kel74), which in the commonly used form has a coefficient
1841@f$a(\mathbf x)@f$ that has different values in the four quadrants of the plane
1842(or eight different values in the octants of @f${\mathbb R}^3@f$). The exact degree
1843of regularity (the @f$s@f$ in the index of the Sobolev space above) depends on the
1844values of @f$a(\mathbf x)@f$ coming together at the origin, and by choosing the
1845jumps large enough, the regularity of the solution can be made as close as
1846desired to @f$H^1@f$.
1848To implement something like this, one could replace the coefficient
1849function by the following (shown here only for the 2d case):
1852double coefficient (const Point<dim> &p)
1854 if ((p[0] < 0) && (p[1] < 0)) // lower left quadrant
1856 else if ((p[0] >= 0) && (p[1] < 0)) // lower right quadrant
1858 else if ((p[0] < 0) && (p[1] >= 0)) // upper left quadrant
1860 else if ((p[0] >= 0) && (p[1] >= 0)) // upper right quadrant
1863 DEAL_II_ASSERT_UNREACHABLE();
1866(Adding the `DEAL_II_ASSERT_UNREACHABLE();` call at the end ensures that either an exception
1867is thrown or that the program aborts if we ever get to that point
1868-- which of course we shouldn't,
1869but
this is a good way to insure yourself: We all make mistakes by
1870sometimes not thinking of all cases,
for example by checking
1871for <code>p[0]</code> to be less than and greater than zero,
1872rather than greater-or-
equal to zero, and thereby forgetting
1873some cases that would otherwise lead to bugs that are awkward
1876By playing with such cases where four or more sectors come
1877together and on which the coefficient has different values, one can
1878construct cases where the solution has singularities at the
1879origin. One can also see how the meshes are refined in such cases.
1882<a name="step_6-PlainProg"></a>
1883<h1> The plain program</h1>
void distribute_local_to_global(const InVector &local_vector, const std::vector< size_type > &local_dof_indices, OutVector &global_vector) const
void attach_dof_handler(const DoFHandler< dim, spacedim > &)
void distribute_dofs(const FiniteElement< dim, spacedim > &fe)
void set_flags(const GridOutFlags::DX &flags)
void write_gnuplot(const Triangulation< dim, spacedim > &tria, std::ostream &out, const Mapping< dim, spacedim > *mapping=nullptr) const
numbers::NumberTraits< Number >::real_type distance(const Point< dim, Number > &p) const
void initialize(const MatrixType &A, const AdditionalData ¶meters=AdditionalData())
#define Assert(cond, exc)
void loop(IteratorType begin, std_cxx20::type_identity_t< IteratorType > end, DOFINFO &dinfo, INFOBOX &info, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &)> &cell_worker, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &)> &boundary_worker, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &, typename INFOBOX::CellInfo &)> &face_worker, AssemblerType &assembler, const LoopControl &lctrl=LoopControl())
void make_hanging_node_constraints(const DoFHandler< dim, spacedim > &dof_handler, AffineConstraints< number > &constraints)
void make_sparsity_pattern(const DoFHandler< dim, spacedim > &dof_handler, SparsityPatternBase &sparsity_pattern, const AffineConstraints< number > &constraints={}, const bool keep_constrained_dofs=true, const types::subdomain_id subdomain_id=numbers::invalid_subdomain_id)
@ update_values
Shape function values.
@ update_JxW_values
Transformed quadrature weights.
@ update_gradients
Shape function gradients.
@ update_quadrature_points
Transformed quadrature points.
std::vector< index_type > data
CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt K
void hyper_ball(Triangulation< dim > &tria, const Point< dim > ¢er=Point< dim >(), const double radius=1., const bool attach_spherical_manifold_on_boundary_cells=false)
void refine(Triangulation< dim, spacedim > &tria, const Vector< Number > &criteria, const double threshold, const unsigned int max_to_mark=numbers::invalid_unsigned_int)
@ matrix
Contents is actually a matrix.
@ general
No special properties.
void cell_matrix(FullMatrix< double > &M, const FEValuesBase< dim > &fe, const FEValuesBase< dim > &fetest, const ArrayView< const std::vector< double > > &velocity, const double factor=1.)
double norm(const FEValuesBase< dim > &fe, const ArrayView< const std::vector< Tensor< 1, dim > > > &Du)
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
SymmetricTensor< 2, dim, Number > e(const Tensor< 2, dim, Number > &F)
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
VectorType::value_type * end(VectorType &V)
T reduce(const T &local_value, const MPI_Comm comm, const std::function< T(const T &, const T &)> &combiner, const unsigned int root_process=0)
void run(const Iterator &begin, const std_cxx20::type_identity_t< Iterator > &end, Worker worker, Copier copier, const ScratchData &sample_scratch_data, const CopyData &sample_copy_data, const unsigned int queue_length, const unsigned int chunk_size)
void abort(const ExceptionBase &exc) noexcept
void copy(const T *begin, const T *end, U *dest)
int(&) functions(const void *v1, const void *v2)
void assemble(const MeshWorker::DoFInfoBox< dim, DOFINFO > &dinfo, A *assembler)
const ::parallel::distributed::Triangulation< dim, spacedim > * triangulation