810 *
const unsigned int = 0)
const override
821 * <a name=
"step_21-Pressureboundaryvalues"></a>
822 * <h4>Pressure boundary
values</h4>
826 * The next are pressure boundary
values. As mentioned in the introduction,
827 * we choose a linear pressure field:
831 *
class PressureBoundaryValues :
public Function<dim>
834 * PressureBoundaryValues()
839 *
const unsigned int = 0) const override
850 * <a name=
"step_21-Saturationboundaryvalues"></a>
851 * <h4>Saturation boundary
values</h4>
855 * Then we also need boundary
values on the inflow portions of the
856 * boundary. The question whether something is an inflow part is decided
857 * when assembling the right hand side, we only have to provide a functional
858 * description of the boundary
values. This is as explained in the
863 *
class SaturationBoundaryValues :
public Function<dim>
866 * SaturationBoundaryValues()
871 *
const unsigned int = 0) const override
885 * <a name=
"step_21-Initialdata"></a>
886 * <h4>Initial data</h4>
890 * Finally, we need
initial data. In reality, we only need
initial data
for
891 * the saturation, but we are lazy, so we will later, before the
first time
892 * step, simply
interpolate the entire solution
for the previous time step
893 * from a function that contains all vector components.
897 * We therefore simply create a function that returns zero in all
898 * components. We
do that by simply forward every function to the
900 *
this program where we presently use the <code>InitialValues</code>
class?
901 * Because
this way it is simpler to later go back and choose a different
906 *
class InitialValues :
public Function<dim>
914 *
const unsigned int component = 0) const override
931 * <a name=
"step_21-Theinversepermeabilitytensor"></a>
932 * <h3>The inverse permeability tensor</h3>
936 * As announced in the introduction, we implement two different permeability
937 * tensor fields. Each of them we put into a
namespace of its own, so that
938 * it will be easy later to replace use of one by the other in the code.
943 * <a name=
"step_21-Singlecurvingcrackpermeability"></a>
944 * <h4>Single curving crack permeability</h4>
948 * The
first function
for the permeability was the one that models a single
949 * curving crack. It was already used at the
end of @ref step_20
"step-20", and its
950 * functional form is given in the introduction of the present tutorial
951 * program. As in some previous programs, we have to declare a (seemingly
952 * unnecessary)
default constructor of the KInverse
class to avoid warnings
953 * from some compilers:
956 *
namespace SingleCurvingCrack
972 *
for (
unsigned int p = 0; p < points.size(); ++p)
976 *
const double distance_to_flowline =
977 * std::fabs(points[p][1] - 0.5 - 0.1 *
std::sin(10 * points[p][0]));
979 *
const double permeability =
984 *
for (
unsigned int d = 0;
d < dim; ++
d)
985 * values[p][d][d] = 1. / permeability;
995 * <a name=
"step_21-Randommediumpermeability"></a>
996 * <h4>Random medium permeability</h4>
1000 * This function does as announced in the introduction, i.e. it creates an
1001 * overlay of exponentials at
random places. There is one thing worth
1002 * considering
for this class. The issue centers around the problem that the
1003 *
class creates the centers of the exponentials using a
random function. If
1004 * we therefore created the centers each time we create an
object of the
1005 * present type, we would get a different list of centers each time. That
's
1006 * not what we expect from classes of this type: they should reliably
1007 * represent the same function.
1011 * The solution to this problem is to make the list of centers a static
1012 * member variable of this class, i.e. there exists exactly one such
1013 * variable for the entire program, rather than for each object of this
1014 * type. That's exactly what we are going to
do.
1018 * The next problem, however, is that we need a way to initialize
this
1019 * variable. Since
this variable is initialized at the beginning of the
1020 * program, we can
't use a regular member function for that since there may
1021 * not be an object of this type around at the time. The C++ standard
1022 * therefore says that only non-member and static member functions can be
1023 * used to initialize a static variable. We use the latter possibility by
1024 * defining a function <code>get_centers</code> that computes the list of
1025 * center points when called.
1029 * Note that this class works just fine in both 2d and 3d, with the only
1030 * difference being that we use more points in 3d: by experimenting we find
1031 * that we need more exponentials in 3d than in 2d (we have more ground to
1032 * cover, after all, if we want to keep the distance between centers roughly
1033 * equal), so we choose 40 in 2d and 100 in 3d. For any other dimension, the
1034 * function does presently not know what to do so simply throws an exception
1035 * indicating exactly this.
1038 * namespace RandomMedium
1040 * template <int dim>
1041 * class KInverse : public TensorFunction<2, dim>
1045 * : TensorFunction<2, dim>()
1049 * value_list(const std::vector<Point<dim>> &points,
1050 * std::vector<Tensor<2, dim>> &values) const override
1052 * AssertDimension(points.size(), values.size());
1054 * for (unsigned int p = 0; p < points.size(); ++p)
1056 * values[p].clear();
1058 * double permeability = 0;
1059 * for (unsigned int i = 0; i < centers.size(); ++i)
1060 * permeability += std::exp(-(points[p] - centers[i]).norm_square() /
1063 * const double normalized_permeability =
1064 * std::min(std::max(permeability, 0.01), 4.);
1066 * for (unsigned int d = 0; d < dim; ++d)
1067 * values[p][d][d] = 1. / normalized_permeability;
1072 * static std::vector<Point<dim>> centers;
1074 * static std::vector<Point<dim>> get_centers()
1076 * const unsigned int N =
1077 * (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented()));
1079 * std::vector<Point<dim>> centers_list(N);
1080 * for (unsigned int i = 0; i < N; ++i)
1081 * for (unsigned int d = 0; d < dim; ++d)
1082 * centers_list[i][d] = static_cast<double>(rand()) / RAND_MAX;
1084 * return centers_list;
1090 * template <int dim>
1091 * std::vector<Point<dim>> KInverse<dim>::centers =
1092 * KInverse<dim>::get_centers();
1093 * } // namespace RandomMedium
1100 * <a name="step_21-Theinversemobilityandsaturationfunctions"></a>
1101 * <h3>The inverse mobility and saturation functions</h3>
1105 * There are two more pieces of data that we need to describe, namely the
1106 * inverse mobility function and the saturation curve. Their form is also
1107 * given in the introduction:
1110 * double mobility_inverse(const double S, const double viscosity)
1112 * return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S));
1115 * double fractional_flow(const double S, const double viscosity)
1117 * return S * S / (S * S + viscosity * (1 - S) * (1 - S));
1125 * <a name="step_21-Linearsolversandpreconditioners"></a>
1126 * <h3>Linear solvers and preconditioners</h3>
1130 * The linear solvers we use are also completely analogous to the ones used
1131 * in @ref step_20 "step-20". The following classes are therefore copied verbatim from
1132 * there. Note that the classes here are not only copied from
1133 * @ref step_20 "step-20", but also duplicate classes in deal.II. In a future version of this
1134 * example, they should be replaced by an efficient method, though. There is a
1135 * single change: if the size of a linear system is small, i.e. when the mesh
1136 * is very coarse, then it is sometimes not sufficient to set a maximum of
1137 * <code>src.size()</code> CG iterations before the solver in the
1138 * <code>vmult()</code> function converges. (This is, of course, a result of
1139 * numerical round-off, since we know that on paper, the CG method converges
1140 * in at most <code>src.size()</code> steps.) As a consequence, we set the
1141 * maximum number of iterations equal to the maximum of the size of the linear
1145 * template <class MatrixType>
1146 * class InverseMatrix : public Subscriptor
1149 * InverseMatrix(const MatrixType &m)
1153 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1155 * SolverControl solver_control(std::max<unsigned int>(src.size(), 200),
1156 * 1e-8 * src.l2_norm());
1157 * SolverCG<Vector<double>> cg(solver_control);
1161 * cg.solve(*matrix, dst, src, PreconditionIdentity());
1165 * const SmartPointer<const MatrixType> matrix;
1170 * class SchurComplement : public Subscriptor
1173 * SchurComplement(const BlockSparseMatrix<double> &A,
1174 * const InverseMatrix<SparseMatrix<double>> &Minv)
1175 * : system_matrix(&A)
1176 * , m_inverse(&Minv)
1177 * , tmp1(A.block(0, 0).m())
1178 * , tmp2(A.block(0, 0).m())
1181 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1183 * system_matrix->block(0, 1).vmult(tmp1, src);
1184 * m_inverse->vmult(tmp2, tmp1);
1185 * system_matrix->block(1, 0).vmult(dst, tmp2);
1189 * const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1190 * const SmartPointer<const InverseMatrix<SparseMatrix<double>>> m_inverse;
1192 * mutable Vector<double> tmp1, tmp2;
1197 * class ApproximateSchurComplement : public Subscriptor
1200 * ApproximateSchurComplement(const BlockSparseMatrix<double> &A)
1201 * : system_matrix(&A)
1202 * , tmp1(A.block(0, 0).m())
1203 * , tmp2(A.block(0, 0).m())
1206 * void vmult(Vector<double> &dst, const Vector<double> &src) const
1208 * system_matrix->block(0, 1).vmult(tmp1, src);
1209 * system_matrix->block(0, 0).precondition_Jacobi(tmp2, tmp1);
1210 * system_matrix->block(1, 0).vmult(dst, tmp2);
1214 * const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1216 * mutable Vector<double> tmp1, tmp2;
1224 * <a name="step_21-codeTwoPhaseFlowProblemcodeclassimplementation"></a>
1225 * <h3><code>TwoPhaseFlowProblem</code> class implementation</h3>
1229 * Here now the implementation of the main class. Much of it is actually
1230 * copied from @ref step_20 "step-20", so we won't comment on it in much detail. You should
1231 *
try to get familiar with that program
first, then most of what is
1232 * happening here should be mostly clear.
1237 * <a name=
"step_21-TwoPhaseFlowProblemTwoPhaseFlowProblem"></a>
1238 * <h4>TwoPhaseFlowProblem::TwoPhaseFlowProblem</h4>
1242 * First
for the constructor. We use @f$RT_k \times DQ_k \times DQ_k@f$
1243 * spaces. For initializing the
DiscreteTime object, we don
't set the time
1244 * step size in the constructor because we don't have its
value yet.
1245 * The time step size is initially set to zero, but it will be computed
1246 * before it is needed to increment time, as described in a subsection of
1247 * the introduction. The time
object internally prevents itself from being
1248 * incremented when @f$dt = 0@f$, forcing us to set a non-zero desired size
for
1249 * @f$dt@f$ before advancing time.
1252 *
template <
int dim>
1253 * TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(
const unsigned int degree)
1259 * , n_refinement_steps(5)
1269 * <a name=
"step_21-TwoPhaseFlowProblemmake_grid_and_dofs"></a>
1270 * <h4>TwoPhaseFlowProblem::make_grid_and_dofs</h4>
1274 * This next function starts out with well-known
functions calls that create
1275 * and
refine a mesh, and then associate degrees of freedom with it. It does
1276 * all the same things as in @ref step_20
"step-20", just now
for three components instead
1280 *
template <
int dim>
1281 *
void TwoPhaseFlowProblem<dim>::make_grid_and_dofs()
1286 * dof_handler.distribute_dofs(fe);
1289 *
const std::vector<types::global_dof_index> dofs_per_component =
1291 *
const unsigned int n_u = dofs_per_component[0],
1292 * n_p = dofs_per_component[dim],
1293 * n_s = dofs_per_component[dim + 1];
1295 * std::cout <<
"Number of active cells: " <<
triangulation.n_active_cells()
1297 * <<
"Number of degrees of freedom: " << dof_handler.n_dofs()
1298 * <<
" (" << n_u <<
'+' << n_p <<
'+' << n_s <<
')' << std::endl
1301 *
const std::vector<types::global_dof_index> block_sizes = {n_u, n_p, n_s};
1305 * sparsity_pattern.copy_from(dsp);
1306 * system_matrix.reinit(sparsity_pattern);
1308 * solution.reinit(block_sizes);
1309 * old_solution.reinit(block_sizes);
1310 * system_rhs.reinit(block_sizes);
1317 * <a name=
"step_21-TwoPhaseFlowProblemassemble_system"></a>
1318 * <h4>TwoPhaseFlowProblem::assemble_system</h4>
1322 * This is the function that assembles the linear system, or at least
1323 * everything except the (1,3) block that depends on the still-unknown
1324 * velocity computed during this time step (we deal with this in
1325 * <code>assemble_rhs_S</code>). Much of it is again as in @ref step_20 "step-20", but we
1326 * have to deal with some nonlinearity this time. However, the top of the
1327 * function is pretty much as usual (note that we set matrix and right hand
1328 * side to zero at the beginning — something we didn't have to do for
1329 * stationary problems since there we use each matrix
object only once and
1330 * it is empty at the beginning anyway).
1334 * Note that in its present form, the function uses the permeability
1335 * implemented in the RandomMedium::KInverse class. Switching to the single
1336 * curved crack permeability function is as simple as just changing the
1340 * template <
int dim>
1341 *
void TwoPhaseFlowProblem<dim>::assemble_system()
1343 * system_matrix = 0;
1346 *
const QGauss<dim> quadrature_formula(degree + 2);
1347 *
const QGauss<dim - 1> face_quadrature_formula(degree + 2);
1350 * quadrature_formula,
1354 * face_quadrature_formula,
1359 *
const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1361 *
const unsigned int n_q_points = quadrature_formula.size();
1362 *
const unsigned int n_face_q_points = face_quadrature_formula.size();
1367 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1369 *
const PressureRightHandSide<dim> pressure_right_hand_side;
1370 *
const PressureBoundaryValues<dim> pressure_boundary_values;
1371 *
const RandomMedium::KInverse<dim> k_inverse;
1373 * std::vector<double> pressure_rhs_values(n_q_points);
1374 * std::vector<double> boundary_values(n_face_q_points);
1375 * std::vector<Tensor<2, dim>> k_inverse_values(n_q_points);
1377 * std::vector<Vector<double>> old_solution_values(n_q_points,
1384 *
for (
const auto &cell : dof_handler.active_cell_iterators())
1386 * fe_values.
reinit(cell);
1392 * Here
's the first significant difference: We have to get the values
1393 * of the saturation function of the previous time step at the
1394 * quadrature points. To this end, we can use the
1395 * FEValues::get_function_values (previously already used in @ref step_9 "step-9",
1396 * @ref step_14 "step-14" and @ref step_15 "step-15"), a function that takes a solution vector and
1397 * returns a list of function values at the quadrature points of the
1398 * present cell. In fact, it returns the complete vector-valued
1399 * solution at each quadrature point, i.e. not only the saturation but
1400 * also the velocities and pressure:
1403 * fe_values.get_function_values(old_solution, old_solution_values);
1407 * Then we also have to get the values of the pressure right hand side
1408 * and of the inverse permeability tensor at the quadrature points:
1411 * pressure_right_hand_side.value_list(fe_values.get_quadrature_points(),
1412 * pressure_rhs_values);
1413 * k_inverse.value_list(fe_values.get_quadrature_points(),
1414 * k_inverse_values);
1418 * With all this, we can now loop over all the quadrature points and
1419 * shape functions on this cell and assemble those parts of the matrix
1420 * and right hand side that we deal with in this function. The
1421 * individual terms in the contributions should be self-explanatory
1422 * given the explicit form of the bilinear form stated in the
1426 * for (unsigned int q = 0; q < n_q_points; ++q)
1427 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1429 * const double old_s = old_solution_values[q](dim + 1);
1431 * const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q);
1432 * const double div_phi_i_u = fe_values[velocities].divergence(i, q);
1433 * const double phi_i_p = fe_values[pressure].value(i, q);
1434 * const double phi_i_s = fe_values[saturation].value(i, q);
1436 * for (unsigned int j = 0; j < dofs_per_cell; ++j)
1438 * const Tensor<1, dim> phi_j_u =
1439 * fe_values[velocities].value(j, q);
1440 * const double div_phi_j_u =
1441 * fe_values[velocities].divergence(j, q);
1442 * const double phi_j_p = fe_values[pressure].value(j, q);
1443 * const double phi_j_s = fe_values[saturation].value(j, q);
1445 * local_matrix(i, j) +=
1446 * (phi_i_u * k_inverse_values[q] *
1447 * mobility_inverse(old_s, viscosity) * phi_j_u -
1448 * div_phi_i_u * phi_j_p - phi_i_p * div_phi_j_u +
1449 * phi_i_s * phi_j_s) *
1454 * (-phi_i_p * pressure_rhs_values[q]) * fe_values.JxW(q);
1460 * Next, we also have to deal with the pressure boundary values. This,
1461 * again is as in @ref step_20 "step-20":
1464 * for (const auto &face : cell->face_iterators())
1465 * if (face->at_boundary())
1467 * fe_face_values.reinit(cell, face);
1469 * pressure_boundary_values.value_list(
1470 * fe_face_values.get_quadrature_points(), boundary_values);
1472 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1473 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1475 * const Tensor<1, dim> phi_i_u =
1476 * fe_face_values[velocities].value(i, q);
1479 * -(phi_i_u * fe_face_values.normal_vector(q) *
1480 * boundary_values[q] * fe_face_values.JxW(q));
1486 * The final step in the loop over all cells is to transfer local
1487 * contributions into the global matrix and right hand side vector:
1490 * cell->get_dof_indices(local_dof_indices);
1491 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1492 * for (unsigned int j = 0; j < dofs_per_cell; ++j)
1493 * system_matrix.add(local_dof_indices[i],
1494 * local_dof_indices[j],
1495 * local_matrix(i, j));
1497 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1498 * system_rhs(local_dof_indices[i]) += local_rhs(i);
1505 * So much for assembly of matrix and right hand side. Note that we do not
1506 * have to interpolate and apply boundary values since they have all been
1507 * taken care of in the weak form already.
1515 * <a name="step_21-TwoPhaseFlowProblemassemble_rhs_S"></a>
1516 * <h4>TwoPhaseFlowProblem::assemble_rhs_S</h4>
1520 * As explained in the introduction, we can only evaluate the right hand
1521 * side of the saturation equation once the velocity has been computed. We
1522 * therefore have this separate function to this end.
1525 * template <int dim>
1526 * void TwoPhaseFlowProblem<dim>::assemble_rhs_S()
1528 * const QGauss<dim> quadrature_formula(degree + 2);
1529 * const QGauss<dim - 1> face_quadrature_formula(degree + 2);
1530 * FEValues<dim> fe_values(fe,
1531 * quadrature_formula,
1532 * update_values | update_gradients |
1533 * update_quadrature_points | update_JxW_values);
1534 * FEFaceValues<dim> fe_face_values(fe,
1535 * face_quadrature_formula,
1536 * update_values | update_normal_vectors |
1537 * update_quadrature_points |
1538 * update_JxW_values);
1539 * FEFaceValues<dim> fe_face_values_neighbor(fe,
1540 * face_quadrature_formula,
1543 * const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1544 * const unsigned int n_q_points = quadrature_formula.size();
1545 * const unsigned int n_face_q_points = face_quadrature_formula.size();
1547 * Vector<double> local_rhs(dofs_per_cell);
1549 * std::vector<Vector<double>> old_solution_values(n_q_points,
1550 * Vector<double>(dim + 2));
1551 * std::vector<Vector<double>> old_solution_values_face(n_face_q_points,
1552 * Vector<double>(dim +
1554 * std::vector<Vector<double>> old_solution_values_face_neighbor(
1555 * n_face_q_points, Vector<double>(dim + 2));
1556 * std::vector<Vector<double>> present_solution_values(n_q_points,
1557 * Vector<double>(dim +
1559 * std::vector<Vector<double>> present_solution_values_face(
1560 * n_face_q_points, Vector<double>(dim + 2));
1562 * std::vector<double> neighbor_saturation(n_face_q_points);
1563 * std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1565 * SaturationBoundaryValues<dim> saturation_boundary_values;
1567 * const FEValuesExtractors::Scalar saturation(dim + 1);
1569 * for (const auto &cell : dof_handler.active_cell_iterators())
1572 * fe_values.reinit(cell);
1574 * fe_values.get_function_values(old_solution, old_solution_values);
1575 * fe_values.get_function_values(solution, present_solution_values);
1579 * First for the cell terms. These are, following the formulas in the
1580 * introduction, @f$(S^n,\sigma)-(F(S^n) \mathbf{v}^{n+1},\nabla
1581 * \sigma)@f$, where @f$\sigma@f$ is the saturation component of the test
1585 * for (unsigned int q = 0; q < n_q_points; ++q)
1586 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1588 * const double old_s = old_solution_values[q](dim + 1);
1589 * Tensor<1, dim> present_u;
1590 * for (unsigned int d = 0; d < dim; ++d)
1591 * present_u[d] = present_solution_values[q](d);
1593 * const double phi_i_s = fe_values[saturation].value(i, q);
1594 * const Tensor<1, dim> grad_phi_i_s =
1595 * fe_values[saturation].gradient(i, q);
1598 * (time.get_next_step_size() * fractional_flow(old_s, viscosity) *
1599 * present_u * grad_phi_i_s +
1600 * old_s * phi_i_s) *
1606 * Secondly, we have to deal with the flux parts on the face
1607 * boundaries. This was a bit more involved because we first have to
1608 * determine which are the influx and outflux parts of the cell
1609 * boundary. If we have an influx boundary, we need to evaluate the
1610 * saturation on the other side of the face (or the boundary values,
1611 * if we are at the boundary of the domain).
1615 * All this is a bit tricky, but has been explained in some detail
1616 * already in @ref step_9 "step-9". Take a look there how this is supposed to work!
1619 * for (const auto face_no : cell->face_indices())
1621 * fe_face_values.reinit(cell, face_no);
1623 * fe_face_values.get_function_values(old_solution,
1624 * old_solution_values_face);
1625 * fe_face_values.get_function_values(solution,
1626 * present_solution_values_face);
1628 * if (cell->at_boundary(face_no))
1629 * saturation_boundary_values.value_list(
1630 * fe_face_values.get_quadrature_points(), neighbor_saturation);
1633 * const auto neighbor = cell->neighbor(face_no);
1634 * const unsigned int neighbor_face =
1635 * cell->neighbor_of_neighbor(face_no);
1637 * fe_face_values_neighbor.reinit(neighbor, neighbor_face);
1639 * fe_face_values_neighbor.get_function_values(
1640 * old_solution, old_solution_values_face_neighbor);
1642 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1643 * neighbor_saturation[q] =
1644 * old_solution_values_face_neighbor[q](dim + 1);
1648 * for (unsigned int q = 0; q < n_face_q_points; ++q)
1650 * Tensor<1, dim> present_u_face;
1651 * for (unsigned int d = 0; d < dim; ++d)
1652 * present_u_face[d] = present_solution_values_face[q](d);
1654 * const double normal_flux =
1655 * present_u_face * fe_face_values.normal_vector(q);
1657 * const bool is_outflow_q_point = (normal_flux >= 0);
1659 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1661 * time.get_next_step_size() * normal_flux *
1662 * fractional_flow((is_outflow_q_point == true ?
1663 * old_solution_values_face[q](dim + 1) :
1664 * neighbor_saturation[q]),
1666 * fe_face_values[saturation].value(i, q) *
1667 * fe_face_values.JxW(q);
1671 * cell->get_dof_indices(local_dof_indices);
1672 * for (unsigned int i = 0; i < dofs_per_cell; ++i)
1673 * system_rhs(local_dof_indices[i]) += local_rhs(i);
1682 * <a name="step_21-TwoPhaseFlowProblemsolve"></a>
1683 * <h4>TwoPhaseFlowProblem::solve</h4>
1687 * After all these preparations, we finally solve the linear system for
1688 * velocity and pressure in the same way as in @ref step_20 "step-20". After that, we have
1689 * to deal with the saturation equation (see below):
1692 * template <int dim>
1693 * void TwoPhaseFlowProblem<dim>::solve()
1695 * const InverseMatrix<SparseMatrix<double>> m_inverse(
1696 * system_matrix.block(0, 0));
1697 * Vector<double> tmp(solution.block(0).size());
1698 * Vector<double> schur_rhs(solution.block(1).size());
1699 * Vector<double> tmp2(solution.block(2).size());
1704 * First the pressure, using the pressure Schur complement of the first
1709 * m_inverse.vmult(tmp, system_rhs.block(0));
1710 * system_matrix.block(1, 0).vmult(schur_rhs, tmp);
1711 * schur_rhs -= system_rhs.block(1);
1714 * SchurComplement schur_complement(system_matrix, m_inverse);
1716 * ApproximateSchurComplement approximate_schur_complement(system_matrix);
1718 * InverseMatrix<ApproximateSchurComplement> preconditioner(
1719 * approximate_schur_complement);
1722 * SolverControl solver_control(solution.block(1).size(),
1723 * 1e-12 * schur_rhs.l2_norm());
1724 * SolverCG<Vector<double>> cg(solver_control);
1726 * cg.solve(schur_complement, solution.block(1), schur_rhs, preconditioner);
1728 * std::cout << " " << solver_control.last_step()
1729 * << " CG Schur complement iterations for pressure." << std::endl;
1738 * system_matrix.block(0, 1).vmult(tmp, solution.block(1));
1740 * tmp += system_rhs.block(0);
1742 * m_inverse.vmult(solution.block(0), tmp);
1747 * Finally, we have to take care of the saturation equation. The first
1748 * business we have here is to determine the time step using the formula
1749 * in the introduction. Knowing the shape of our domain and that we
1750 * created the mesh by regular subdivision of cells, we can compute the
1751 * diameter of each of our cells quite easily (in fact we use the linear
1752 * extensions in coordinate directions of the cells, not the
1753 * diameter). Note that we will learn a more general way to do this in
1754 * @ref step_24 "step-24", where we use the GridTools::minimal_cell_diameter function.
1758 * The maximal velocity we compute using a helper function to compute the
1759 * maximal velocity defined below, and with all this we can evaluate our
1760 * new time step length. We use the method
1761 * DiscreteTime::set_desired_next_time_step() to suggest the new
1762 * calculated value of the time step to the DiscreteTime object. In most
1763 * cases, the time object uses the exact provided value to increment time.
1764 * It some case, the step size may be modified further by the time object.
1765 * For example, if the calculated time increment overshoots the end time,
1766 * it is truncated accordingly.
1769 * time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) /
1770 * get_maximal_velocity());
1774 * The next step is to assemble the right hand side, and then to pass
1775 * everything on for solution. At the end, we project back saturations
1776 * onto the physically reasonable range:
1781 * SolverControl solver_control(system_matrix.block(2, 2).m(),
1782 * 1e-8 * system_rhs.block(2).l2_norm());
1783 * SolverCG<Vector<double>> cg(solver_control);
1784 * cg.solve(system_matrix.block(2, 2),
1785 * solution.block(2),
1786 * system_rhs.block(2),
1787 * PreconditionIdentity());
1789 * project_back_saturation();
1791 * std::cout << " " << solver_control.last_step()
1792 * << " CG iterations for saturation." << std::endl;
1796 * old_solution = solution;
1803 * <a name="step_21-TwoPhaseFlowProblemoutput_results"></a>
1804 * <h4>TwoPhaseFlowProblem::output_results</h4>
1808 * There is nothing surprising here. Since the program will do a lot of time
1809 * steps, we create an output file only every fifth time step and skip all
1810 * other time steps at the top of the file already.
1814 * When creating file names for output close to the bottom of the function,
1815 * we convert the number of the time step to a string representation that
1816 * is padded by leading zeros to four digits. We do this because this way
1817 * all output file names have the same length, and consequently sort well
1818 * when creating a directory listing.
1821 * template <int dim>
1822 * void TwoPhaseFlowProblem<dim>::output_results() const
1824 * if (time.get_step_number() % 5 != 0)
1827 * std::vector<std::string> solution_names;
1831 * solution_names = {"u", "v", "p", "S"};
1835 * solution_names = {"u", "v", "w", "p", "S"};
1839 * DEAL_II_NOT_IMPLEMENTED();
1842 * DataOut<dim> data_out;
1844 * data_out.attach_dof_handler(dof_handler);
1845 * data_out.add_data_vector(solution, solution_names);
1847 * data_out.build_patches(degree + 1);
1849 * std::ofstream output("solution-" +
1850 * Utilities::int_to_string(time.get_step_number(), 4) +
1852 * data_out.write_vtk(output);
1860 * <a name="step_21-TwoPhaseFlowProblemproject_back_saturation"></a>
1861 * <h4>TwoPhaseFlowProblem::project_back_saturation</h4>
1865 * In this function, we simply run over all saturation degrees of freedom
1866 * and make sure that if they should have left the physically reasonable
1867 * range, that they be reset to the interval @f$[0,1]@f$. To do this, we only
1868 * have to loop over all saturation components of the solution vector; these
1869 * are stored in the block 2 (block 0 are the velocities, block 1 are the
1874 * It may be instructive to note that this function almost never triggers
1875 * when the time step is chosen as mentioned in the introduction. However,
1876 * if we choose the timestep only slightly larger, we get plenty of values
1877 * outside the proper range. Strictly speaking, the function is therefore
1878 * unnecessary if we choose the time step small enough. In a sense, the
1879 * function is therefore only a safety device to avoid situations where our
1880 * entire solution becomes unphysical because individual degrees of freedom
1881 * have become unphysical a few time steps earlier.
1884 * template <int dim>
1885 * void TwoPhaseFlowProblem<dim>::project_back_saturation()
1887 * for (unsigned int i = 0; i < solution.block(2).size(); ++i)
1888 * if (solution.block(2)(i) < 0)
1889 * solution.block(2)(i) = 0;
1890 * else if (solution.block(2)(i) > 1)
1891 * solution.block(2)(i) = 1;
1898 * <a name="step_21-TwoPhaseFlowProblemget_maximal_velocity"></a>
1899 * <h4>TwoPhaseFlowProblem::get_maximal_velocity</h4>
1903 * The following function is used in determining the maximal allowable time
1904 * step. What it does is to loop over all quadrature points in the domain
1905 * and find what the maximal magnitude of the velocity is.
1908 * template <int dim>
1909 * double TwoPhaseFlowProblem<dim>::get_maximal_velocity() const
1911 * const QGauss<dim> quadrature_formula(degree + 2);
1912 * const unsigned int n_q_points = quadrature_formula.size();
1914 * FEValues<dim> fe_values(fe, quadrature_formula, update_values);
1915 * std::vector<Vector<double>> solution_values(n_q_points,
1916 * Vector<double>(dim + 2));
1917 * double max_velocity = 0;
1919 * for (const auto &cell : dof_handler.active_cell_iterators())
1921 * fe_values.reinit(cell);
1922 * fe_values.get_function_values(solution, solution_values);
1924 * for (unsigned int q = 0; q < n_q_points; ++q)
1926 * Tensor<1, dim> velocity;
1927 * for (unsigned int i = 0; i < dim; ++i)
1928 * velocity[i] = solution_values[q](i);
1930 * max_velocity = std::max(max_velocity, velocity.norm());
1934 * return max_velocity;
1941 * <a name="step_21-TwoPhaseFlowProblemrun"></a>
1942 * <h4>TwoPhaseFlowProblem::run</h4>
1946 * This is the final function of our main class. Its brevity speaks for
1947 * itself. There are only two points worth noting: First, the function
1948 * projects the initial values onto the finite element space at the
1949 * beginning; the VectorTools::project function doing this requires an
1950 * argument indicating the hanging node constraints. We have none in this
1951 * program (we compute on a uniformly refined mesh), but the function
1952 * requires the argument anyway, of course. So we have to create a
1953 * constraint object. In its original state, constraint objects are
1954 * unsorted, and have to be sorted (using the AffineConstraints::close
1955 * function) before they can be used. This is what we do here, and which is
1962 * The
second point worth mentioning is that we only compute the length of
1963 * the present time step in the middle of solving the linear system
1964 * corresponding to each time step. We can therefore output the present
1965 * time of a time step only at the
end of the time step.
1967 *
inside the
loop. Since we are reporting the time and dt after we
1968 * increment it, we have to call the method
1970 *
DiscreteTime::get_next_step_size(). After many steps, when the simulation
1971 * reaches the end time, the last dt is chosen by the
DiscreteTime class in
1972 * such a way that the last step finishes exactly at the end time.
1975 * template <
int dim>
1976 *
void TwoPhaseFlowProblem<dim>::run()
1978 * make_grid_and_dofs();
1982 * constraints.
close();
1987 * InitialValues<dim>(),
1993 * std::cout <<
"Timestep " << time.get_step_number() + 1 << std::endl;
1995 * assemble_system();
2001 * time.advance_time();
2002 * std::cout <<
" Now at t=" << time.get_current_time()
2003 * <<
", dt=" << time.get_previous_step_size() <<
'.'
2007 *
while (time.is_at_end() ==
false);
2015 * <a name=
"step_21-Thecodemaincodefunction"></a>
2016 * <h3>The <code>main</code> function</h3>
2020 * That
's it. In the main function, we pass the degree of the finite element
2021 * space to the constructor of the TwoPhaseFlowProblem object. Here, we use
2022 * zero-th degree elements, i.e. @f$RT_0\times DQ_0 \times DQ_0@f$. The rest is as
2023 * in all the other programs.
2030 * using namespace Step21;
2032 * TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2033 * two_phase_flow_problem.run();
2035 * catch (std::exception &exc)
2037 * std::cerr << std::endl
2039 * << "----------------------------------------------------"
2041 * std::cerr << "Exception on processing: " << std::endl
2042 * << exc.what() << std::endl
2043 * << "Aborting!" << std::endl
2044 * << "----------------------------------------------------"
2051 * std::cerr << std::endl
2053 * << "----------------------------------------------------"
2055 * std::cerr << "Unknown exception!" << std::endl
2056 * << "Aborting!" << std::endl
2057 * << "----------------------------------------------------"
2065<a name="step_21-Results"></a><h1>Results</h1>
2068The code as presented here does not actually compute the results
2069found on the web page. The reason is, that even on a decent
2070computer it runs more than a day. If you want to reproduce these
2071results, modify the end time of the DiscreteTime object to `250` within the
2072constructor of TwoPhaseFlowProblem.
2074If we run the program, we get the following kind of output:
2076Number of active cells: 1024
2077Number of degrees of freedom: 4160 (2112+1024+1024)
2080 22 CG Schur complement iterations for pressure.
2081 1 CG iterations for saturation.
2082 Now at t=0.0326742, dt=0.0326742.
2085 17 CG Schur complement iterations for pressure.
2086 1 CG iterations for saturation.
2087 Now at t=0.0653816, dt=0.0327074.
2090 17 CG Schur complement iterations for pressure.
2091 1 CG iterations for saturation.
2092 Now at t=0.0980651, dt=0.0326836.
2096As we can see, the time step is pretty much constant right from the start,
2097which indicates that the velocities in the domain are not strongly dependent
2098on changes in saturation, although they certainly are through the factor
2099@f$\lambda(S)@f$ in the pressure equation.
2101Our second observation is that the number of CG iterations needed to solve the
2102pressure Schur complement equation drops from 22 to 17 between the first and
2103the second time step (in fact, it remains around 17 for the rest of the
2104computations). The reason is actually simple: Before we solve for the pressure
2105during a time step, we don't reset the <code>solution</code> variable to
2106zero. The pressure (and the other variables) therefore have the previous time
2107step
's values at the time we get into the CG solver. Since the velocities and
2108pressures don't change very much as computations progress, the previous time
2109step
's pressure is actually a good initial guess for this time step's
2110pressure. Consequently, the number of iterations we need once we have computed
2111the pressure once is significantly reduced.
2113The
final observation concerns the number of iterations needed to solve
for
2114the saturation, i.e. one. This shouldn
't surprise us too much: the matrix we
2115have to solve with is the mass matrix. However, this is the mass matrix for
2116the @f$DGQ_0@f$ element of piecewise constants where no element couples with the
2117degrees of freedom on neighboring cells. The matrix is therefore a diagonal
2118one, and it is clear that we should be able to invert this matrix in a single
2122With all this, here are a few movies that show how the saturation progresses
2123over time. First, this is for the single crack model, as implemented in the
2124<code>SingleCurvingCrack::KInverse</code> class:
2126<img src="https://www.dealii.org/images/steps/developer/step-21.centerline.gif" alt="">
2128As can be seen, the water rich fluid snakes its way mostly along the
2129high-permeability zone in the middle of the domain, whereas the rest of the
2130domain is mostly impermeable. This and the next movie are generated using
2131<code>n_refinement_steps=7</code>, leading to a @f$128\times 128@f$ mesh with some
213216,000 cells and about 66,000 unknowns in total.
2135The second movie shows the saturation for the random medium model of class
2136<code>RandomMedium::KInverse</code>, where we have randomly distributed
2137centers of high permeability and fluid hops from one of these zones to
2140<img src="https://www.dealii.org/images/steps/developer/step-21.random2d.gif" alt="">
2143Finally, here is the same situation in three space dimensions, on a mesh with
2144<code>n_refinement_steps=5</code>, which produces a mesh of some 32,000 cells
2145and 167,000 degrees of freedom:
2147<img src="https://www.dealii.org/images/steps/developer/step-21.random3d.gif" alt="">
2149To repeat these computations, all you have to do is to change the line
2151 TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2153in the main function to
2155 TwoPhaseFlowProblem<3> two_phase_flow_problem(0);
2157The visualization uses a cloud technique, where the saturation is indicated by
2158colored but transparent clouds for each cell. This way, one can also see
2159somewhat what happens deep inside the domain. A different way of visualizing
2160would have been to show isosurfaces of the saturation evolving over
2161time. There are techniques to plot isosurfaces transparently, so that one can
2162see several of them at the same time like the layers of an onion.
2164So why don't we show such isosurfaces? The problem lies in the way isosurfaces
2165are computed: they require that the field to be visualized is continuous, so
2166that the isosurfaces can be generated by following contours at least across a
2167single cell. However, our saturation field is piecewise
constant and
2168discontinuous. If we wanted to plot an isosurface
for a saturation @f$S=0.5@f$,
2169chances would be that there is no single
point in the domain where that
2170saturation is actually attained. If we had to define isosurfaces in that
2171context at all, we would have to take the interfaces between cells, where one
2172of the two adjacent cells has a saturation greater than and the other cell a
2173saturation less than 0.5. However, it appears that most visualization programs
2174are not equipped to
do this kind of transformation.
2177<a name=
"step-21-extensions"></a>
2178<a name=
"step_21-Possibilitiesforextensions"></a><h3>Possibilities
for extensions</h3>
2181There are a number of areas where
this program can be improved. Three of them
2182are listed below. All of them are, in fact, addressed in a tutorial program
2183that forms the continuation of the current one: @ref step_43
"step-43".
2186<a name=
"step_21-Solvers"></a><h4>Solvers</h4>
2189At present, the program is not particularly fast: the 2
d random medium
2190computation took about a day
for the 1,000 or so time steps. The corresponding
21913
d computation took almost two days
for 800 time steps. The reason why it
2192isn
't faster than this is twofold. First, we rebuild the entire matrix in
2193every time step, although some parts such as the @f$B@f$, @f$B^T@f$, and @f$M^S@f$ blocks
2196Second, we could do a lot better with the solver and
2197preconditioners. Presently, we solve the Schur complement @f$B^TM^u(S)^{-1}B@f$
2198with a CG method, using @f$[B^T (\textrm{diag}(M^u(S)))^{-1} B]^{-1}@f$ as a
2199preconditioner. Applying this preconditioner is expensive, since it involves
2200solving a linear system each time. This may have been appropriate for @ref
2201step_20 "step-20", where we have to solve the entire problem only
2202once. However, here we have to solve it hundreds of times, and in such cases
2203it is worth considering a preconditioner that is more expensive to set up the
2204first time, but cheaper to apply later on.
2206One possibility would be to realize that the matrix we use as preconditioner,
2207@f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ is still sparse, and symmetric on top of
2208that. If one looks at the flow field evolve over time, we also see that while
2209@f$S@f$ changes significantly over time, the pressure hardly does and consequently
2210@f$B^T (\textrm{diag}(M^u(S)))^{-1} B \approx B^T (\textrm{diag}(M^u(S^0)))^{-1}
2211B@f$. In other words, the matrix for the first time step should be a good
2212preconditioner also for all later time steps. With a bit of
2213back-and-forthing, it isn't hard to actually get a representation of it as a
2215a sparse incomplete Cholesky decomposition. To form this decomposition is
2216expensive, but we have to do it only once in the
first time step, and can then
2217use it as a cheap preconditioner in the future. We could do better even by
2219a complete decomposition of the
matrix, which should yield an even better
2222Finally, why use the approximation @f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ to
2223precondition @f$B^T M^u(S)^{-1} B@f$? The latter
matrix, after all, is the mixed
2224form of the Laplace
operator on the pressure space,
for which we use linear
2225elements. We could therefore build a separate
matrix @f$A^p@f$ on the side that
2226directly corresponds to the non-mixed formulation of the Laplacian,
for
2227example
using the bilinear form @f$(\mathbf{
K}\lambda(S^n) \nabla
2228\varphi_i,\nabla\varphi_j)@f$. We could then form an incomplete or complete
2229decomposition of
this non-mixed matrix and use it as a preconditioner of the
2232Using such techniques, it can reasonably be expected that the solution process
2233will be faster by at least an order of magnitude.
2236<a name=
"step_21-Timestepping"></a><h4>Time stepping</h4>
2239In the introduction we have identified the time step restriction
2241 \triangle t_{n+1} \le \frac h{|\mathbf{u}^{n+1}(\mathbf{x})|}
2243that has to hold globally, i.e.
for all @f$\mathbf x@f$. After discretization, we
2244satisfy it by choosing
2246 \triangle t_{n+1} = \frac {\min_K h_K}{\max_{\mathbf{x}}|\mathbf{u}^{n+1}(\mathbf{x})|}.
2249This restriction on the time step is somewhat annoying: the finer we make the
2250mesh the smaller the time step; in other words, we get punished twice: each
2251time step is more expensive to solve and we have to
do more time steps.
2253This is particularly annoying since the majority of the additional work is
2254spent solving the implicit part of the equations, i.e. the pressure-velocity
2255system, whereas it is the hyperbolic transport equation
for the saturation
2256that imposes the time step restriction.
2258To avoid
this bottleneck, people have invented a number of approaches. For
2259example, they may only re-compute the pressure-velocity field every few time
2260steps (or,
if you want, use different time step sizes
for the
2261pressure/velocity and saturation equations). This keeps the time step
2262restriction on the cheap
explicit part
while it makes the solution of the
2263implicit part less frequent. Experiments in
this direction are
2264certainly worthwhile; one starting
point for such an approach is the paper by
2265Zhangxin Chen, Guanren Huan and Baoyan Li: <i>An improved IMPES method
for
2266two-phase flow in porous media</i>, Transport in Porous Media, 54 (2004),
2267pp. 361—376. There are certainly many other papers on
this topic as well, but
2268this one happened to land on our desk a
while back.
2272<a name=
"step_21-Adaptivity"></a><h4>Adaptivity</h4>
2275Adaptivity would also clearly help. Looking at the movies, one clearly sees
2276that most of the action is confined to a relatively small part of the domain
2277(
this particularly obvious
for the saturation, but also holds
for the
2278velocities and pressures). Adaptivity can therefore be expected to keep the
2279necessary number of degrees of freedom low, or alternatively increase the
2282On the other hand, adaptivity
for time dependent problems is not a trivial
2283thing: we would have to change the mesh every few time steps, and we would
2284have to transport our present solution to the next mesh every time we change
2286insurmountable obstacles, but they
do require some additional coding and more
2287than we felt comfortable was worth packing into
this tutorial program.
2290<a name=
"step_21-PlainProg"></a>
2291<h1> The plain program</h1>
2292@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
#define AssertDimension(dim1, dim2)
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_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_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)
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