Reference documentation for deal.II version GIT relicensing-214-g6e74dec06b 2024-03-27 18:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
step-21.h
Go to the documentation of this file.
1,
811 *   const unsigned int /*component*/ = 0) const override
812 *   {
813 *   return 0;
814 *   }
815 *   };
816 *  
817 *  
818 *  
819 * @endcode
820 *
821 *
822 * <a name="step_21-Pressureboundaryvalues"></a>
823 * <h4>Pressure boundary values</h4>
824 *
825
826 *
827 * The next are pressure boundary values. As mentioned in the introduction,
828 * we choose a linear pressure field:
829 *
830 * @code
831 *   template <int dim>
832 *   class PressureBoundaryValues : public Function<dim>
833 *   {
834 *   public:
835 *   PressureBoundaryValues()
836 *   : Function<dim>(1)
837 *   {}
838 *  
839 *   virtual double value(const Point<dim> &p,
840 *   const unsigned int /*component*/ = 0) const override
841 *   {
842 *   return 1 - p[0];
843 *   }
844 *   };
845 *  
846 *  
847 *  
848 * @endcode
849 *
850 *
851 * <a name="step_21-Saturationboundaryvalues"></a>
852 * <h4>Saturation boundary values</h4>
853 *
854
855 *
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
860 * introduction:
861 *
862 * @code
863 *   template <int dim>
864 *   class SaturationBoundaryValues : public Function<dim>
865 *   {
866 *   public:
867 *   SaturationBoundaryValues()
868 *   : Function<dim>(1)
869 *   {}
870 *  
871 *   virtual double value(const Point<dim> &p,
872 *   const unsigned int /*component*/ = 0) const override
873 *   {
874 *   if (p[0] == 0)
875 *   return 1;
876 *   else
877 *   return 0;
878 *   }
879 *   };
880 *  
881 *  
882 *  
883 * @endcode
884 *
885 *
886 * <a name="step_21-Initialdata"></a>
887 * <h4>Initial data</h4>
888 *
889
890 *
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.
895 *
896
897 *
898 * We therefore simply create a function that returns zero in all
899 * components. We do that by simply forward every function to the
900 * Functions::ZeroFunction class. Why not use that right away in the places of
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
903 * function for initial values.
904 *
905 * @code
906 *   template <int dim>
907 *   class InitialValues : public Function<dim>
908 *   {
909 *   public:
910 *   InitialValues()
911 *   : Function<dim>(dim + 2)
912 *   {}
913 *  
914 *   virtual double value(const Point<dim> &p,
915 *   const unsigned int component = 0) const override
916 *   {
917 *   return Functions::ZeroFunction<dim>(dim + 2).value(p, component);
918 *   }
919 *  
920 *   virtual void vector_value(const Point<dim> &p,
921 *   Vector<double> &values) const override
922 *   {
923 *   Functions::ZeroFunction<dim>(dim + 2).vector_value(p, values);
924 *   }
925 *   };
926 *  
927 *  
928 *  
929 * @endcode
930 *
931 *
932 * <a name="step_21-Theinversepermeabilitytensor"></a>
933 * <h3>The inverse permeability tensor</h3>
934 *
935
936 *
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.
940 *
941
942 *
943 *
944 * <a name="step_21-Singlecurvingcrackpermeability"></a>
945 * <h4>Single curving crack permeability</h4>
946 *
947
948 *
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:
955 *
956 * @code
957 *   namespace SingleCurvingCrack
958 *   {
959 *   template <int dim>
960 *   class KInverse : public TensorFunction<2, dim>
961 *   {
962 *   public:
963 *   KInverse()
965 *   {}
966 *  
967 *   virtual void
968 *   value_list(const std::vector<Point<dim>> &points,
969 *   std::vector<Tensor<2, dim>> &values) const override
970 *   {
971 *   AssertDimension(points.size(), values.size());
972 *  
973 *   for (unsigned int p = 0; p < points.size(); ++p)
974 *   {
975 *   values[p].clear();
976 *  
977 *   const double distance_to_flowline =
978 *   std::fabs(points[p][1] - 0.5 - 0.1 * std::sin(10 * points[p][0]));
979 *  
980 *   const double permeability =
981 *   std::max(std::exp(-(distance_to_flowline * distance_to_flowline) /
982 *   (0.1 * 0.1)),
983 *   0.01);
984 *  
985 *   for (unsigned int d = 0; d < dim; ++d)
986 *   values[p][d][d] = 1. / permeability;
987 *   }
988 *   }
989 *   };
990 *   } // namespace SingleCurvingCrack
991 *  
992 *  
993 * @endcode
994 *
995 *
996 * <a name="step_21-Randommediumpermeability"></a>
997 * <h4>Random medium permeability</h4>
998 *
999
1000 *
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.
1009 *
1010
1011 *
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.
1016 *
1017
1018 *
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.
1027 *
1028
1029 *
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.
1037 *
1038 * @code
1039 *   namespace RandomMedium
1040 *   {
1041 *   template <int dim>
1042 *   class KInverse : public TensorFunction<2, dim>
1043 *   {
1044 *   public:
1045 *   KInverse()
1046 *   : TensorFunction<2, dim>()
1047 *   {}
1048 *  
1049 *   virtual void
1050 *   value_list(const std::vector<Point<dim>> &points,
1051 *   std::vector<Tensor<2, dim>> &values) const override
1052 *   {
1053 *   AssertDimension(points.size(), values.size());
1054 *  
1055 *   for (unsigned int p = 0; p < points.size(); ++p)
1056 *   {
1057 *   values[p].clear();
1058 *  
1059 *   double permeability = 0;
1060 *   for (unsigned int i = 0; i < centers.size(); ++i)
1061 *   permeability += std::exp(-(points[p] - centers[i]).norm_square() /
1062 *   (0.05 * 0.05));
1063 *  
1064 *   const double normalized_permeability =
1065 *   std::min(std::max(permeability, 0.01), 4.);
1066 *  
1067 *   for (unsigned int d = 0; d < dim; ++d)
1068 *   values[p][d][d] = 1. / normalized_permeability;
1069 *   }
1070 *   }
1071 *  
1072 *   private:
1073 *   static std::vector<Point<dim>> centers;
1074 *  
1075 *   static std::vector<Point<dim>> get_centers()
1076 *   {
1077 *   const unsigned int N =
1078 *   (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented()));
1079 *  
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;
1084 *  
1085 *   return centers_list;
1086 *   }
1087 *   };
1088 *  
1089 *  
1090 *  
1091 *   template <int dim>
1092 *   std::vector<Point<dim>> KInverse<dim>::centers =
1093 *   KInverse<dim>::get_centers();
1094 *   } // namespace RandomMedium
1095 *  
1096 *  
1097 *  
1098 * @endcode
1099 *
1100 *
1101 * <a name="step_21-Theinversemobilityandsaturationfunctions"></a>
1102 * <h3>The inverse mobility and saturation functions</h3>
1103 *
1104
1105 *
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:
1109 *
1110 * @code
1111 *   double mobility_inverse(const double S, const double viscosity)
1112 *   {
1113 *   return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S));
1114 *   }
1115 *  
1116 *   double fractional_flow(const double S, const double viscosity)
1117 *   {
1118 *   return S * S / (S * S + viscosity * (1 - S) * (1 - S));
1119 *   }
1120 *  
1121 *  
1122 *  
1123 * @endcode
1124 *
1125 *
1126 * <a name="step_21-Linearsolversandpreconditioners"></a>
1127 * <h3>Linear solvers and preconditioners</h3>
1128 *
1129
1130 *
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
1143 * system and 200.
1144 *
1145 * @code
1146 *   template <class MatrixType>
1147 *   class InverseMatrix : public Subscriptor
1148 *   {
1149 *   public:
1150 *   InverseMatrix(const MatrixType &m)
1151 *   : matrix(&m)
1152 *   {}
1153 *  
1154 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1155 *   {
1156 *   SolverControl solver_control(std::max<unsigned int>(src.size(), 200),
1157 *   1e-8 * src.l2_norm());
1158 *   SolverCG<Vector<double>> cg(solver_control);
1159 *  
1160 *   dst = 0;
1161 *  
1162 *   cg.solve(*matrix, dst, src, PreconditionIdentity());
1163 *   }
1164 *  
1165 *   private:
1166 *   const SmartPointer<const MatrixType> matrix;
1167 *   };
1168 *  
1169 *  
1170 *  
1171 *   class SchurComplement : public Subscriptor
1172 *   {
1173 *   public:
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())
1180 *   {}
1181 *  
1182 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1183 *   {
1184 *   system_matrix->block(0, 1).vmult(tmp1, src);
1185 *   m_inverse->vmult(tmp2, tmp1);
1186 *   system_matrix->block(1, 0).vmult(dst, tmp2);
1187 *   }
1188 *  
1189 *   private:
1190 *   const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1191 *   const SmartPointer<const InverseMatrix<SparseMatrix<double>>> m_inverse;
1192 *  
1193 *   mutable Vector<double> tmp1, tmp2;
1194 *   };
1195 *  
1196 *  
1197 *  
1198 *   class ApproximateSchurComplement : public Subscriptor
1199 *   {
1200 *   public:
1201 *   ApproximateSchurComplement(const BlockSparseMatrix<double> &A)
1202 *   : system_matrix(&A)
1203 *   , tmp1(A.block(0, 0).m())
1204 *   , tmp2(A.block(0, 0).m())
1205 *   {}
1206 *  
1207 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1208 *   {
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);
1212 *   }
1213 *  
1214 *   private:
1215 *   const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1216 *  
1217 *   mutable Vector<double> tmp1, tmp2;
1218 *   };
1219 *  
1220 *  
1221 *  
1222 * @endcode
1223 *
1224 *
1225 * <a name="step_21-codeTwoPhaseFlowProblemcodeclassimplementation"></a>
1226 * <h3><code>TwoPhaseFlowProblem</code> class implementation</h3>
1227 *
1228
1229 *
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.
1234 *
1235
1236 *
1237 *
1238 * <a name="step_21-TwoPhaseFlowProblemTwoPhaseFlowProblem"></a>
1239 * <h4>TwoPhaseFlowProblem::TwoPhaseFlowProblem</h4>
1240 *
1241
1242 *
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.
1251 *
1252 * @code
1253 *   template <int dim>
1254 *   TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(const unsigned int degree)
1255 *   : degree(degree)
1256 *   , fe(FE_RaviartThomas<dim>(degree),
1257 *   FE_DGQ<dim>(degree),
1258 *   FE_DGQ<dim>(degree))
1259 *   , dof_handler(triangulation)
1260 *   , n_refinement_steps(5)
1261 *   , time(/*start time*/ 0., /*end time*/ 1.)
1262 *   , viscosity(0.2)
1263 *   {}
1264 *  
1265 *  
1266 *  
1267 * @endcode
1268 *
1269 *
1270 * <a name="step_21-TwoPhaseFlowProblemmake_grid_and_dofs"></a>
1271 * <h4>TwoPhaseFlowProblem::make_grid_and_dofs</h4>
1272 *
1273
1274 *
1275 * This next function starts out with well-known functions calls that create
1276 * and refine a mesh, and then associate degrees of freedom with it. It does
1277 * all the same things as in @ref step_20 "step-20", just now for three components instead
1278 * of two.
1279 *
1280 * @code
1281 *   template <int dim>
1282 *   void TwoPhaseFlowProblem<dim>::make_grid_and_dofs()
1283 *   {
1285 *   triangulation.refine_global(n_refinement_steps);
1286 *  
1287 *   dof_handler.distribute_dofs(fe);
1288 *   DoFRenumbering::component_wise(dof_handler);
1289 *  
1290 *   const std::vector<types::global_dof_index> dofs_per_component =
1291 *   DoFTools::count_dofs_per_fe_component(dof_handler);
1292 *   const unsigned int n_u = dofs_per_component[0],
1293 *   n_p = dofs_per_component[dim],
1294 *   n_s = dofs_per_component[dim + 1];
1295 *  
1296 *   std::cout << "Number of active cells: " << triangulation.n_active_cells()
1297 *   << std::endl
1298 *   << "Number of degrees of freedom: " << dof_handler.n_dofs()
1299 *   << " (" << n_u << '+' << n_p << '+' << n_s << ')' << std::endl
1300 *   << std::endl;
1301 *  
1302 *   const std::vector<types::global_dof_index> block_sizes = {n_u, n_p, n_s};
1303 *   BlockDynamicSparsityPattern dsp(block_sizes, block_sizes);
1304 *   DoFTools::make_sparsity_pattern(dof_handler, dsp);
1305 *  
1306 *   sparsity_pattern.copy_from(dsp);
1307 *   system_matrix.reinit(sparsity_pattern);
1308 *  
1309 *   solution.reinit(block_sizes);
1310 *   old_solution.reinit(block_sizes);
1311 *   system_rhs.reinit(block_sizes);
1312 *   }
1313 *  
1314 *  
1315 * @endcode
1316 *
1317 *
1318 * <a name="step_21-TwoPhaseFlowProblemassemble_system"></a>
1319 * <h4>TwoPhaseFlowProblem::assemble_system</h4>
1320 *
1321
1322 *
1323 * This is the function that assembles the linear system, or at least
1324 * everything except the (1,3) block that depends on the still-unknown
1325 * velocity computed during this time step (we deal with this in
1326 * <code>assemble_rhs_S</code>). Much of it is again as in @ref step_20 "step-20", but we
1327 * have to deal with some nonlinearity this time. However, the top of the
1328 * function is pretty much as usual (note that we set matrix and right hand
1329 * side to zero at the beginning &mdash; something we didn't have to do for
1330 * stationary problems since there we use each matrix object only once and
1331 * it is empty at the beginning anyway).
1332 *
1333
1334 *
1335 * Note that in its present form, the function uses the permeability
1336 * implemented in the RandomMedium::KInverse class. Switching to the single
1337 * curved crack permeability function is as simple as just changing the
1338 * namespace name.
1339 *
1340 * @code
1341 *   template <int dim>
1342 *   void TwoPhaseFlowProblem<dim>::assemble_system()
1343 *   {
1344 *   system_matrix = 0;
1345 *   system_rhs = 0;
1346 *  
1347 *   QGauss<dim> quadrature_formula(degree + 2);
1348 *   QGauss<dim - 1> face_quadrature_formula(degree + 2);
1349 *  
1350 *   FEValues<dim> fe_values(fe,
1351 *   quadrature_formula,
1354 *   FEFaceValues<dim> fe_face_values(fe,
1355 *   face_quadrature_formula,
1358 *   update_JxW_values);
1359 *  
1360 *   const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1361 *  
1362 *   const unsigned int n_q_points = quadrature_formula.size();
1363 *   const unsigned int n_face_q_points = face_quadrature_formula.size();
1364 *  
1365 *   FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell);
1366 *   Vector<double> local_rhs(dofs_per_cell);
1367 *  
1368 *   std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1369 *  
1370 *   const PressureRightHandSide<dim> pressure_right_hand_side;
1371 *   const PressureBoundaryValues<dim> pressure_boundary_values;
1372 *   const RandomMedium::KInverse<dim> k_inverse;
1373 *  
1374 *   std::vector<double> pressure_rhs_values(n_q_points);
1375 *   std::vector<double> boundary_values(n_face_q_points);
1376 *   std::vector<Tensor<2, dim>> k_inverse_values(n_q_points);
1377 *  
1378 *   std::vector<Vector<double>> old_solution_values(n_q_points,
1379 *   Vector<double>(dim + 2));
1380 *  
1381 *   const FEValuesExtractors::Vector velocities(0);
1382 *   const FEValuesExtractors::Scalar pressure(dim);
1383 *   const FEValuesExtractors::Scalar saturation(dim + 1);
1384 *  
1385 *   for (const auto &cell : dof_handler.active_cell_iterators())
1386 *   {
1387 *   fe_values.reinit(cell);
1388 *   local_matrix = 0;
1389 *   local_rhs = 0;
1390 *  
1391 * @endcode
1392 *
1393 * Here's the first significant difference: We have to get the values
1394 * of the saturation function of the previous time step at the
1395 * quadrature points. To this end, we can use the
1396 * FEValues::get_function_values (previously already used in @ref step_9 "step-9",
1397 * @ref step_14 "step-14" and @ref step_15 "step-15"), a function that takes a solution vector and
1398 * returns a list of function values at the quadrature points of the
1399 * present cell. In fact, it returns the complete vector-valued
1400 * solution at each quadrature point, i.e. not only the saturation but
1401 * also the velocities and pressure:
1402 *
1403 * @code
1404 *   fe_values.get_function_values(old_solution, old_solution_values);
1405 *  
1406 * @endcode
1407 *
1408 * Then we also have to get the values of the pressure right hand side
1409 * and of the inverse permeability tensor at the quadrature points:
1410 *
1411 * @code
1412 *   pressure_right_hand_side.value_list(fe_values.get_quadrature_points(),
1413 *   pressure_rhs_values);
1414 *   k_inverse.value_list(fe_values.get_quadrature_points(),
1415 *   k_inverse_values);
1416 *  
1417 * @endcode
1418 *
1419 * With all this, we can now loop over all the quadrature points and
1420 * shape functions on this cell and assemble those parts of the matrix
1421 * and right hand side that we deal with in this function. The
1422 * individual terms in the contributions should be self-explanatory
1423 * given the explicit form of the bilinear form stated in the
1424 * introduction:
1425 *
1426 * @code
1427 *   for (unsigned int q = 0; q < n_q_points; ++q)
1428 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1429 *   {
1430 *   const double old_s = old_solution_values[q](dim + 1);
1431 *  
1432 *   const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q);
1433 *   const double div_phi_i_u = fe_values[velocities].divergence(i, q);
1434 *   const double phi_i_p = fe_values[pressure].value(i, q);
1435 *   const double phi_i_s = fe_values[saturation].value(i, q);
1436 *  
1437 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
1438 *   {
1439 *   const Tensor<1, dim> phi_j_u =
1440 *   fe_values[velocities].value(j, q);
1441 *   const double div_phi_j_u =
1442 *   fe_values[velocities].divergence(j, q);
1443 *   const double phi_j_p = fe_values[pressure].value(j, q);
1444 *   const double phi_j_s = fe_values[saturation].value(j, q);
1445 *  
1446 *   local_matrix(i, j) +=
1447 *   (phi_i_u * k_inverse_values[q] *
1448 *   mobility_inverse(old_s, viscosity) * phi_j_u -
1449 *   div_phi_i_u * phi_j_p - phi_i_p * div_phi_j_u +
1450 *   phi_i_s * phi_j_s) *
1451 *   fe_values.JxW(q);
1452 *   }
1453 *  
1454 *   local_rhs(i) +=
1455 *   (-phi_i_p * pressure_rhs_values[q]) * fe_values.JxW(q);
1456 *   }
1457 *  
1458 *  
1459 * @endcode
1460 *
1461 * Next, we also have to deal with the pressure boundary values. This,
1462 * again is as in @ref step_20 "step-20":
1463 *
1464 * @code
1465 *   for (const auto &face : cell->face_iterators())
1466 *   if (face->at_boundary())
1467 *   {
1468 *   fe_face_values.reinit(cell, face);
1469 *  
1470 *   pressure_boundary_values.value_list(
1471 *   fe_face_values.get_quadrature_points(), boundary_values);
1472 *  
1473 *   for (unsigned int q = 0; q < n_face_q_points; ++q)
1474 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1475 *   {
1476 *   const Tensor<1, dim> phi_i_u =
1477 *   fe_face_values[velocities].value(i, q);
1478 *  
1479 *   local_rhs(i) +=
1480 *   -(phi_i_u * fe_face_values.normal_vector(q) *
1481 *   boundary_values[q] * fe_face_values.JxW(q));
1482 *   }
1483 *   }
1484 *  
1485 * @endcode
1486 *
1487 * The final step in the loop over all cells is to transfer local
1488 * contributions into the global matrix and right hand side vector:
1489 *
1490 * @code
1491 *   cell->get_dof_indices(local_dof_indices);
1492 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1493 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
1494 *   system_matrix.add(local_dof_indices[i],
1495 *   local_dof_indices[j],
1496 *   local_matrix(i, j));
1497 *  
1498 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1499 *   system_rhs(local_dof_indices[i]) += local_rhs(i);
1500 *   }
1501 *   }
1502 *  
1503 *  
1504 * @endcode
1505 *
1506 * So much for assembly of matrix and right hand side. Note that we do not
1507 * have to interpolate and apply boundary values since they have all been
1508 * taken care of in the weak form already.
1509 *
1510
1511 *
1512 *
1513
1514 *
1515 *
1516 * <a name="step_21-TwoPhaseFlowProblemassemble_rhs_S"></a>
1517 * <h4>TwoPhaseFlowProblem::assemble_rhs_S</h4>
1518 *
1519
1520 *
1521 * As explained in the introduction, we can only evaluate the right hand
1522 * side of the saturation equation once the velocity has been computed. We
1523 * therefore have this separate function to this end.
1524 *
1525 * @code
1526 *   template <int dim>
1527 *   void TwoPhaseFlowProblem<dim>::assemble_rhs_S()
1528 *   {
1529 *   QGauss<dim> quadrature_formula(degree + 2);
1530 *   QGauss<dim - 1> face_quadrature_formula(degree + 2);
1531 *   FEValues<dim> fe_values(fe,
1532 *   quadrature_formula,
1533 *   update_values | update_gradients |
1534 *   update_quadrature_points | update_JxW_values);
1535 *   FEFaceValues<dim> fe_face_values(fe,
1536 *   face_quadrature_formula,
1537 *   update_values | update_normal_vectors |
1538 *   update_quadrature_points |
1539 *   update_JxW_values);
1540 *   FEFaceValues<dim> fe_face_values_neighbor(fe,
1541 *   face_quadrature_formula,
1542 *   update_values);
1543 *  
1544 *   const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1545 *   const unsigned int n_q_points = quadrature_formula.size();
1546 *   const unsigned int n_face_q_points = face_quadrature_formula.size();
1547 *  
1548 *   Vector<double> local_rhs(dofs_per_cell);
1549 *  
1550 *   std::vector<Vector<double>> old_solution_values(n_q_points,
1551 *   Vector<double>(dim + 2));
1552 *   std::vector<Vector<double>> old_solution_values_face(n_face_q_points,
1553 *   Vector<double>(dim +
1554 *   2));
1555 *   std::vector<Vector<double>> old_solution_values_face_neighbor(
1556 *   n_face_q_points, Vector<double>(dim + 2));
1557 *   std::vector<Vector<double>> present_solution_values(n_q_points,
1558 *   Vector<double>(dim +
1559 *   2));
1560 *   std::vector<Vector<double>> present_solution_values_face(
1561 *   n_face_q_points, Vector<double>(dim + 2));
1562 *  
1563 *   std::vector<double> neighbor_saturation(n_face_q_points);
1564 *   std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1565 *  
1566 *   SaturationBoundaryValues<dim> saturation_boundary_values;
1567 *  
1568 *   const FEValuesExtractors::Scalar saturation(dim + 1);
1569 *  
1570 *   for (const auto &cell : dof_handler.active_cell_iterators())
1571 *   {
1572 *   local_rhs = 0;
1573 *   fe_values.reinit(cell);
1574 *  
1575 *   fe_values.get_function_values(old_solution, old_solution_values);
1576 *   fe_values.get_function_values(solution, present_solution_values);
1577 *  
1578 * @endcode
1579 *
1580 * First for the cell terms. These are, following the formulas in the
1581 * introduction, @f$(S^n,\sigma)-(F(S^n) \mathbf{v}^{n+1},\nabla
1582 * \sigma)@f$, where @f$\sigma@f$ is the saturation component of the test
1583 * function:
1584 *
1585 * @code
1586 *   for (unsigned int q = 0; q < n_q_points; ++q)
1587 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1588 *   {
1589 *   const double old_s = old_solution_values[q](dim + 1);
1590 *   Tensor<1, dim> present_u;
1591 *   for (unsigned int d = 0; d < dim; ++d)
1592 *   present_u[d] = present_solution_values[q](d);
1593 *  
1594 *   const double phi_i_s = fe_values[saturation].value(i, q);
1595 *   const Tensor<1, dim> grad_phi_i_s =
1596 *   fe_values[saturation].gradient(i, q);
1597 *  
1598 *   local_rhs(i) +=
1599 *   (time.get_next_step_size() * fractional_flow(old_s, viscosity) *
1600 *   present_u * grad_phi_i_s +
1601 *   old_s * phi_i_s) *
1602 *   fe_values.JxW(q);
1603 *   }
1604 *  
1605 * @endcode
1606 *
1607 * Secondly, we have to deal with the flux parts on the face
1608 * boundaries. This was a bit more involved because we first have to
1609 * determine which are the influx and outflux parts of the cell
1610 * boundary. If we have an influx boundary, we need to evaluate the
1611 * saturation on the other side of the face (or the boundary values,
1612 * if we are at the boundary of the domain).
1613 *
1614
1615 *
1616 * All this is a bit tricky, but has been explained in some detail
1617 * already in @ref step_9 "step-9". Take a look there how this is supposed to work!
1618 *
1619 * @code
1620 *   for (const auto face_no : cell->face_indices())
1621 *   {
1622 *   fe_face_values.reinit(cell, face_no);
1623 *  
1624 *   fe_face_values.get_function_values(old_solution,
1625 *   old_solution_values_face);
1626 *   fe_face_values.get_function_values(solution,
1627 *   present_solution_values_face);
1628 *  
1629 *   if (cell->at_boundary(face_no))
1630 *   saturation_boundary_values.value_list(
1631 *   fe_face_values.get_quadrature_points(), neighbor_saturation);
1632 *   else
1633 *   {
1634 *   const auto neighbor = cell->neighbor(face_no);
1635 *   const unsigned int neighbor_face =
1636 *   cell->neighbor_of_neighbor(face_no);
1637 *  
1638 *   fe_face_values_neighbor.reinit(neighbor, neighbor_face);
1639 *  
1640 *   fe_face_values_neighbor.get_function_values(
1641 *   old_solution, old_solution_values_face_neighbor);
1642 *  
1643 *   for (unsigned int q = 0; q < n_face_q_points; ++q)
1644 *   neighbor_saturation[q] =
1645 *   old_solution_values_face_neighbor[q](dim + 1);
1646 *   }
1647 *  
1648 *  
1649 *   for (unsigned int q = 0; q < n_face_q_points; ++q)
1650 *   {
1651 *   Tensor<1, dim> present_u_face;
1652 *   for (unsigned int d = 0; d < dim; ++d)
1653 *   present_u_face[d] = present_solution_values_face[q](d);
1654 *  
1655 *   const double normal_flux =
1656 *   present_u_face * fe_face_values.normal_vector(q);
1657 *  
1658 *   const bool is_outflow_q_point = (normal_flux >= 0);
1659 *  
1660 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1661 *   local_rhs(i) -=
1662 *   time.get_next_step_size() * normal_flux *
1663 *   fractional_flow((is_outflow_q_point == true ?
1664 *   old_solution_values_face[q](dim + 1) :
1665 *   neighbor_saturation[q]),
1666 *   viscosity) *
1667 *   fe_face_values[saturation].value(i, q) *
1668 *   fe_face_values.JxW(q);
1669 *   }
1670 *   }
1671 *  
1672 *   cell->get_dof_indices(local_dof_indices);
1673 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1674 *   system_rhs(local_dof_indices[i]) += local_rhs(i);
1675 *   }
1676 *   }
1677 *  
1678 *  
1679 *  
1680 * @endcode
1681 *
1682 *
1683 * <a name="step_21-TwoPhaseFlowProblemsolve"></a>
1684 * <h4>TwoPhaseFlowProblem::solve</h4>
1685 *
1686
1687 *
1688 * After all these preparations, we finally solve the linear system for
1689 * velocity and pressure in the same way as in @ref step_20 "step-20". After that, we have
1690 * to deal with the saturation equation (see below):
1691 *
1692 * @code
1693 *   template <int dim>
1694 *   void TwoPhaseFlowProblem<dim>::solve()
1695 *   {
1696 *   const InverseMatrix<SparseMatrix<double>> m_inverse(
1697 *   system_matrix.block(0, 0));
1698 *   Vector<double> tmp(solution.block(0).size());
1699 *   Vector<double> schur_rhs(solution.block(1).size());
1700 *   Vector<double> tmp2(solution.block(2).size());
1701 *  
1702 *  
1703 * @endcode
1704 *
1705 * First the pressure, using the pressure Schur complement of the first
1706 * two equations:
1707 *
1708 * @code
1709 *   {
1710 *   m_inverse.vmult(tmp, system_rhs.block(0));
1711 *   system_matrix.block(1, 0).vmult(schur_rhs, tmp);
1712 *   schur_rhs -= system_rhs.block(1);
1713 *  
1714 *  
1715 *   SchurComplement schur_complement(system_matrix, m_inverse);
1716 *  
1717 *   ApproximateSchurComplement approximate_schur_complement(system_matrix);
1718 *  
1719 *   InverseMatrix<ApproximateSchurComplement> preconditioner(
1720 *   approximate_schur_complement);
1721 *  
1722 *  
1723 *   SolverControl solver_control(solution.block(1).size(),
1724 *   1e-12 * schur_rhs.l2_norm());
1725 *   SolverCG<Vector<double>> cg(solver_control);
1726 *  
1727 *   cg.solve(schur_complement, solution.block(1), schur_rhs, preconditioner);
1728 *  
1729 *   std::cout << " " << solver_control.last_step()
1730 *   << " CG Schur complement iterations for pressure." << std::endl;
1731 *   }
1732 *  
1733 * @endcode
1734 *
1735 * Now the velocity:
1736 *
1737 * @code
1738 *   {
1739 *   system_matrix.block(0, 1).vmult(tmp, solution.block(1));
1740 *   tmp *= -1;
1741 *   tmp += system_rhs.block(0);
1742 *  
1743 *   m_inverse.vmult(solution.block(0), tmp);
1744 *   }
1745 *  
1746 * @endcode
1747 *
1748 * Finally, we have to take care of the saturation equation. The first
1749 * business we have here is to determine the time step using the formula
1750 * in the introduction. Knowing the shape of our domain and that we
1751 * created the mesh by regular subdivision of cells, we can compute the
1752 * diameter of each of our cells quite easily (in fact we use the linear
1753 * extensions in coordinate directions of the cells, not the
1754 * diameter). Note that we will learn a more general way to do this in
1755 * @ref step_24 "step-24", where we use the GridTools::minimal_cell_diameter function.
1756 *
1757
1758 *
1759 * The maximal velocity we compute using a helper function to compute the
1760 * maximal velocity defined below, and with all this we can evaluate our
1761 * new time step length. We use the method
1762 * DiscreteTime::set_desired_next_time_step() to suggest the new
1763 * calculated value of the time step to the DiscreteTime object. In most
1764 * cases, the time object uses the exact provided value to increment time.
1765 * It some case, the step size may be modified further by the time object.
1766 * For example, if the calculated time increment overshoots the end time,
1767 * it is truncated accordingly.
1768 *
1769 * @code
1770 *   time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) /
1771 *   get_maximal_velocity());
1772 *  
1773 * @endcode
1774 *
1775 * The next step is to assemble the right hand side, and then to pass
1776 * everything on for solution. At the end, we project back saturations
1777 * onto the physically reasonable range:
1778 *
1779 * @code
1780 *   assemble_rhs_S();
1781 *   {
1782 *   SolverControl solver_control(system_matrix.block(2, 2).m(),
1783 *   1e-8 * system_rhs.block(2).l2_norm());
1784 *   SolverCG<Vector<double>> cg(solver_control);
1785 *   cg.solve(system_matrix.block(2, 2),
1786 *   solution.block(2),
1787 *   system_rhs.block(2),
1788 *   PreconditionIdentity());
1789 *  
1790 *   project_back_saturation();
1791 *  
1792 *   std::cout << " " << solver_control.last_step()
1793 *   << " CG iterations for saturation." << std::endl;
1794 *   }
1795 *  
1796 *  
1797 *   old_solution = solution;
1798 *   }
1799 *  
1800 *  
1801 * @endcode
1802 *
1803 *
1804 * <a name="step_21-TwoPhaseFlowProblemoutput_results"></a>
1805 * <h4>TwoPhaseFlowProblem::output_results</h4>
1806 *
1807
1808 *
1809 * There is nothing surprising here. Since the program will do a lot of time
1810 * steps, we create an output file only every fifth time step and skip all
1811 * other time steps at the top of the file already.
1812 *
1813
1814 *
1815 * When creating file names for output close to the bottom of the function,
1816 * we convert the number of the time step to a string representation that
1817 * is padded by leading zeros to four digits. We do this because this way
1818 * all output file names have the same length, and consequently sort well
1819 * when creating a directory listing.
1820 *
1821 * @code
1822 *   template <int dim>
1823 *   void TwoPhaseFlowProblem<dim>::output_results() const
1824 *   {
1825 *   if (time.get_step_number() % 5 != 0)
1826 *   return;
1827 *  
1828 *   std::vector<std::string> solution_names;
1829 *   switch (dim)
1830 *   {
1831 *   case 2:
1832 *   solution_names = {"u", "v", "p", "S"};
1833 *   break;
1834 *  
1835 *   case 3:
1836 *   solution_names = {"u", "v", "w", "p", "S"};
1837 *   break;
1838 *  
1839 *   default:
1840 *   DEAL_II_NOT_IMPLEMENTED();
1841 *   }
1842 *  
1843 *   DataOut<dim> data_out;
1844 *  
1845 *   data_out.attach_dof_handler(dof_handler);
1846 *   data_out.add_data_vector(solution, solution_names);
1847 *  
1848 *   data_out.build_patches(degree + 1);
1849 *  
1850 *   std::ofstream output("solution-" +
1851 *   Utilities::int_to_string(time.get_step_number(), 4) +
1852 *   ".vtk");
1853 *   data_out.write_vtk(output);
1854 *   }
1855 *  
1856 *  
1857 *  
1858 * @endcode
1859 *
1860 *
1861 * <a name="step_21-TwoPhaseFlowProblemproject_back_saturation"></a>
1862 * <h4>TwoPhaseFlowProblem::project_back_saturation</h4>
1863 *
1864
1865 *
1866 * In this function, we simply run over all saturation degrees of freedom
1867 * and make sure that if they should have left the physically reasonable
1868 * range, that they be reset to the interval @f$[0,1]@f$. To do this, we only
1869 * have to loop over all saturation components of the solution vector; these
1870 * are stored in the block 2 (block 0 are the velocities, block 1 are the
1871 * pressures).
1872 *
1873
1874 *
1875 * It may be instructive to note that this function almost never triggers
1876 * when the time step is chosen as mentioned in the introduction. However,
1877 * if we choose the timestep only slightly larger, we get plenty of values
1878 * outside the proper range. Strictly speaking, the function is therefore
1879 * unnecessary if we choose the time step small enough. In a sense, the
1880 * function is therefore only a safety device to avoid situations where our
1881 * entire solution becomes unphysical because individual degrees of freedom
1882 * have become unphysical a few time steps earlier.
1883 *
1884 * @code
1885 *   template <int dim>
1886 *   void TwoPhaseFlowProblem<dim>::project_back_saturation()
1887 *   {
1888 *   for (unsigned int i = 0; i < solution.block(2).size(); ++i)
1889 *   if (solution.block(2)(i) < 0)
1890 *   solution.block(2)(i) = 0;
1891 *   else if (solution.block(2)(i) > 1)
1892 *   solution.block(2)(i) = 1;
1893 *   }
1894 *  
1895 *  
1896 * @endcode
1897 *
1898 *
1899 * <a name="step_21-TwoPhaseFlowProblemget_maximal_velocity"></a>
1900 * <h4>TwoPhaseFlowProblem::get_maximal_velocity</h4>
1901 *
1902
1903 *
1904 * The following function is used in determining the maximal allowable time
1905 * step. What it does is to loop over all quadrature points in the domain
1906 * and find what the maximal magnitude of the velocity is.
1907 *
1908 * @code
1909 *   template <int dim>
1910 *   double TwoPhaseFlowProblem<dim>::get_maximal_velocity() const
1911 *   {
1912 *   QGauss<dim> quadrature_formula(degree + 2);
1913 *   const unsigned int n_q_points = quadrature_formula.size();
1914 *  
1915 *   FEValues<dim> fe_values(fe, quadrature_formula, update_values);
1916 *   std::vector<Vector<double>> solution_values(n_q_points,
1917 *   Vector<double>(dim + 2));
1918 *   double max_velocity = 0;
1919 *  
1920 *   for (const auto &cell : dof_handler.active_cell_iterators())
1921 *   {
1922 *   fe_values.reinit(cell);
1923 *   fe_values.get_function_values(solution, solution_values);
1924 *  
1925 *   for (unsigned int q = 0; q < n_q_points; ++q)
1926 *   {
1927 *   Tensor<1, dim> velocity;
1928 *   for (unsigned int i = 0; i < dim; ++i)
1929 *   velocity[i] = solution_values[q](i);
1930 *  
1931 *   max_velocity = std::max(max_velocity, velocity.norm());
1932 *   }
1933 *   }
1934 *  
1935 *   return max_velocity;
1936 *   }
1937 *  
1938 *  
1939 * @endcode
1940 *
1941 *
1942 * <a name="step_21-TwoPhaseFlowProblemrun"></a>
1943 * <h4>TwoPhaseFlowProblem::run</h4>
1944 *
1945
1946 *
1947 * This is the final function of our main class. Its brevity speaks for
1948 * itself. There are only two points worth noting: First, the function
1949 * projects the initial values onto the finite element space at the
1950 * beginning; the VectorTools::project function doing this requires an
1951 * argument indicating the hanging node constraints. We have none in this
1952 * program (we compute on a uniformly refined mesh), but the function
1953 * requires the argument anyway, of course. So we have to create a
1954 * constraint object. In its original state, constraint objects are
1955 * unsorted, and have to be sorted (using the AffineConstraints::close
1956 * function) before they can be used. This is what we do here, and which is
1957 * why we can't simply call the VectorTools::project function with an
1958 * anonymous temporary object <code>AffineConstraints<double>()</code> as the
1959 * second argument.
1960 *
1961
1962 *
1963 * The second point worth mentioning is that we only compute the length of
1964 * the present time step in the middle of solving the linear system
1965 * corresponding to each time step. We can therefore output the present
1966 * time of a time step only at the end of the time step.
1967 * We increment time by calling the method DiscreteTime::advance_time()
1968 * inside the loop. Since we are reporting the time and dt after we
1969 * increment it, we have to call the method
1971 * DiscreteTime::get_next_step_size(). After many steps, when the simulation
1972 * reaches the end time, the last dt is chosen by the DiscreteTime class in
1973 * such a way that the last step finishes exactly at the end time.
1974 *
1975 * @code
1976 *   template <int dim>
1977 *   void TwoPhaseFlowProblem<dim>::run()
1978 *   {
1979 *   make_grid_and_dofs();
1980 *  
1981 *   {
1982 *   AffineConstraints<double> constraints;
1983 *   constraints.close();
1984 *  
1985 *   VectorTools::project(dof_handler,
1986 *   constraints,
1987 *   QGauss<dim>(degree + 2),
1988 *   InitialValues<dim>(),
1989 *   old_solution);
1990 *   }
1991 *  
1992 *   do
1993 *   {
1994 *   std::cout << "Timestep " << time.get_step_number() + 1 << std::endl;
1995 *  
1996 *   assemble_system();
1997 *  
1998 *   solve();
1999 *  
2000 *   output_results();
2001 *  
2002 *   time.advance_time();
2003 *   std::cout << " Now at t=" << time.get_current_time()
2004 *   << ", dt=" << time.get_previous_step_size() << '.'
2005 *   << std::endl
2006 *   << std::endl;
2007 *   }
2008 *   while (time.is_at_end() == false);
2009 *   }
2010 *   } // namespace Step21
2011 *  
2012 *  
2013 * @endcode
2014 *
2015 *
2016 * <a name="step_21-Thecodemaincodefunction"></a>
2017 * <h3>The <code>main</code> function</h3>
2018 *
2019
2020 *
2021 * That's it. In the main function, we pass the degree of the finite element
2022 * space to the constructor of the TwoPhaseFlowProblem object. Here, we use
2023 * zero-th degree elements, i.e. @f$RT_0\times DQ_0 \times DQ_0@f$. The rest is as
2024 * in all the other programs.
2025 *
2026 * @code
2027 *   int main()
2028 *   {
2029 *   try
2030 *   {
2031 *   using namespace Step21;
2032 *  
2033 *   TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2034 *   two_phase_flow_problem.run();
2035 *   }
2036 *   catch (std::exception &exc)
2037 *   {
2038 *   std::cerr << std::endl
2039 *   << std::endl
2040 *   << "----------------------------------------------------"
2041 *   << std::endl;
2042 *   std::cerr << "Exception on processing: " << std::endl
2043 *   << exc.what() << std::endl
2044 *   << "Aborting!" << std::endl
2045 *   << "----------------------------------------------------"
2046 *   << std::endl;
2047 *  
2048 *   return 1;
2049 *   }
2050 *   catch (...)
2051 *   {
2052 *   std::cerr << std::endl
2053 *   << std::endl
2054 *   << "----------------------------------------------------"
2055 *   << std::endl;
2056 *   std::cerr << "Unknown exception!" << std::endl
2057 *   << "Aborting!" << std::endl
2058 *   << "----------------------------------------------------"
2059 *   << std::endl;
2060 *   return 1;
2061 *   }
2062 *  
2063 *   return 0;
2064 *   }
2065 * @endcode
2066<a name="step_21-Results"></a><h1>Results</h1>
2067
2068
2069The code as presented here does not actually compute the results
2070found on the web page. The reason is, that even on a decent
2071computer it runs more than a day. If you want to reproduce these
2072results, modify the end time of the DiscreteTime object to `250` within the
2073constructor of TwoPhaseFlowProblem.
2074
2075If we run the program, we get the following kind of output:
2076@code
2077Number of active cells: 1024
2078Number of degrees of freedom: 4160 (2112+1024+1024)
2079
2080Timestep 1
2081 22 CG Schur complement iterations for pressure.
2082 1 CG iterations for saturation.
2083 Now at t=0.0326742, dt=0.0326742.
2084
2085Timestep 2
2086 17 CG Schur complement iterations for pressure.
2087 1 CG iterations for saturation.
2088 Now at t=0.0653816, dt=0.0327074.
2089
2090Timestep 3
2091 17 CG Schur complement iterations for pressure.
2092 1 CG iterations for saturation.
2093 Now at t=0.0980651, dt=0.0326836.
2094
2095...
2096@endcode
2097As we can see, the time step is pretty much constant right from the start,
2098which indicates that the velocities in the domain are not strongly dependent
2099on changes in saturation, although they certainly are through the factor
2100@f$\lambda(S)@f$ in the pressure equation.
2101
2102Our second observation is that the number of CG iterations needed to solve the
2103pressure Schur complement equation drops from 22 to 17 between the first and
2104the second time step (in fact, it remains around 17 for the rest of the
2105computations). The reason is actually simple: Before we solve for the pressure
2106during a time step, we don't reset the <code>solution</code> variable to
2107zero. The pressure (and the other variables) therefore have the previous time
2108step's values at the time we get into the CG solver. Since the velocities and
2109pressures don't change very much as computations progress, the previous time
2110step's pressure is actually a good initial guess for this time step's
2111pressure. Consequently, the number of iterations we need once we have computed
2112the pressure once is significantly reduced.
2113
2114The final observation concerns the number of iterations needed to solve for
2115the saturation, i.e. one. This shouldn't surprise us too much: the matrix we
2116have to solve with is the mass matrix. However, this is the mass matrix for
2117the @f$DGQ_0@f$ element of piecewise constants where no element couples with the
2118degrees of freedom on neighboring cells. The matrix is therefore a diagonal
2119one, and it is clear that we should be able to invert this matrix in a single
2120CG iteration.
2121
2122
2123With all this, here are a few movies that show how the saturation progresses
2124over time. First, this is for the single crack model, as implemented in the
2125<code>SingleCurvingCrack::KInverse</code> class:
2126
2127<img src="https://www.dealii.org/images/steps/developer/step-21.centerline.gif" alt="">
2128
2129As can be seen, the water rich fluid snakes its way mostly along the
2130high-permeability zone in the middle of the domain, whereas the rest of the
2131domain is mostly impermeable. This and the next movie are generated using
2132<code>n_refinement_steps=7</code>, leading to a @f$128\times 128@f$ mesh with some
213316,000 cells and about 66,000 unknowns in total.
2134
2135
2136The second movie shows the saturation for the random medium model of class
2137<code>RandomMedium::KInverse</code>, where we have randomly distributed
2138centers of high permeability and fluid hops from one of these zones to
2139the next:
2140
2141<img src="https://www.dealii.org/images/steps/developer/step-21.random2d.gif" alt="">
2142
2143
2144Finally, here is the same situation in three space dimensions, on a mesh with
2145<code>n_refinement_steps=5</code>, which produces a mesh of some 32,000 cells
2146and 167,000 degrees of freedom:
2147
2148<img src="https://www.dealii.org/images/steps/developer/step-21.random3d.gif" alt="">
2149
2150To repeat these computations, all you have to do is to change the line
2151@code
2152 TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2153@endcode
2154in the main function to
2155@code
2156 TwoPhaseFlowProblem<3> two_phase_flow_problem(0);
2157@endcode
2158The visualization uses a cloud technique, where the saturation is indicated by
2159colored but transparent clouds for each cell. This way, one can also see
2160somewhat what happens deep inside the domain. A different way of visualizing
2161would have been to show isosurfaces of the saturation evolving over
2162time. There are techniques to plot isosurfaces transparently, so that one can
2163see several of them at the same time like the layers of an onion.
2164
2165So why don't we show such isosurfaces? The problem lies in the way isosurfaces
2166are computed: they require that the field to be visualized is continuous, so
2167that the isosurfaces can be generated by following contours at least across a
2168single cell. However, our saturation field is piecewise constant and
2169discontinuous. If we wanted to plot an isosurface for a saturation @f$S=0.5@f$,
2170chances would be that there is no single point in the domain where that
2171saturation is actually attained. If we had to define isosurfaces in that
2172context at all, we would have to take the interfaces between cells, where one
2173of the two adjacent cells has a saturation greater than and the other cell a
2174saturation less than 0.5. However, it appears that most visualization programs
2175are not equipped to do this kind of transformation.
2176
2177
2178<a name="step-21-extensions"></a>
2179<a name="step_21-Possibilitiesforextensions"></a><h3>Possibilities for extensions</h3>
2180
2181
2182There are a number of areas where this program can be improved. Three of them
2183are listed below. All of them are, in fact, addressed in a tutorial program
2184that forms the continuation of the current one: @ref step_43 "step-43".
2185
2186
2187<a name="step_21-Solvers"></a><h4>Solvers</h4>
2188
2189
2190At present, the program is not particularly fast: the 2d random medium
2191computation took about a day for the 1,000 or so time steps. The corresponding
21923d computation took almost two days for 800 time steps. The reason why it
2193isn't faster than this is twofold. First, we rebuild the entire matrix in
2194every time step, although some parts such as the @f$B@f$, @f$B^T@f$, and @f$M^S@f$ blocks
2195never change.
2196
2197Second, we could do a lot better with the solver and
2198preconditioners. Presently, we solve the Schur complement @f$B^TM^u(S)^{-1}B@f$
2199with a CG method, using @f$[B^T (\textrm{diag}(M^u(S)))^{-1} B]^{-1}@f$ as a
2200preconditioner. Applying this preconditioner is expensive, since it involves
2201solving a linear system each time. This may have been appropriate for @ref
2202step_20 "step-20", where we have to solve the entire problem only
2203once. However, here we have to solve it hundreds of times, and in such cases
2204it is worth considering a preconditioner that is more expensive to set up the
2205first time, but cheaper to apply later on.
2206
2207One possibility would be to realize that the matrix we use as preconditioner,
2208@f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ is still sparse, and symmetric on top of
2209that. If one looks at the flow field evolve over time, we also see that while
2210@f$S@f$ changes significantly over time, the pressure hardly does and consequently
2211@f$B^T (\textrm{diag}(M^u(S)))^{-1} B \approx B^T (\textrm{diag}(M^u(S^0)))^{-1}
2212B@f$. In other words, the matrix for the first time step should be a good
2213preconditioner also for all later time steps. With a bit of
2214back-and-forthing, it isn't hard to actually get a representation of it as a
2215SparseMatrix object. We could then hand it off to the SparseMIC class to form
2216a sparse incomplete Cholesky decomposition. To form this decomposition is
2217expensive, but we have to do it only once in the first time step, and can then
2218use it as a cheap preconditioner in the future. We could do better even by
2219using the SparseDirectUMFPACK class that produces not only an incomplete, but
2220a complete decomposition of the matrix, which should yield an even better
2221preconditioner.
2222
2223Finally, why use the approximation @f$B^T (\textrm{diag}(M^u(S)))^{-1} B@f$ to
2224precondition @f$B^T M^u(S)^{-1} B@f$? The latter matrix, after all, is the mixed
2225form of the Laplace operator on the pressure space, for which we use linear
2226elements. We could therefore build a separate matrix @f$A^p@f$ on the side that
2227directly corresponds to the non-mixed formulation of the Laplacian, for
2228example using the bilinear form @f$(\mathbf{K}\lambda(S^n) \nabla
2229\varphi_i,\nabla\varphi_j)@f$. We could then form an incomplete or complete
2230decomposition of this non-mixed matrix and use it as a preconditioner of the
2231mixed form.
2232
2233Using such techniques, it can reasonably be expected that the solution process
2234will be faster by at least an order of magnitude.
2235
2236
2237<a name="step_21-Timestepping"></a><h4>Time stepping</h4>
2238
2239
2240In the introduction we have identified the time step restriction
2241@f[
2242 \triangle t_{n+1} \le \frac h{|\mathbf{u}^{n+1}(\mathbf{x})|}
2243@f]
2244that has to hold globally, i.e. for all @f$\mathbf x@f$. After discretization, we
2245satisfy it by choosing
2246@f[
2247 \triangle t_{n+1} = \frac {\min_K h_K}{\max_{\mathbf{x}}|\mathbf{u}^{n+1}(\mathbf{x})|}.
2248@f]
2249
2250This restriction on the time step is somewhat annoying: the finer we make the
2251mesh the smaller the time step; in other words, we get punished twice: each
2252time step is more expensive to solve and we have to do more time steps.
2253
2254This is particularly annoying since the majority of the additional work is
2255spent solving the implicit part of the equations, i.e. the pressure-velocity
2256system, whereas it is the hyperbolic transport equation for the saturation
2257that imposes the time step restriction.
2258
2259To avoid this bottleneck, people have invented a number of approaches. For
2260example, they may only re-compute the pressure-velocity field every few time
2261steps (or, if you want, use different time step sizes for the
2262pressure/velocity and saturation equations). This keeps the time step
2263restriction on the cheap explicit part while it makes the solution of the
2264implicit part less frequent. Experiments in this direction are
2265certainly worthwhile; one starting point for such an approach is the paper by
2266Zhangxin Chen, Guanren Huan and Baoyan Li: <i>An improved IMPES method for
2267two-phase flow in porous media</i>, Transport in Porous Media, 54 (2004),
2268pp. 361&mdash;376. There are certainly many other papers on this topic as well, but
2269this one happened to land on our desk a while back.
2270
2271
2272
2273<a name="step_21-Adaptivity"></a><h4>Adaptivity</h4>
2274
2275
2276Adaptivity would also clearly help. Looking at the movies, one clearly sees
2277that most of the action is confined to a relatively small part of the domain
2278(this particularly obvious for the saturation, but also holds for the
2279velocities and pressures). Adaptivity can therefore be expected to keep the
2280necessary number of degrees of freedom low, or alternatively increase the
2281accuracy.
2282
2283On the other hand, adaptivity for time dependent problems is not a trivial
2284thing: we would have to change the mesh every few time steps, and we would
2285have to transport our present solution to the next mesh every time we change
2286it (something that the SolutionTransfer class can help with). These are not
2287insurmountable obstacles, but they do require some additional coding and more
2288than we felt comfortable was worth packing into this tutorial program.
2289 *
2290 *
2291<a name="step_21-PlainProg"></a>
2292<h1> The plain program</h1>
2293@include "step-21.cc"
2294*/
double get_previous_step_size() const
void advance_time()
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
Definition point.h:111
virtual void value_list(const std::vector< Point< dim > > &points, std::vector< value_type > &values) const
Point< 2 > second
Definition grid_out.cc:4614
Point< 2 > first
Definition grid_out.cc:4613
__global__ void set(Number *val, const Number s, const size_type N)
#define AssertDimension(dim1, dim2)
void loop(IteratorType begin, std_cxx20::type_identity_t< IteratorType > 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, AssemblerType &assembler, const LoopControl &lctrl=LoopControl())
Definition loop.h:442
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.
const Event initial
Definition event.cc:64
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)
std::vector< types::global_dof_index > count_dofs_per_fe_component(const DoFHandler< dim, spacedim > &dof_handler, const bool vector_valued_once=false, const std::vector< unsigned int > &target_component={})
void interpolate(const DoFHandler< dim, spacedim > &dof1, const InVector &u1, const DoFHandler< dim, spacedim > &dof2, OutVector &u2)
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)
spacedim const Point< spacedim > & p
Definition grid_tools.h:981
const std::vector< bool > & used
spacedim & mesh
Definition grid_tools.h:980
@ matrix
Contents is actually a matrix.
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
Definition utilities.cc:191
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
void project(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const AffineConstraints< typename VectorType::value_type > &constraints, const Quadrature< dim > &quadrature, const Function< spacedim, typename VectorType::value_type > &function, VectorType &vec, const bool enforce_zero_boundary=false, const Quadrature< dim - 1 > &q_boundary=(dim > 1 ? QGauss< dim - 1 >(2) :Quadrature< dim - 1 >(0)), const bool project_to_boundary_first=false)
int(&) functions(const void *v1, const void *v2)
void reinit(MatrixBlock< MatrixType > &v, const BlockSparsityPattern &p)
const InputIterator OutputIterator out
Definition parallel.h:167
const Iterator const std_cxx20::type_identity_t< Iterator > & end
Definition parallel.h:610
const InputIterator OutputIterator const Function & function
Definition parallel.h:168
::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