811 *
const unsigned int = 0)
const override
822 * <a name=
"Pressureboundaryvalues"></a>
823 * <h4>Pressure boundary
values</h4>
827 * The next are pressure boundary
values. As mentioned in the introduction,
828 * we choose a linear pressure field:
832 *
class PressureBoundaryValues :
public Function<dim>
835 * PressureBoundaryValues()
840 *
const unsigned int = 0) const override
851 * <a name=
"Saturationboundaryvalues"></a>
852 * <h4>Saturation boundary
values</h4>
856 * Then we also need boundary
values on the inflow portions of the
857 * boundary. The question whether something is an inflow part is decided
858 * when assembling the right hand side, we only have to provide a functional
859 * description of the boundary
values. This is as explained in the
864 *
class SaturationBoundaryValues :
public Function<dim>
867 * SaturationBoundaryValues()
872 *
const unsigned int = 0) const override
886 * <a name=
"Initialdata"></a>
887 * <h4>Initial data</h4>
891 * Finally, we need
initial data. In reality, we only need
initial data
for
892 * the saturation, but we are lazy, so we will later, before the
first time
893 * step, simply
interpolate the entire solution
for the previous time step
894 * from a function that contains all vector components.
898 * We therefore simply create a function that returns zero in all
899 * components. We
do that by simply forward every function to the
901 *
this program where we presently use the <code>InitialValues</code>
class?
902 * Because
this way it is simpler to later go back and choose a different
907 *
class InitialValues :
public Function<dim>
915 *
const unsigned int component = 0) const override
932 * <a name=
"Theinversepermeabilitytensor"></a>
933 * <h3>The inverse permeability tensor</h3>
937 * As announced in the introduction, we implement two different permeability
938 * tensor fields. Each of them we put into a
namespace of its own, so that
939 * it will be easy later to replace use of one by the other in the code.
944 * <a name=
"Singlecurvingcrackpermeability"></a>
945 * <h4>Single curving crack permeability</h4>
949 * The
first function
for the permeability was the one that models a single
950 * curving crack. It was already used at the
end of @ref step_20
"step-20", and its
951 * functional form is given in the introduction of the present tutorial
952 * program. As in some previous programs, we have to declare a (seemingly
953 * unnecessary)
default constructor of the KInverse
class to avoid warnings
954 * from some compilers:
957 *
namespace SingleCurvingCrack
973 *
for (
unsigned int p = 0; p < points.size(); ++p)
977 *
const double distance_to_flowline =
978 * std::fabs(points[p][1] - 0.5 - 0.1 *
std::sin(10 * points[p][0]));
980 *
const double permeability =
985 *
for (
unsigned int d = 0;
d < dim; ++
d)
986 * values[p][d][d] = 1. / permeability;
996 * <a name=
"Randommediumpermeability"></a>
997 * <h4>Random medium permeability</h4>
1001 * This function does as announced in the introduction, i.e. it creates an
1002 * overlay of exponentials at
random places. There is one thing worth
1003 * considering
for this class. The issue centers around the problem that the
1004 *
class creates the centers of the exponentials using a
random function. If
1005 * we therefore created the centers each time we create an
object of the
1006 * present type, we would get a different list of centers each time. That
's
1007 * not what we expect from classes of this type: they should reliably
1008 * represent the same function.
1012 * The solution to this problem is to make the list of centers a static
1013 * member variable of this class, i.e. there exists exactly one such
1014 * variable for the entire program, rather than for each object of this
1015 * type. That's exactly what we are going to
do.
1019 * The next problem, however, is that we need a way to initialize
this
1020 * variable. Since
this variable is initialized at the beginning of the
1021 * program, we can
't use a regular member function for that since there may
1022 * not be an object of this type around at the time. The C++ standard
1023 * therefore says that only non-member and static member functions can be
1024 * used to initialize a static variable. We use the latter possibility by
1025 * defining a function <code>get_centers</code> that computes the list of
1026 * center points when called.
1030 * Note that this class works just fine in both 2d and 3d, with the only
1031 * difference being that we use more points in 3d: by experimenting we find
1032 * that we need more exponentials in 3d than in 2d (we have more ground to
1033 * cover, after all, if we want to keep the distance between centers roughly
1034 * equal), so we choose 40 in 2d and 100 in 3d. For any other dimension, the
1035 * function does presently not know what to do so simply throws an exception
1036 * indicating exactly this.
1039 * namespace RandomMedium
1041 * template <int dim>
1042 * class KInverse : public TensorFunction<2, dim>
1046 * : TensorFunction<2, dim>()
1050 * value_list(const std::vector<Point<dim>> &points,
1051 * std::vector<Tensor<2, dim>> & values) const override
1053 * AssertDimension(points.size(), values.size());
1055 * for (unsigned int p = 0; p < points.size(); ++p)
1057 * values[p].clear();
1059 * double permeability = 0;
1060 * for (unsigned int i = 0; i < centers.size(); ++i)
1061 * permeability += std::exp(-(points[p] - centers[i]).norm_square() /
1064 * const double normalized_permeability =
1065 * std::min(std::max(permeability, 0.01), 4.);
1067 * for (unsigned int d = 0; d < dim; ++d)
1068 * values[p][d][d] = 1. / normalized_permeability;
1073 * static std::vector<Point<dim>> centers;
1075 * static std::vector<Point<dim>> get_centers()
1077 * const unsigned int N =
1078 * (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented()));
1080 * std::vector<Point<dim>> centers_list(N);
1081 * for (unsigned int i = 0; i < N; ++i)
1082 * for (unsigned int d = 0; d < dim; ++d)
1083 * centers_list[i][d] = static_cast<double>(rand()) / RAND_MAX;
1085 * return centers_list;
1091 * template <int dim>
1092 * std::vector<Point<dim>>
1093 * KInverse<dim>::centers = KInverse<dim>::get_centers();
1094 * } // namespace RandomMedium
1101 * <a name="Theinversemobilityandsaturationfunctions"></a>
1102 * <h3>The inverse mobility and saturation functions</h3>
1106 * There are two more pieces of data that we need to describe, namely the
1107 * inverse mobility function and the saturation curve. Their form is also
1108 * given in the introduction:
1111 * double mobility_inverse(const double S, const double viscosity)
1113 * return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S));
1116 * double fractional_flow(const double S, const double viscosity)
1118 * return S * S / (S * S + viscosity * (1 - S) * (1 - S));
1126 * <a name="Linearsolversandpreconditioners"></a>
1127 * <h3>Linear solvers and preconditioners</h3>
1131 * The linear solvers we use are also completely analogous to the ones used
1132 * in @ref step_20 "step-20". The following classes are therefore copied verbatim from
1133 * there. Note that the classes here are not only copied from
1134 * @ref step_20 "step-20", but also duplicate classes in deal.II. In a future version of this
1135 * example, they should be replaced by an efficient method, though. There is a
1136 * single change: if the size of a linear system is small, i.e. when the mesh
1137 * is very coarse, then it is sometimes not sufficient to set a maximum of
1138 * <code>src.size()</code> CG iterations before the solver in the
1139 * <code>vmult()</code> function converges. (This is, of course, a result of
1140 * numerical round-off, since we know that on paper, the CG method converges
1141 * in at most <code>src.size()</code> steps.) As a consequence, we set the
1142 * maximum number of iterations equal to the maximum of the size of the linear
1146 * template <class MatrixType>
1147 * class InverseMatrix : public Subscriptor
1150 * InverseMatrix(const MatrixType &m)
1154 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1156 * SolverControl solver_control(std::max<unsigned int>(src.size(), 200),
1157 * 1e-8 * src.l2_norm());
1158 * SolverCG<Vector<double>> cg(solver_control);
1162 * cg.solve(*matrix, dst, src, PreconditionIdentity());
1166 * const SmartPointer<const MatrixType> matrix;
1171 * class SchurComplement : public Subscriptor
1174 * SchurComplement(const BlockSparseMatrix<double> & A,
1175 * const InverseMatrix<SparseMatrix<double>> &Minv)
1176 * : system_matrix(&A)
1177 * , m_inverse(&Minv)
1178 * , tmp1(A.block(0, 0).m())
1179 * , tmp2(A.block(0, 0).m())
1182 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1184 * system_matrix->block(0, 1).vmult(tmp1, src);
1185 * m_inverse->vmult(tmp2, tmp1);
1186 * system_matrix->block(1, 0).vmult(dst, tmp2);
1190 * const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1191 * const SmartPointer<const InverseMatrix<SparseMatrix<double>>> m_inverse;
1193 * mutable Vector<double> tmp1, tmp2;
1198 * class ApproximateSchurComplement : public Subscriptor
1201 * ApproximateSchurComplement(const BlockSparseMatrix<double> &A)
1202 * : system_matrix(&A)
1203 * , tmp1(A.block(0, 0).m())
1204 * , tmp2(A.block(0, 0).m())
1207 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1209 * system_matrix->block(0, 1).vmult(tmp1, src);
1210 * system_matrix->block(0, 0).precondition_Jacobi(tmp2, tmp1);
1211 * system_matrix->block(1, 0).vmult(dst, tmp2);
1215 * const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1217 * mutable Vector<double> tmp1, tmp2;
1225 * <a name="codeTwoPhaseFlowProblemcodeclassimplementation"></a>
1226 * <h3><code>TwoPhaseFlowProblem</code> class implementation</h3>
1230 * Here now the implementation of the main class. Much of it is actually
1231 * copied from @ref step_20 "step-20", so we won't comment on it in much detail. You should
1232 *
try to get familiar with that program
first, then most of what is
1233 * happening here should be mostly clear.
1238 * <a name=
"TwoPhaseFlowProblemTwoPhaseFlowProblem"></a>
1239 * <h4>TwoPhaseFlowProblem::TwoPhaseFlowProblem</h4>
1243 * First
for the constructor. We use @f$RT_k \times DQ_k \times DQ_k@f$
1244 * spaces. For initializing the
DiscreteTime object, we don
't set the time
1245 * step size in the constructor because we don't have its
value yet.
1246 * The time step size is initially
set to zero, but it will be computed
1247 * before it is needed to increment time, as described in a subsection of
1248 * the introduction. The time
object internally prevents itself from being
1249 * incremented when @f$dt = 0@f$, forcing us to
set a non-zero desired size
for
1250 * @f$dt@f$ before advancing time.
1253 *
template <
int dim>
1254 * TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(
const unsigned int degree)
1263 * , n_refinement_steps(5)
1273 * <a name=
"TwoPhaseFlowProblemmake_grid_and_dofs"></a>
1274 * <h4>TwoPhaseFlowProblem::make_grid_and_dofs</h4>
1278 * This next function starts out with well-known
functions calls that create
1279 * and
refine a mesh, and then associate degrees of freedom with it. It does
1280 * all the same things as in @ref step_20
"step-20", just now
for three components instead
1284 *
template <
int dim>
1285 *
void TwoPhaseFlowProblem<dim>::make_grid_and_dofs()
1290 * dof_handler.distribute_dofs(fe);
1293 *
const std::vector<types::global_dof_index> dofs_per_component =
1295 *
const unsigned int n_u = dofs_per_component[0],
1296 * n_p = dofs_per_component[dim],
1297 * n_s = dofs_per_component[dim + 1];
1299 * std::cout <<
"Number of active cells: " <<
triangulation.n_active_cells()
1301 * <<
"Number of degrees of freedom: " << dof_handler.n_dofs()
1302 * <<
" (" << n_u <<
'+' << n_p <<
'+' << n_s <<
')' << std::endl
1305 *
const std::vector<types::global_dof_index> block_sizes = {n_u, n_p, n_s};
1309 * sparsity_pattern.copy_from(dsp);
1310 * system_matrix.reinit(sparsity_pattern);
1312 * solution.reinit(block_sizes);
1313 * old_solution.reinit(block_sizes);
1314 * system_rhs.reinit(block_sizes);
1321 * <a name=
"TwoPhaseFlowProblemassemble_system"></a>
1322 * <h4>TwoPhaseFlowProblem::assemble_system</h4>
1326 * This is the function that assembles the linear system, or at least
1327 * everything except the (1,3) block that depends on the still-unknown
1328 * velocity computed during this time step (we deal with this in
1329 * <code>assemble_rhs_S</code>). Much of it is again as in @ref step_20 "step-20", but we
1330 * have to deal with some nonlinearity this time. However, the top of the
1331 * function is pretty much as usual (note that we set matrix and right hand
1332 * side to zero at the beginning — something we didn't have to do for
1333 * stationary problems since there we use each matrix
object only once and
1334 * it is empty at the beginning anyway).
1338 * Note that in its present form, the function uses the permeability
1339 * implemented in the RandomMedium::KInverse class. Switching to the single
1340 * curved crack permeability function is as simple as just changing the
1344 * template <
int dim>
1345 *
void TwoPhaseFlowProblem<dim>::assemble_system()
1347 * system_matrix = 0;
1351 *
QGauss<dim - 1> face_quadrature_formula(degree + 2);
1354 * quadrature_formula,
1358 * face_quadrature_formula,
1363 *
const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1365 *
const unsigned int n_q_points = quadrature_formula.size();
1366 *
const unsigned int n_face_q_points = face_quadrature_formula.size();
1371 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1373 *
const PressureRightHandSide<dim> pressure_right_hand_side;
1374 *
const PressureBoundaryValues<dim> pressure_boundary_values;
1375 *
const RandomMedium::KInverse<dim> k_inverse;
1377 * std::vector<double> pressure_rhs_values(n_q_points);
1378 * std::vector<double> boundary_values(n_face_q_points);
1379 * std::vector<Tensor<2, dim>> k_inverse_values(n_q_points);
1381 * std::vector<Vector<double>> old_solution_values(n_q_points,
1388 *
for (
const auto &cell : dof_handler.active_cell_iterators())
1390 * fe_values.
reinit(cell);
1396 * Here
's the first significant difference: We have to get the values
1397 * of the saturation function of the previous time step at the
1398 * quadrature points. To this end, we can use the
1399 * FEValues::get_function_values (previously already used in @ref step_9 "step-9",
1400 * @ref step_14 "step-14" and @ref step_15 "step-15"), a function that takes a solution vector and
1401 * returns a list of function values at the quadrature points of the
1402 * present cell. In fact, it returns the complete vector-valued
1403 * solution at each quadrature point, i.e. not only the saturation but
1404 * also the velocities and pressure:
1407 * fe_values.get_function_values(old_solution, old_solution_values);
1411 * Then we also have to get the values of the pressure right hand side
1412 * and of the inverse permeability tensor at the quadrature points:
1415 * pressure_right_hand_side.value_list(fe_values.get_quadrature_points(),
1416 * pressure_rhs_values);
1417 * k_inverse.value_list(fe_values.get_quadrature_points(),
1418 * k_inverse_values);
1422 * With all this, we can now loop over all the quadrature points and
1423 * shape functions on this cell and assemble those parts of the matrix
1424 * and right hand side that we deal with in this function. The
1425 * individual terms in the contributions should be self-explanatory
1426 * given the explicit form of the bilinear form stated in the
1430 * for (unsigned int q = 0; q < n_q_points; ++q)
1431 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1433 * const double old_s = old_solution_values[q](dim + 1);
1435 * const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q);
1436 * const double div_phi_i_u = fe_values[velocities].divergence(i, q);
1437 * const double phi_i_p = fe_values[pressure].value(i, q);
1438 * const double phi_i_s = fe_values[saturation].value(i, q);
1440 * for (unsigned int j = 0; j < dofs_per_cell; ++j)
1442 * const Tensor<1, dim> phi_j_u =
1443 * fe_values[velocities].value(j, q);
1444 * const double div_phi_j_u =
1445 * fe_values[velocities].divergence(j, q);
1446 * const double phi_j_p = fe_values[pressure].value(j, q);
1447 * const double phi_j_s = fe_values[saturation].value(j, q);
1449 * local_matrix(i, j) +=
1450 * (phi_i_u * k_inverse_values[q] *
1451 * mobility_inverse(old_s, viscosity) * phi_j_u -
1452 * div_phi_i_u * phi_j_p - phi_i_p * div_phi_j_u +
1453 * phi_i_s * phi_j_s) *
1458 * (-phi_i_p * pressure_rhs_values[q]) * fe_values.JxW(q);
1464 * Next, we also have to deal with the pressure boundary values. This,
1465 * again is as in @ref step_20 "step-20":
1468 * for (const auto &face : cell->face_iterators())
1469 * if (face->at_boundary())
1471 * fe_face_values.reinit(cell, face);
1473 * pressure_boundary_values.value_list(
1474 * fe_face_values.get_quadrature_points(), boundary_values);
1476 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1477 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1479 * const Tensor<1, dim> phi_i_u =
1480 * fe_face_values[velocities].value(i, q);
1483 * -(phi_i_u * fe_face_values.normal_vector(q) *
1484 * boundary_values[q] * fe_face_values.JxW(q));
1490 * The final step in the loop over all cells is to transfer local
1491 * contributions into the global matrix and right hand side vector:
1494 * cell->get_dof_indices(local_dof_indices);
1495 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1496 * for (unsigned int j = 0; j < dofs_per_cell; ++j)
1497 * system_matrix.add(local_dof_indices[i],
1498 * local_dof_indices[j],
1499 * local_matrix(i, j));
1501 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1502 * system_rhs(local_dof_indices[i]) += local_rhs(i);
1509 * So much for assembly of matrix and right hand side. Note that we do not
1510 * have to interpolate and apply boundary values since they have all been
1511 * taken care of in the weak form already.
1519 * <a name="TwoPhaseFlowProblemassemble_rhs_S"></a>
1520 * <h4>TwoPhaseFlowProblem::assemble_rhs_S</h4>
1524 * As explained in the introduction, we can only evaluate the right hand
1525 * side of the saturation equation once the velocity has been computed. We
1526 * therefore have this separate function to this end.
1529 * template <int dim>
1530 * void TwoPhaseFlowProblem<dim>::assemble_rhs_S()
1532 * QGauss<dim> quadrature_formula(degree + 2);
1533 * QGauss<dim - 1> face_quadrature_formula(degree + 2);
1534 * FEValues<dim> fe_values(fe,
1535 * quadrature_formula,
1536 * update_values | update_gradients |
1537 * update_quadrature_points | update_JxW_values);
1538 * FEFaceValues<dim> fe_face_values(fe,
1539 * face_quadrature_formula,
1540 * update_values | update_normal_vectors |
1541 * update_quadrature_points |
1542 * update_JxW_values);
1543 * FEFaceValues<dim> fe_face_values_neighbor(fe,
1544 * face_quadrature_formula,
1547 * const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1548 * const unsigned int n_q_points = quadrature_formula.size();
1549 * const unsigned int n_face_q_points = face_quadrature_formula.size();
1551 * Vector<double> local_rhs(dofs_per_cell);
1553 * std::vector<Vector<double>> old_solution_values(n_q_points,
1554 * Vector<double>(dim + 2));
1555 * std::vector<Vector<double>> old_solution_values_face(n_face_q_points,
1556 * Vector<double>(dim +
1558 * std::vector<Vector<double>> old_solution_values_face_neighbor(
1559 * n_face_q_points, Vector<double>(dim + 2));
1560 * std::vector<Vector<double>> present_solution_values(n_q_points,
1561 * Vector<double>(dim +
1563 * std::vector<Vector<double>> present_solution_values_face(
1564 * n_face_q_points, Vector<double>(dim + 2));
1566 * std::vector<double> neighbor_saturation(n_face_q_points);
1567 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1569 * SaturationBoundaryValues<dim> saturation_boundary_values;
1571 * const FEValuesExtractors::Scalar saturation(dim + 1);
1573 * for (const auto &cell : dof_handler.active_cell_iterators())
1576 * fe_values.reinit(cell);
1578 * fe_values.get_function_values(old_solution, old_solution_values);
1579 * fe_values.get_function_values(solution, present_solution_values);
1583 * First for the cell terms. These are, following the formulas in the
1584 * introduction, @f$(S^n,\sigma)-(F(S^n) \mathbf{v}^{n+1},\nabla
1585 * \sigma)@f$, where @f$\sigma@f$ is the saturation component of the test
1589 * for (unsigned int q = 0; q < n_q_points; ++q)
1590 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1592 * const double old_s = old_solution_values[q](dim + 1);
1593 * Tensor<1, dim> present_u;
1594 * for (unsigned int d = 0; d < dim; ++d)
1595 * present_u[d] = present_solution_values[q](d);
1597 * const double phi_i_s = fe_values[saturation].value(i, q);
1598 * const Tensor<1, dim> grad_phi_i_s =
1599 * fe_values[saturation].gradient(i, q);
1602 * (time.get_next_step_size() * fractional_flow(old_s, viscosity) *
1603 * present_u * grad_phi_i_s +
1604 * old_s * phi_i_s) *
1610 * Secondly, we have to deal with the flux parts on the face
1611 * boundaries. This was a bit more involved because we first have to
1612 * determine which are the influx and outflux parts of the cell
1613 * boundary. If we have an influx boundary, we need to evaluate the
1614 * saturation on the other side of the face (or the boundary values,
1615 * if we are at the boundary of the domain).
1619 * All this is a bit tricky, but has been explained in some detail
1620 * already in @ref step_9 "step-9". Take a look there how this is supposed to work!
1623 * for (const auto face_no : cell->face_indices())
1625 * fe_face_values.reinit(cell, face_no);
1627 * fe_face_values.get_function_values(old_solution,
1628 * old_solution_values_face);
1629 * fe_face_values.get_function_values(solution,
1630 * present_solution_values_face);
1632 * if (cell->at_boundary(face_no))
1633 * saturation_boundary_values.value_list(
1634 * fe_face_values.get_quadrature_points(), neighbor_saturation);
1637 * const auto neighbor = cell->neighbor(face_no);
1638 * const unsigned int neighbor_face =
1639 * cell->neighbor_of_neighbor(face_no);
1641 * fe_face_values_neighbor.reinit(neighbor, neighbor_face);
1643 * fe_face_values_neighbor.get_function_values(
1644 * old_solution, old_solution_values_face_neighbor);
1646 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1647 * neighbor_saturation[q] =
1648 * old_solution_values_face_neighbor[q](dim + 1);
1652 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1654 * Tensor<1, dim> present_u_face;
1655 * for (unsigned int d = 0; d < dim; ++d)
1656 * present_u_face[d] = present_solution_values_face[q](d);
1658 * const double normal_flux =
1659 * present_u_face * fe_face_values.normal_vector(q);
1661 * const bool is_outflow_q_point = (normal_flux >= 0);
1663 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1665 * time.get_next_step_size() * normal_flux *
1666 * fractional_flow((is_outflow_q_point == true ?
1667 * old_solution_values_face[q](dim + 1) :
1668 * neighbor_saturation[q]),
1670 * fe_face_values[saturation].value(i, q) *
1671 * fe_face_values.JxW(q);
1675 * cell->get_dof_indices(local_dof_indices);
1676 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1677 * system_rhs(local_dof_indices[i]) += local_rhs(i);
1686 * <a name="TwoPhaseFlowProblemsolve"></a>
1687 * <h4>TwoPhaseFlowProblem::solve</h4>
1691 * After all these preparations, we finally solve the linear system for
1692 * velocity and pressure in the same way as in @ref step_20 "step-20". After that, we have
1693 * to deal with the saturation equation (see below):
1696 * template <int dim>
1697 * void TwoPhaseFlowProblem<dim>::solve()
1699 * const InverseMatrix<SparseMatrix<double>> m_inverse(
1700 * system_matrix.block(0, 0));
1701 * Vector<double> tmp(solution.block(0).size());
1702 * Vector<double> schur_rhs(solution.block(1).size());
1703 * Vector<double> tmp2(solution.block(2).size());
1708 * First the pressure, using the pressure Schur complement of the first
1713 * m_inverse.vmult(tmp, system_rhs.block(0));
1714 * system_matrix.block(1, 0).vmult(schur_rhs, tmp);
1715 * schur_rhs -= system_rhs.block(1);
1718 * SchurComplement schur_complement(system_matrix, m_inverse);
1720 * ApproximateSchurComplement approximate_schur_complement(system_matrix);
1722 * InverseMatrix<ApproximateSchurComplement> preconditioner(
1723 * approximate_schur_complement);
1726 * SolverControl solver_control(solution.block(1).size(),
1727 * 1e-12 * schur_rhs.l2_norm());
1728 * SolverCG<Vector<double>> cg(solver_control);
1730 * cg.solve(schur_complement, solution.block(1), schur_rhs, preconditioner);
1732 * std::cout << " " << solver_control.last_step()
1733 * << " CG Schur complement iterations for pressure." << std::endl;
1742 * system_matrix.block(0, 1).vmult(tmp, solution.block(1));
1744 * tmp += system_rhs.block(0);
1746 * m_inverse.vmult(solution.block(0), tmp);
1751 * Finally, we have to take care of the saturation equation. The first
1752 * business we have here is to determine the time step using the formula
1753 * in the introduction. Knowing the shape of our domain and that we
1754 * created the mesh by regular subdivision of cells, we can compute the
1755 * diameter of each of our cells quite easily (in fact we use the linear
1756 * extensions in coordinate directions of the cells, not the
1757 * diameter). Note that we will learn a more general way to do this in
1758 * @ref step_24 "step-24", where we use the GridTools::minimal_cell_diameter function.
1762 * The maximal velocity we compute using a helper function to compute the
1763 * maximal velocity defined below, and with all this we can evaluate our
1764 * new time step length. We use the method
1765 * DiscreteTime::set_desired_next_time_step() to suggest the new
1766 * calculated value of the time step to the DiscreteTime object. In most
1767 * cases, the time object uses the exact provided value to increment time.
1768 * It some case, the step size may be modified further by the time object.
1769 * For example, if the calculated time increment overshoots the end time,
1770 * it is truncated accordingly.
1773 * time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) /
1774 * get_maximal_velocity());
1778 * The next step is to assemble the right hand side, and then to pass
1779 * everything on for solution. At the end, we project back saturations
1780 * onto the physically reasonable range:
1785 * SolverControl solver_control(system_matrix.block(2, 2).m(),
1786 * 1e-8 * system_rhs.block(2).l2_norm());
1787 * SolverCG<Vector<double>> cg(solver_control);
1788 * cg.solve(system_matrix.block(2, 2),
1789 * solution.block(2),
1790 * system_rhs.block(2),
1791 * PreconditionIdentity());
1793 * project_back_saturation();
1795 * std::cout << " " << solver_control.last_step()
1796 * << " CG iterations for saturation." << std::endl;
1800 * old_solution = solution;
1807 * <a name="TwoPhaseFlowProblemoutput_results"></a>
1808 * <h4>TwoPhaseFlowProblem::output_results</h4>
1812 * There is nothing surprising here. Since the program will do a lot of time
1813 * steps, we create an output file only every fifth time step and skip all
1814 * other time steps at the top of the file already.
1818 * When creating file names for output close to the bottom of the function,
1819 * we convert the number of the time step to a string representation that
1820 * is padded by leading zeros to four digits. We do this because this way
1821 * all output file names have the same length, and consequently sort well
1822 * when creating a directory listing.
1825 * template <int dim>
1826 * void TwoPhaseFlowProblem<dim>::output_results() const
1828 * if (time.get_step_number() % 5 != 0)
1831 * std::vector<std::string> solution_names;
1835 * solution_names = {"u", "v", "p", "S"};
1839 * solution_names = {"u", "v", "w", "p", "S"};
1843 * Assert(false, ExcNotImplemented());
1846 * DataOut<dim> data_out;
1848 * data_out.attach_dof_handler(dof_handler);
1849 * data_out.add_data_vector(solution, solution_names);
1851 * data_out.build_patches(degree + 1);
1853 * std::ofstream output("solution-" +
1854 * Utilities::int_to_string(time.get_step_number(), 4) +
1856 * data_out.write_vtk(output);
1864 * <a name="TwoPhaseFlowProblemproject_back_saturation"></a>
1865 * <h4>TwoPhaseFlowProblem::project_back_saturation</h4>
1869 * In this function, we simply run over all saturation degrees of freedom
1870 * and make sure that if they should have left the physically reasonable
1871 * range, that they be reset to the interval @f$[0,1]@f$. To do this, we only
1872 * have to loop over all saturation components of the solution vector; these
1873 * are stored in the block 2 (block 0 are the velocities, block 1 are the
1878 * It may be instructive to note that this function almost never triggers
1879 * when the time step is chosen as mentioned in the introduction. However,
1880 * if we choose the timestep only slightly larger, we get plenty of values
1881 * outside the proper range. Strictly speaking, the function is therefore
1882 * unnecessary if we choose the time step small enough. In a sense, the
1883 * function is therefore only a safety device to avoid situations where our
1884 * entire solution becomes unphysical because individual degrees of freedom
1885 * have become unphysical a few time steps earlier.
1888 * template <int dim>
1889 * void TwoPhaseFlowProblem<dim>::project_back_saturation()
1891 * for (unsigned int i = 0; i < solution.block(2).size(); ++i)
1892 * if (solution.block(2)(i) < 0)
1893 * solution.block(2)(i) = 0;
1894 * else if (solution.block(2)(i) > 1)
1895 * solution.block(2)(i) = 1;
1902 * <a name="TwoPhaseFlowProblemget_maximal_velocity"></a>
1903 * <h4>TwoPhaseFlowProblem::get_maximal_velocity</h4>
1907 * The following function is used in determining the maximal allowable time
1908 * step. What it does is to loop over all quadrature points in the domain
1909 * and find what the maximal magnitude of the velocity is.
1912 * template <int dim>
1913 * double TwoPhaseFlowProblem<dim>::get_maximal_velocity() const
1915 * QGauss<dim> quadrature_formula(degree + 2);
1916 * const unsigned int n_q_points = quadrature_formula.size();
1918 * FEValues<dim> fe_values(fe, quadrature_formula, update_values);
1919 * std::vector<Vector<double>> solution_values(n_q_points,
1920 * Vector<double>(dim + 2));
1921 * double max_velocity = 0;
1923 * for (const auto &cell : dof_handler.active_cell_iterators())
1925 * fe_values.reinit(cell);
1926 * fe_values.get_function_values(solution, solution_values);
1928 * for (unsigned int q = 0; q < n_q_points; ++q)
1930 * Tensor<1, dim> velocity;
1931 * for (unsigned int i = 0; i < dim; ++i)
1932 * velocity[i] = solution_values[q](i);
1934 * max_velocity = std::max(max_velocity, velocity.norm());
1938 * return max_velocity;
1945 * <a name="TwoPhaseFlowProblemrun"></a>
1946 * <h4>TwoPhaseFlowProblem::run</h4>
1950 * This is the final function of our main class. Its brevity speaks for
1951 * itself. There are only two points worth noting: First, the function
1952 * projects the initial values onto the finite element space at the
1953 * beginning; the VectorTools::project function doing this requires an
1954 * argument indicating the hanging node constraints. We have none in this
1955 * program (we compute on a uniformly refined mesh), but the function
1956 * requires the argument anyway, of course. So we have to create a
1957 * constraint object. In its original state, constraint objects are
1958 * unsorted, and have to be sorted (using the AffineConstraints::close
1959 * function) before they can be used. This is what we do here, and which is
1966 * The
second point worth mentioning is that we only compute the length of
1967 * the present time step in the middle of solving the linear system
1968 * corresponding to each time step. We can therefore output the present
1969 * time of a time step only at the
end of the time step.
1971 *
inside the
loop. Since we are reporting the time and dt after we
1972 * increment it, we have to
call the method
1974 *
DiscreteTime::get_next_step_size(). After many steps, when the simulation
1975 * reaches the end time, the last dt is chosen by the
DiscreteTime class in
1976 * such a way that the last step finishes exactly at the end time.
1979 * template <
int dim>
1980 *
void TwoPhaseFlowProblem<dim>::run()
1982 * make_grid_and_dofs();
1986 * constraints.
close();
1991 * InitialValues<dim>(),
1997 * std::cout <<
"Timestep " << time.get_step_number() + 1 << std::endl;
1999 * assemble_system();
2005 * time.advance_time();
2006 * std::cout <<
" Now at t=" << time.get_current_time()
2007 * <<
", dt=" << time.get_previous_step_size() <<
'.'
2011 *
while (time.is_at_end() ==
false);
2019 * <a name=
"Thecodemaincodefunction"></a>
2020 * <h3>The <code>main</code> function</h3>
2024 * That
's it. In the main function, we pass the degree of the finite element
2025 * space to the constructor of the TwoPhaseFlowProblem object. Here, we use
2026 * zero-th degree elements, i.e. @f$RT_0\times DQ_0 \times DQ_0@f$. The rest is as
2027 * in all the other programs.
2034 * using namespace Step21;
2036 * TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2037 * two_phase_flow_problem.run();
2039 * catch (std::exception &exc)
2041 * std::cerr << std::endl
2043 * << "----------------------------------------------------"
2045 * std::cerr << "Exception on processing: " << std::endl
2046 * << exc.what() << std::endl
2047 * << "Aborting!" << std::endl
2048 * << "----------------------------------------------------"
2055 * std::cerr << std::endl
2057 * << "----------------------------------------------------"
2059 * std::cerr << "Unknown exception!" << std::endl
2060 * << "Aborting!" << std::endl
2061 * << "----------------------------------------------------"
2069<a name="Results"></a><h1>Results</h1>
2072The code as presented here does not actually compute the results
2073found on the web page. The reason is, that even on a decent
2074computer it runs more than a day. If you want to reproduce these
2075results, modify the end time of the DiscreteTime object to `250` within the
2076constructor of TwoPhaseFlowProblem.
2078If we run the program, we get the following kind of output:
2080Number of active cells: 1024
2081Number of degrees of freedom: 4160 (2112+1024+1024)
2084 22 CG Schur complement iterations for pressure.
2085 1 CG iterations for saturation.
2086 Now at t=0.0326742, dt=0.0326742.
2089 17 CG Schur complement iterations for pressure.
2090 1 CG iterations for saturation.
2091 Now at t=0.0653816, dt=0.0327074.
2094 17 CG Schur complement iterations for pressure.
2095 1 CG iterations for saturation.
2096 Now at t=0.0980651, dt=0.0326836.
2100As we can see, the time step is pretty much constant right from the start,
2101which indicates that the velocities in the domain are not strongly dependent
2102on changes in saturation, although they certainly are through the factor
2103@f$\lambda(S)@f$ in the pressure equation.
2105Our second observation is that the number of CG iterations needed to solve the
2106pressure Schur complement equation drops from 22 to 17 between the first and
2107the second time step (in fact, it remains around 17 for the rest of the
2108computations). The reason is actually simple: Before we solve for the pressure
2109during a time step, we don't reset the <code>solution</code> variable to
2110zero. The pressure (and the other variables) therefore have the previous time
2111step
's values at the time we get into the CG solver. Since the velocities and
2112pressures don't change very much as computations progress, the previous time
2113step
's pressure is actually a good initial guess for this time step's
2114pressure. Consequently, the number of iterations we need once we have computed
2115the pressure once is significantly reduced.
2117The
final observation concerns the number of iterations needed to solve
for
2118the saturation, i.e. one. This shouldn
't surprise us too much: the matrix we
2119have to solve with is the mass matrix. However, this is the mass matrix for
2120the @f$DGQ_0@f$ element of piecewise constants where no element couples with the
2121degrees of freedom on neighboring cells. The matrix is therefore a diagonal
2122one, and it is clear that we should be able to invert this matrix in a single
2126With all this, here are a few movies that show how the saturation progresses
2127over time. First, this is for the single crack model, as implemented in the
2128<code>SingleCurvingCrack::KInverse</code> class:
2130<img src="https://www.dealii.org/images/steps/developer/step-21.centerline.gif" alt="">
2132As can be seen, the water rich fluid snakes its way mostly along the
2133high-permeability zone in the middle of the domain, whereas the rest of the
2134domain is mostly impermeable. This and the next movie are generated using
2135<code>n_refinement_steps=7</code>, leading to a @f$128\times 128@f$ mesh with some
213616,000 cells and about 66,000 unknowns in total.
2139The second movie shows the saturation for the random medium model of class
2140<code>RandomMedium::KInverse</code>, where we have randomly distributed
2141centers of high permeability and fluid hops from one of these zones to
2144<img src="https://www.dealii.org/images/steps/developer/step-21.random2d.gif" alt="">
2147Finally, here is the same situation in three space dimensions, on a mesh with
2148<code>n_refinement_steps=5</code>, which produces a mesh of some 32,000 cells
2149and 167,000 degrees of freedom:
2151<img src="https://www.dealii.org/images/steps/developer/step-21.random3d.gif" alt="">
2153To repeat these computations, all you have to do is to change the line
2155 TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2157in the main function to
2159 TwoPhaseFlowProblem<3> two_phase_flow_problem(0);
2161The visualization uses a cloud technique, where the saturation is indicated by
2162colored but transparent clouds for each cell. This way, one can also see
2163somewhat what happens deep inside the domain. A different way of visualizing
2164would have been to show isosurfaces of the saturation evolving over
2165time. There are techniques to plot isosurfaces transparently, so that one can
2166see several of them at the same time like the layers of an onion.
2168So why don't we show such isosurfaces? The problem lies in the way isosurfaces
2169are computed: they require that the field to be visualized is continuous, so
2170that the isosurfaces can be generated by following contours at least across a
2171single cell. However, our saturation field is piecewise
constant and
2172discontinuous. If we wanted to plot an isosurface
for a saturation @f$S=0.5@f$,
2173chances would be that there is no single
point in the domain where that
2174saturation is actually attained. If we had to define isosurfaces in that
2175context at all, we would have to take the interfaces between cells, where one
2176of the two adjacent cells has a saturation greater than and the other cell a
2177saturation less than 0.5. However, it appears that most visualization programs
2178are not equipped to
do this kind of transformation.
2181<a name=
"extensions"></a>
2182<a name=
"Possibilitiesforextensions"></a><h3>Possibilities
for extensions</h3>
2185There are a number of areas where
this program can be improved. Three of them
2186are listed below. All of them are, in fact, addressed in a tutorial program
2187that forms the continuation of the current one: @ref step_43
"step-43".
2190<a name=
"Solvers"></a><h4>Solvers</h4>
2193At present, the program is not particularly fast: the 2
d random medium
2194computation took about a day
for the 1,000 or so time steps. The corresponding
21953
d computation took almost two days
for 800 time steps. The reason why it
2196isn
't faster than this is twofold. First, we rebuild the entire matrix in
2197every time step, although some parts such as the @f$B@f$, @f$B^T@f$, and @f$M^S@f$ blocks
2200Second, we could do a lot better with the solver and
2201preconditioners. Presently, we solve the Schur complement @f$B^TM^u(S)^{-1}B@f$
2202with a CG method, using @f$[B^T (\textrm{diag}(M^u(S)))^{-1} B]^{-1}@f$ as a
2203preconditioner. Applying this preconditioner is expensive, since it involves
2204solving a linear system each time. This may have been appropriate for @ref
2205step_20 "step-20", where we have to solve the entire problem only
2206once. However, here we have to solve it hundreds of times, and in such cases
2207it is worth considering a preconditioner that is more expensive to set up the
2208first time, but cheaper to apply later on.
2210One possibility would be to realize that the matrix we use as preconditioner,
2211@f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ is still sparse, and symmetric on top of
2212that. If one looks at the flow field evolve over time, we also see that while
2213@f$S@f$ changes significantly over time, the pressure hardly does and consequently
2214@f$B^T (\textrm{diag}(M^u(S)))^{-1} B \approx B^T (\textrm{diag}(M^u(S^0)))^{-1}
2215B@f$. In other words, the matrix for the first time step should be a good
2216preconditioner also for all later time steps. With a bit of
2217back-and-forthing, it isn't hard to actually get a representation of it as a
2219a sparse incomplete Cholesky decomposition. To form this decomposition is
2220expensive, but we have to do it only once in the
first time step, and can then
2221use it as a cheap preconditioner in the future. We could do better even by
2223a complete decomposition of the
matrix, which should yield an even better
2226Finally, why use the approximation @f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ to
2227precondition @f$B^T M^u(S)^{-1} B@f$? The latter
matrix, after all, is the mixed
2228form of the Laplace
operator on the pressure space,
for which we use linear
2229elements. We could therefore build a separate
matrix @f$A^p@f$ on the side that
2230directly corresponds to the non-mixed formulation of the Laplacian,
for
2231example
using the bilinear form @f$(\mathbf{
K}\lambda(S^n) \nabla
2232\varphi_i,\nabla\varphi_j)@f$. We could then form an incomplete or complete
2233decomposition of
this non-mixed matrix and use it as a preconditioner of the
2236Using such techniques, it can reasonably be expected that the solution process
2237will be faster by at least an order of magnitude.
2240<a name=
"Timestepping"></a><h4>Time stepping</h4>
2243In the introduction we have identified the time step restriction
2245 \triangle t_{n+1} \le \frac h{|\mathbf{u}^{n+1}(\mathbf{x})|}
2247that has to hold globally, i.e.
for all @f$\mathbf x@f$. After discretization, we
2248satisfy it by choosing
2250 \triangle t_{n+1} = \frac {\min_K h_K}{\max_{\mathbf{x}}|\mathbf{u}^{n+1}(\mathbf{x})|}.
2253This restriction on the time step is somewhat annoying: the finer we make the
2254mesh the smaller the time step; in other words, we get punished twice: each
2255time step is more expensive to solve and we have to
do more time steps.
2257This is particularly annoying since the majority of the additional work is
2258spent solving the implicit part of the equations, i.e. the pressure-velocity
2259system, whereas it is the hyperbolic transport equation
for the saturation
2260that imposes the time step restriction.
2262To avoid
this bottleneck, people have invented a number of approaches. For
2263example, they may only re-compute the pressure-velocity field every few time
2264steps (or,
if you want, use different time step sizes
for the
2265pressure/velocity and saturation equations). This keeps the time step
2266restriction on the cheap
explicit part
while it makes the solution of the
2267implicit part less frequent. Experiments in
this direction are
2268certainly worthwhile; one starting
point for such an approach is the paper by
2269Zhangxin Chen, Guanren Huan and Baoyan Li: <i>An improved IMPES method
for
2270two-phase flow in porous media</i>, Transport in Porous Media, 54 (2004),
2271pp. 361—376. There are certainly many other papers on
this topic as well, but
2272this one happened to land on our desk a
while back.
2276<a name=
"Adaptivity"></a><h4>Adaptivity</h4>
2279Adaptivity would also clearly help. Looking at the movies, one clearly sees
2280that most of the action is confined to a relatively small part of the domain
2281(
this particularly obvious
for the saturation, but also holds
for the
2282velocities and pressures). Adaptivity can therefore be expected to keep the
2283necessary number of degrees of freedom low, or alternatively increase the
2286On the other hand, adaptivity
for time dependent problems is not a trivial
2287thing: we would have to change the mesh every few time steps, and we would
2288have to transport our present solution to the next mesh every time we change
2290insurmountable obstacles, but they
do require some additional coding and more
2291than we felt comfortable was worth packing into
this tutorial program.
2294<a name=
"PlainProg"></a>
2295<h1> The plain program</h1>
2296@include
"step-21.cc"
double get_previous_step_size() const
virtual RangeNumberType value(const Point< dim > &p, const unsigned int component=0) const
virtual void vector_value(const Point< dim > &p, Vector< RangeNumberType > &values) const
virtual RangeNumberType value(const Point< dim > &p, const unsigned int component=0) const override
virtual void vector_value(const Point< dim > &p, Vector< RangeNumberType > &return_value) const override
virtual void value_list(const std::vector< Point< dim > > &points, std::vector< value_type > &values) const
__global__ void set(Number *val, const Number s, const size_type N)
#define AssertDimension(dim1, dim2)
void loop(ITERATOR begin, std_cxx20::type_identity_t< ITERATOR > end, DOFINFO &dinfo, INFOBOX &info, const std::function< void(DOFINFO &, typename INFOBOX::CellInfo &)> &cell_worker, const std::function< void(DOFINFO &, typename INFOBOX::CellInfo &)> &boundary_worker, const std::function< void(DOFINFO &, DOFINFO &, typename INFOBOX::CellInfo &, typename INFOBOX::CellInfo &)> &face_worker, ASSEMBLER &assembler, const LoopControl &lctrl=LoopControl())
void make_sparsity_pattern(const DoFHandler< dim, spacedim > &dof_handler, SparsityPatternBase &sparsity_pattern, const AffineConstraints< number > &constraints=AffineConstraints< number >(), const bool keep_constrained_dofs=true, const types::subdomain_id subdomain_id=numbers::invalid_subdomain_id)
@ update_values
Shape function values.
@ update_normal_vectors
Normal vectors.
@ update_JxW_values
Transformed quadrature weights.
@ update_gradients
Shape function gradients.
@ update_quadrature_points
Transformed quadrature points.
CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt K
void component_wise(DoFHandler< dim, spacedim > &dof_handler, const std::vector< unsigned int > &target_component=std::vector< unsigned int >())
void random(DoFHandler< dim, spacedim > &dof_handler)
void hyper_cube(Triangulation< dim, spacedim > &tria, const double left=0., const double right=1., const bool colorize=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.
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
void call(const std::function< RT()> &function, internal::return_value< RT > &ret_val)
VectorType::value_type * end(VectorType &V)
int(&) functions(const void *v1, const void *v2)
void reinit(MatrixBlock< MatrixType > &v, const BlockSparsityPattern &p)
::VectorizedArray< Number, width > exp(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > sin(const ::VectorizedArray< Number, width > &)
const ::parallel::distributed::Triangulation< dim, spacedim > * triangulation