deal.II version GIT relicensing-1721-g8100761196 2024-08-31 12:30:00+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,
810 *   const unsigned int /*component*/ = 0) const override
811 *   {
812 *   return 0;
813 *   }
814 *   };
815 *  
816 *  
817 *  
818 * @endcode
819 *
820 *
821 * <a name="step_21-Pressureboundaryvalues"></a>
822 * <h4>Pressure boundary values</h4>
823 *
824
825 *
826 * The next are pressure boundary values. As mentioned in the introduction,
827 * we choose a linear pressure field:
828 *
829 * @code
830 *   template <int dim>
831 *   class PressureBoundaryValues : public Function<dim>
832 *   {
833 *   public:
834 *   PressureBoundaryValues()
835 *   : Function<dim>(1)
836 *   {}
837 *  
838 *   virtual double value(const Point<dim> &p,
839 *   const unsigned int /*component*/ = 0) const override
840 *   {
841 *   return 1 - p[0];
842 *   }
843 *   };
844 *  
845 *  
846 *  
847 * @endcode
848 *
849 *
850 * <a name="step_21-Saturationboundaryvalues"></a>
851 * <h4>Saturation boundary values</h4>
852 *
853
854 *
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
859 * introduction:
860 *
861 * @code
862 *   template <int dim>
863 *   class SaturationBoundaryValues : public Function<dim>
864 *   {
865 *   public:
866 *   SaturationBoundaryValues()
867 *   : Function<dim>(1)
868 *   {}
869 *  
870 *   virtual double value(const Point<dim> &p,
871 *   const unsigned int /*component*/ = 0) const override
872 *   {
873 *   if (p[0] == 0)
874 *   return 1;
875 *   else
876 *   return 0;
877 *   }
878 *   };
879 *  
880 *  
881 *  
882 * @endcode
883 *
884 *
885 * <a name="step_21-Initialdata"></a>
886 * <h4>Initial data</h4>
887 *
888
889 *
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.
894 *
895
896 *
897 * We therefore simply create a function that returns zero in all
898 * components. We do that by simply forward every function to the
899 * Functions::ZeroFunction class. Why not use that right away in the places of
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
902 * function for initial values.
903 *
904 * @code
905 *   template <int dim>
906 *   class InitialValues : public Function<dim>
907 *   {
908 *   public:
909 *   InitialValues()
910 *   : Function<dim>(dim + 2)
911 *   {}
912 *  
913 *   virtual double value(const Point<dim> &p,
914 *   const unsigned int component = 0) const override
915 *   {
916 *   return Functions::ZeroFunction<dim>(dim + 2).value(p, component);
917 *   }
918 *  
919 *   virtual void vector_value(const Point<dim> &p,
920 *   Vector<double> &values) const override
921 *   {
922 *   Functions::ZeroFunction<dim>(dim + 2).vector_value(p, values);
923 *   }
924 *   };
925 *  
926 *  
927 *  
928 * @endcode
929 *
930 *
931 * <a name="step_21-Theinversepermeabilitytensor"></a>
932 * <h3>The inverse permeability tensor</h3>
933 *
934
935 *
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.
939 *
940
941 *
942 *
943 * <a name="step_21-Singlecurvingcrackpermeability"></a>
944 * <h4>Single curving crack permeability</h4>
945 *
946
947 *
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:
954 *
955 * @code
956 *   namespace SingleCurvingCrack
957 *   {
958 *   template <int dim>
959 *   class KInverse : public TensorFunction<2, dim>
960 *   {
961 *   public:
962 *   KInverse()
964 *   {}
965 *  
966 *   virtual void
967 *   value_list(const std::vector<Point<dim>> &points,
968 *   std::vector<Tensor<2, dim>> &values) const override
969 *   {
970 *   AssertDimension(points.size(), values.size());
971 *  
972 *   for (unsigned int p = 0; p < points.size(); ++p)
973 *   {
974 *   values[p].clear();
975 *  
976 *   const double distance_to_flowline =
977 *   std::fabs(points[p][1] - 0.5 - 0.1 * std::sin(10 * points[p][0]));
978 *  
979 *   const double permeability =
980 *   std::max(std::exp(-(distance_to_flowline * distance_to_flowline) /
981 *   (0.1 * 0.1)),
982 *   0.01);
983 *  
984 *   for (unsigned int d = 0; d < dim; ++d)
985 *   values[p][d][d] = 1. / permeability;
986 *   }
987 *   }
988 *   };
989 *   } // namespace SingleCurvingCrack
990 *  
991 *  
992 * @endcode
993 *
994 *
995 * <a name="step_21-Randommediumpermeability"></a>
996 * <h4>Random medium permeability</h4>
997 *
998
999 *
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.
1008 *
1009
1010 *
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.
1015 *
1016
1017 *
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.
1026 *
1027
1028 *
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.
1036 *
1037 * @code
1038 *   namespace RandomMedium
1039 *   {
1040 *   template <int dim>
1041 *   class KInverse : public TensorFunction<2, dim>
1042 *   {
1043 *   public:
1044 *   KInverse()
1045 *   : TensorFunction<2, dim>()
1046 *   {}
1047 *  
1048 *   virtual void
1049 *   value_list(const std::vector<Point<dim>> &points,
1050 *   std::vector<Tensor<2, dim>> &values) const override
1051 *   {
1052 *   AssertDimension(points.size(), values.size());
1053 *  
1054 *   for (unsigned int p = 0; p < points.size(); ++p)
1055 *   {
1056 *   values[p].clear();
1057 *  
1058 *   double permeability = 0;
1059 *   for (unsigned int i = 0; i < centers.size(); ++i)
1060 *   permeability += std::exp(-(points[p] - centers[i]).norm_square() /
1061 *   (0.05 * 0.05));
1062 *  
1063 *   const double normalized_permeability =
1064 *   std::min(std::max(permeability, 0.01), 4.);
1065 *  
1066 *   for (unsigned int d = 0; d < dim; ++d)
1067 *   values[p][d][d] = 1. / normalized_permeability;
1068 *   }
1069 *   }
1070 *  
1071 *   private:
1072 *   static std::vector<Point<dim>> centers;
1073 *  
1074 *   static std::vector<Point<dim>> get_centers()
1075 *   {
1076 *   const unsigned int N =
1077 *   (dim == 2 ? 40 : (dim == 3 ? 100 : throw ExcNotImplemented()));
1078 *  
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;
1083 *  
1084 *   return centers_list;
1085 *   }
1086 *   };
1087 *  
1088 *  
1089 *  
1090 *   template <int dim>
1091 *   std::vector<Point<dim>> KInverse<dim>::centers =
1092 *   KInverse<dim>::get_centers();
1093 *   } // namespace RandomMedium
1094 *  
1095 *  
1096 *  
1097 * @endcode
1098 *
1099 *
1100 * <a name="step_21-Theinversemobilityandsaturationfunctions"></a>
1101 * <h3>The inverse mobility and saturation functions</h3>
1102 *
1103
1104 *
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:
1108 *
1109 * @code
1110 *   double mobility_inverse(const double S, const double viscosity)
1111 *   {
1112 *   return 1.0 / (1.0 / viscosity * S * S + (1 - S) * (1 - S));
1113 *   }
1114 *  
1115 *   double fractional_flow(const double S, const double viscosity)
1116 *   {
1117 *   return S * S / (S * S + viscosity * (1 - S) * (1 - S));
1118 *   }
1119 *  
1120 *  
1121 *  
1122 * @endcode
1123 *
1124 *
1125 * <a name="step_21-Linearsolversandpreconditioners"></a>
1126 * <h3>Linear solvers and preconditioners</h3>
1127 *
1128
1129 *
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
1142 * system and 200.
1143 *
1144 * @code
1145 *   template <class MatrixType>
1146 *   class InverseMatrix : public Subscriptor
1147 *   {
1148 *   public:
1149 *   InverseMatrix(const MatrixType &m)
1150 *   : matrix(&m)
1151 *   {}
1152 *  
1153 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1154 *   {
1155 *   SolverControl solver_control(std::max<unsigned int>(src.size(), 200),
1156 *   1e-8 * src.l2_norm());
1157 *   SolverCG<Vector<double>> cg(solver_control);
1158 *  
1159 *   dst = 0;
1160 *  
1161 *   cg.solve(*matrix, dst, src, PreconditionIdentity());
1162 *   }
1163 *  
1164 *   private:
1165 *   const SmartPointer<const MatrixType> matrix;
1166 *   };
1167 *  
1168 *  
1169 *  
1170 *   class SchurComplement : public Subscriptor
1171 *   {
1172 *   public:
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())
1179 *   {}
1180 *  
1181 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1182 *   {
1183 *   system_matrix->block(0, 1).vmult(tmp1, src);
1184 *   m_inverse->vmult(tmp2, tmp1);
1185 *   system_matrix->block(1, 0).vmult(dst, tmp2);
1186 *   }
1187 *  
1188 *   private:
1189 *   const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1190 *   const SmartPointer<const InverseMatrix<SparseMatrix<double>>> m_inverse;
1191 *  
1192 *   mutable Vector<double> tmp1, tmp2;
1193 *   };
1194 *  
1195 *  
1196 *  
1197 *   class ApproximateSchurComplement : public Subscriptor
1198 *   {
1199 *   public:
1200 *   ApproximateSchurComplement(const BlockSparseMatrix<double> &A)
1201 *   : system_matrix(&A)
1202 *   , tmp1(A.block(0, 0).m())
1203 *   , tmp2(A.block(0, 0).m())
1204 *   {}
1205 *  
1206 *   void vmult(Vector<double> &dst, const Vector<double> &src) const
1207 *   {
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);
1211 *   }
1212 *  
1213 *   private:
1214 *   const SmartPointer<const BlockSparseMatrix<double>> system_matrix;
1215 *  
1216 *   mutable Vector<double> tmp1, tmp2;
1217 *   };
1218 *  
1219 *  
1220 *  
1221 * @endcode
1222 *
1223 *
1224 * <a name="step_21-codeTwoPhaseFlowProblemcodeclassimplementation"></a>
1225 * <h3><code>TwoPhaseFlowProblem</code> class implementation</h3>
1226 *
1227
1228 *
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.
1233 *
1234
1235 *
1236 *
1237 * <a name="step_21-TwoPhaseFlowProblemTwoPhaseFlowProblem"></a>
1238 * <h4>TwoPhaseFlowProblem::TwoPhaseFlowProblem</h4>
1239 *
1240
1241 *
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.
1250 *
1251 * @code
1252 *   template <int dim>
1253 *   TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem(const unsigned int degree)
1254 *   : degree(degree)
1255 *   , fe(FE_RaviartThomas<dim>(degree),
1256 *   FE_DGQ<dim>(degree),
1257 *   FE_DGQ<dim>(degree))
1258 *   , dof_handler(triangulation)
1259 *   , n_refinement_steps(5)
1260 *   , time(/*start time*/ 0., /*end time*/ 1.)
1261 *   , viscosity(0.2)
1262 *   {}
1263 *  
1264 *  
1265 *  
1266 * @endcode
1267 *
1268 *
1269 * <a name="step_21-TwoPhaseFlowProblemmake_grid_and_dofs"></a>
1270 * <h4>TwoPhaseFlowProblem::make_grid_and_dofs</h4>
1271 *
1272
1273 *
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
1277 * of two.
1278 *
1279 * @code
1280 *   template <int dim>
1281 *   void TwoPhaseFlowProblem<dim>::make_grid_and_dofs()
1282 *   {
1284 *   triangulation.refine_global(n_refinement_steps);
1285 *  
1286 *   dof_handler.distribute_dofs(fe);
1287 *   DoFRenumbering::component_wise(dof_handler);
1288 *  
1289 *   const std::vector<types::global_dof_index> dofs_per_component =
1290 *   DoFTools::count_dofs_per_fe_component(dof_handler);
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];
1294 *  
1295 *   std::cout << "Number of active cells: " << triangulation.n_active_cells()
1296 *   << std::endl
1297 *   << "Number of degrees of freedom: " << dof_handler.n_dofs()
1298 *   << " (" << n_u << '+' << n_p << '+' << n_s << ')' << std::endl
1299 *   << std::endl;
1300 *  
1301 *   const std::vector<types::global_dof_index> block_sizes = {n_u, n_p, n_s};
1302 *   BlockDynamicSparsityPattern dsp(block_sizes, block_sizes);
1303 *   DoFTools::make_sparsity_pattern(dof_handler, dsp);
1304 *  
1305 *   sparsity_pattern.copy_from(dsp);
1306 *   system_matrix.reinit(sparsity_pattern);
1307 *  
1308 *   solution.reinit(block_sizes);
1309 *   old_solution.reinit(block_sizes);
1310 *   system_rhs.reinit(block_sizes);
1311 *   }
1312 *  
1313 *  
1314 * @endcode
1315 *
1316 *
1317 * <a name="step_21-TwoPhaseFlowProblemassemble_system"></a>
1318 * <h4>TwoPhaseFlowProblem::assemble_system</h4>
1319 *
1320
1321 *
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 &mdash; 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).
1331 *
1332
1333 *
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
1337 * namespace name.
1338 *
1339 * @code
1340 *   template <int dim>
1341 *   void TwoPhaseFlowProblem<dim>::assemble_system()
1342 *   {
1343 *   system_matrix = 0;
1344 *   system_rhs = 0;
1345 *  
1346 *   const QGauss<dim> quadrature_formula(degree + 2);
1347 *   const QGauss<dim - 1> face_quadrature_formula(degree + 2);
1348 *  
1349 *   FEValues<dim> fe_values(fe,
1350 *   quadrature_formula,
1353 *   FEFaceValues<dim> fe_face_values(fe,
1354 *   face_quadrature_formula,
1357 *   update_JxW_values);
1358 *  
1359 *   const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
1360 *  
1361 *   const unsigned int n_q_points = quadrature_formula.size();
1362 *   const unsigned int n_face_q_points = face_quadrature_formula.size();
1363 *  
1364 *   FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell);
1365 *   Vector<double> local_rhs(dofs_per_cell);
1366 *  
1367 *   std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1368 *  
1369 *   const PressureRightHandSide<dim> pressure_right_hand_side;
1370 *   const PressureBoundaryValues<dim> pressure_boundary_values;
1371 *   const RandomMedium::KInverse<dim> k_inverse;
1372 *  
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);
1376 *  
1377 *   std::vector<Vector<double>> old_solution_values(n_q_points,
1378 *   Vector<double>(dim + 2));
1379 *  
1380 *   const FEValuesExtractors::Vector velocities(0);
1381 *   const FEValuesExtractors::Scalar pressure(dim);
1382 *   const FEValuesExtractors::Scalar saturation(dim + 1);
1383 *  
1384 *   for (const auto &cell : dof_handler.active_cell_iterators())
1385 *   {
1386 *   fe_values.reinit(cell);
1387 *   local_matrix = 0;
1388 *   local_rhs = 0;
1389 *  
1390 * @endcode
1391 *
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:
1401 *
1402 * @code
1403 *   fe_values.get_function_values(old_solution, old_solution_values);
1404 *  
1405 * @endcode
1406 *
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:
1409 *
1410 * @code
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);
1415 *  
1416 * @endcode
1417 *
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
1423 * introduction:
1424 *
1425 * @code
1426 *   for (unsigned int q = 0; q < n_q_points; ++q)
1427 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1428 *   {
1429 *   const double old_s = old_solution_values[q](dim + 1);
1430 *  
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);
1435 *  
1436 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
1437 *   {
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);
1444 *  
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) *
1450 *   fe_values.JxW(q);
1451 *   }
1452 *  
1453 *   local_rhs(i) +=
1454 *   (-phi_i_p * pressure_rhs_values[q]) * fe_values.JxW(q);
1455 *   }
1456 *  
1457 *  
1458 * @endcode
1459 *
1460 * Next, we also have to deal with the pressure boundary values. This,
1461 * again is as in @ref step_20 "step-20":
1462 *
1463 * @code
1464 *   for (const auto &face : cell->face_iterators())
1465 *   if (face->at_boundary())
1466 *   {
1467 *   fe_face_values.reinit(cell, face);
1468 *  
1469 *   pressure_boundary_values.value_list(
1470 *   fe_face_values.get_quadrature_points(), boundary_values);
1471 *  
1472 *   for (unsigned int q = 0; q < n_face_q_points; ++q)
1473 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1474 *   {
1475 *   const Tensor<1, dim> phi_i_u =
1476 *   fe_face_values[velocities].value(i, q);
1477 *  
1478 *   local_rhs(i) +=
1479 *   -(phi_i_u * fe_face_values.normal_vector(q) *
1480 *   boundary_values[q] * fe_face_values.JxW(q));
1481 *   }
1482 *   }
1483 *  
1484 * @endcode
1485 *
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:
1488 *
1489 * @code
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));
1496 *  
1497 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1498 *   system_rhs(local_dof_indices[i]) += local_rhs(i);
1499 *   }
1500 *   }
1501 *  
1502 *  
1503 * @endcode
1504 *
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.
1508 *
1509
1510 *
1511 *
1512
1513 *
1514 *
1515 * <a name="step_21-TwoPhaseFlowProblemassemble_rhs_S"></a>
1516 * <h4>TwoPhaseFlowProblem::assemble_rhs_S</h4>
1517 *
1518
1519 *
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.
1523 *
1524 * @code
1525 *   template <int dim>
1526 *   void TwoPhaseFlowProblem<dim>::assemble_rhs_S()
1527 *   {
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,
1541 *   update_values);
1542 *  
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();
1546 *  
1547 *   Vector<double> local_rhs(dofs_per_cell);
1548 *  
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 +
1553 *   2));
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 +
1558 *   2));
1559 *   std::vector<Vector<double>> present_solution_values_face(
1560 *   n_face_q_points, Vector<double>(dim + 2));
1561 *  
1562 *   std::vector<double> neighbor_saturation(n_face_q_points);
1563 *   std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1564 *  
1565 *   SaturationBoundaryValues<dim> saturation_boundary_values;
1566 *  
1567 *   const FEValuesExtractors::Scalar saturation(dim + 1);
1568 *  
1569 *   for (const auto &cell : dof_handler.active_cell_iterators())
1570 *   {
1571 *   local_rhs = 0;
1572 *   fe_values.reinit(cell);
1573 *  
1574 *   fe_values.get_function_values(old_solution, old_solution_values);
1575 *   fe_values.get_function_values(solution, present_solution_values);
1576 *  
1577 * @endcode
1578 *
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
1582 * function:
1583 *
1584 * @code
1585 *   for (unsigned int q = 0; q < n_q_points; ++q)
1586 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1587 *   {
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);
1592 *  
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);
1596 *  
1597 *   local_rhs(i) +=
1598 *   (time.get_next_step_size() * fractional_flow(old_s, viscosity) *
1599 *   present_u * grad_phi_i_s +
1600 *   old_s * phi_i_s) *
1601 *   fe_values.JxW(q);
1602 *   }
1603 *  
1604 * @endcode
1605 *
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).
1612 *
1613
1614 *
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!
1617 *
1618 * @code
1619 *   for (const auto face_no : cell->face_indices())
1620 *   {
1621 *   fe_face_values.reinit(cell, face_no);
1622 *  
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);
1627 *  
1628 *   if (cell->at_boundary(face_no))
1629 *   saturation_boundary_values.value_list(
1630 *   fe_face_values.get_quadrature_points(), neighbor_saturation);
1631 *   else
1632 *   {
1633 *   const auto neighbor = cell->neighbor(face_no);
1634 *   const unsigned int neighbor_face =
1635 *   cell->neighbor_of_neighbor(face_no);
1636 *  
1637 *   fe_face_values_neighbor.reinit(neighbor, neighbor_face);
1638 *  
1639 *   fe_face_values_neighbor.get_function_values(
1640 *   old_solution, old_solution_values_face_neighbor);
1641 *  
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);
1645 *   }
1646 *  
1647 *  
1648 *   for (unsigned int q = 0; q < n_face_q_points; ++q)
1649 *   {
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);
1653 *  
1654 *   const double normal_flux =
1655 *   present_u_face * fe_face_values.normal_vector(q);
1656 *  
1657 *   const bool is_outflow_q_point = (normal_flux >= 0);
1658 *  
1659 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
1660 *   local_rhs(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]),
1665 *   viscosity) *
1666 *   fe_face_values[saturation].value(i, q) *
1667 *   fe_face_values.JxW(q);
1668 *   }
1669 *   }
1670 *  
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);
1674 *   }
1675 *   }
1676 *  
1677 *  
1678 *  
1679 * @endcode
1680 *
1681 *
1682 * <a name="step_21-TwoPhaseFlowProblemsolve"></a>
1683 * <h4>TwoPhaseFlowProblem::solve</h4>
1684 *
1685
1686 *
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):
1690 *
1691 * @code
1692 *   template <int dim>
1693 *   void TwoPhaseFlowProblem<dim>::solve()
1694 *   {
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());
1700 *  
1701 *  
1702 * @endcode
1703 *
1704 * First the pressure, using the pressure Schur complement of the first
1705 * two equations:
1706 *
1707 * @code
1708 *   {
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);
1712 *  
1713 *  
1714 *   SchurComplement schur_complement(system_matrix, m_inverse);
1715 *  
1716 *   ApproximateSchurComplement approximate_schur_complement(system_matrix);
1717 *  
1718 *   InverseMatrix<ApproximateSchurComplement> preconditioner(
1719 *   approximate_schur_complement);
1720 *  
1721 *  
1722 *   SolverControl solver_control(solution.block(1).size(),
1723 *   1e-12 * schur_rhs.l2_norm());
1724 *   SolverCG<Vector<double>> cg(solver_control);
1725 *  
1726 *   cg.solve(schur_complement, solution.block(1), schur_rhs, preconditioner);
1727 *  
1728 *   std::cout << " " << solver_control.last_step()
1729 *   << " CG Schur complement iterations for pressure." << std::endl;
1730 *   }
1731 *  
1732 * @endcode
1733 *
1734 * Now the velocity:
1735 *
1736 * @code
1737 *   {
1738 *   system_matrix.block(0, 1).vmult(tmp, solution.block(1));
1739 *   tmp *= -1;
1740 *   tmp += system_rhs.block(0);
1741 *  
1742 *   m_inverse.vmult(solution.block(0), tmp);
1743 *   }
1744 *  
1745 * @endcode
1746 *
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.
1755 *
1756
1757 *
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.
1767 *
1768 * @code
1769 *   time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) /
1770 *   get_maximal_velocity());
1771 *  
1772 * @endcode
1773 *
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:
1777 *
1778 * @code
1779 *   assemble_rhs_S();
1780 *   {
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());
1788 *  
1789 *   project_back_saturation();
1790 *  
1791 *   std::cout << " " << solver_control.last_step()
1792 *   << " CG iterations for saturation." << std::endl;
1793 *   }
1794 *  
1795 *  
1796 *   old_solution = solution;
1797 *   }
1798 *  
1799 *  
1800 * @endcode
1801 *
1802 *
1803 * <a name="step_21-TwoPhaseFlowProblemoutput_results"></a>
1804 * <h4>TwoPhaseFlowProblem::output_results</h4>
1805 *
1806
1807 *
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.
1811 *
1812
1813 *
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.
1819 *
1820 * @code
1821 *   template <int dim>
1822 *   void TwoPhaseFlowProblem<dim>::output_results() const
1823 *   {
1824 *   if (time.get_step_number() % 5 != 0)
1825 *   return;
1826 *  
1827 *   std::vector<std::string> solution_names;
1828 *   switch (dim)
1829 *   {
1830 *   case 2:
1831 *   solution_names = {"u", "v", "p", "S"};
1832 *   break;
1833 *  
1834 *   case 3:
1835 *   solution_names = {"u", "v", "w", "p", "S"};
1836 *   break;
1837 *  
1838 *   default:
1839 *   DEAL_II_NOT_IMPLEMENTED();
1840 *   }
1841 *  
1842 *   DataOut<dim> data_out;
1843 *  
1844 *   data_out.attach_dof_handler(dof_handler);
1845 *   data_out.add_data_vector(solution, solution_names);
1846 *  
1847 *   data_out.build_patches(degree + 1);
1848 *  
1849 *   std::ofstream output("solution-" +
1850 *   Utilities::int_to_string(time.get_step_number(), 4) +
1851 *   ".vtk");
1852 *   data_out.write_vtk(output);
1853 *   }
1854 *  
1855 *  
1856 *  
1857 * @endcode
1858 *
1859 *
1860 * <a name="step_21-TwoPhaseFlowProblemproject_back_saturation"></a>
1861 * <h4>TwoPhaseFlowProblem::project_back_saturation</h4>
1862 *
1863
1864 *
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
1870 * pressures).
1871 *
1872
1873 *
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.
1882 *
1883 * @code
1884 *   template <int dim>
1885 *   void TwoPhaseFlowProblem<dim>::project_back_saturation()
1886 *   {
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;
1892 *   }
1893 *  
1894 *  
1895 * @endcode
1896 *
1897 *
1898 * <a name="step_21-TwoPhaseFlowProblemget_maximal_velocity"></a>
1899 * <h4>TwoPhaseFlowProblem::get_maximal_velocity</h4>
1900 *
1901
1902 *
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.
1906 *
1907 * @code
1908 *   template <int dim>
1909 *   double TwoPhaseFlowProblem<dim>::get_maximal_velocity() const
1910 *   {
1911 *   const QGauss<dim> quadrature_formula(degree + 2);
1912 *   const unsigned int n_q_points = quadrature_formula.size();
1913 *  
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;
1918 *  
1919 *   for (const auto &cell : dof_handler.active_cell_iterators())
1920 *   {
1921 *   fe_values.reinit(cell);
1922 *   fe_values.get_function_values(solution, solution_values);
1923 *  
1924 *   for (unsigned int q = 0; q < n_q_points; ++q)
1925 *   {
1926 *   Tensor<1, dim> velocity;
1927 *   for (unsigned int i = 0; i < dim; ++i)
1928 *   velocity[i] = solution_values[q](i);
1929 *  
1930 *   max_velocity = std::max(max_velocity, velocity.norm());
1931 *   }
1932 *   }
1933 *  
1934 *   return max_velocity;
1935 *   }
1936 *  
1937 *  
1938 * @endcode
1939 *
1940 *
1941 * <a name="step_21-TwoPhaseFlowProblemrun"></a>
1942 * <h4>TwoPhaseFlowProblem::run</h4>
1943 *
1944
1945 *
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
1956 * why we can't simply call the VectorTools::project function with an
1957 * anonymous temporary object <code>AffineConstraints<double>()</code> as the
1958 * second argument.
1959 *
1960
1961 *
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.
1966 * We increment time by calling the method DiscreteTime::advance_time()
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.
1973 *
1974 * @code
1975 *   template <int dim>
1976 *   void TwoPhaseFlowProblem<dim>::run()
1977 *   {
1978 *   make_grid_and_dofs();
1979 *  
1980 *   {
1981 *   AffineConstraints<double> constraints;
1982 *   constraints.close();
1983 *  
1984 *   VectorTools::project(dof_handler,
1985 *   constraints,
1986 *   QGauss<dim>(degree + 2),
1987 *   InitialValues<dim>(),
1988 *   old_solution);
1989 *   }
1990 *  
1991 *   do
1992 *   {
1993 *   std::cout << "Timestep " << time.get_step_number() + 1 << std::endl;
1994 *  
1995 *   assemble_system();
1996 *  
1997 *   solve();
1998 *  
1999 *   output_results();
2000 *  
2001 *   time.advance_time();
2002 *   std::cout << " Now at t=" << time.get_current_time()
2003 *   << ", dt=" << time.get_previous_step_size() << '.'
2004 *   << std::endl
2005 *   << std::endl;
2006 *   }
2007 *   while (time.is_at_end() == false);
2008 *   }
2009 *   } // namespace Step21
2010 *  
2011 *  
2012 * @endcode
2013 *
2014 *
2015 * <a name="step_21-Thecodemaincodefunction"></a>
2016 * <h3>The <code>main</code> function</h3>
2017 *
2018
2019 *
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.
2024 *
2025 * @code
2026 *   int main()
2027 *   {
2028 *   try
2029 *   {
2030 *   using namespace Step21;
2031 *  
2032 *   TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2033 *   two_phase_flow_problem.run();
2034 *   }
2035 *   catch (std::exception &exc)
2036 *   {
2037 *   std::cerr << std::endl
2038 *   << std::endl
2039 *   << "----------------------------------------------------"
2040 *   << std::endl;
2041 *   std::cerr << "Exception on processing: " << std::endl
2042 *   << exc.what() << std::endl
2043 *   << "Aborting!" << std::endl
2044 *   << "----------------------------------------------------"
2045 *   << std::endl;
2046 *  
2047 *   return 1;
2048 *   }
2049 *   catch (...)
2050 *   {
2051 *   std::cerr << std::endl
2052 *   << std::endl
2053 *   << "----------------------------------------------------"
2054 *   << std::endl;
2055 *   std::cerr << "Unknown exception!" << std::endl
2056 *   << "Aborting!" << std::endl
2057 *   << "----------------------------------------------------"
2058 *   << std::endl;
2059 *   return 1;
2060 *   }
2061 *  
2062 *   return 0;
2063 *   }
2064 * @endcode
2065<a name="step_21-Results"></a><h1>Results</h1>
2066
2067
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.
2073
2074If we run the program, we get the following kind of output:
2075@code
2076Number of active cells: 1024
2077Number of degrees of freedom: 4160 (2112+1024+1024)
2078
2079Timestep 1
2080 22 CG Schur complement iterations for pressure.
2081 1 CG iterations for saturation.
2082 Now at t=0.0326742, dt=0.0326742.
2083
2084Timestep 2
2085 17 CG Schur complement iterations for pressure.
2086 1 CG iterations for saturation.
2087 Now at t=0.0653816, dt=0.0327074.
2088
2089Timestep 3
2090 17 CG Schur complement iterations for pressure.
2091 1 CG iterations for saturation.
2092 Now at t=0.0980651, dt=0.0326836.
2093
2094...
2095@endcode
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.
2100
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.
2112
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
2119CG iteration.
2120
2121
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:
2125
2126<img src="https://www.dealii.org/images/steps/developer/step-21.centerline.gif" alt="">
2127
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.
2133
2134
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
2138the next:
2139
2140<img src="https://www.dealii.org/images/steps/developer/step-21.random2d.gif" alt="">
2141
2142
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:
2146
2147<img src="https://www.dealii.org/images/steps/developer/step-21.random3d.gif" alt="">
2148
2149To repeat these computations, all you have to do is to change the line
2150@code
2151 TwoPhaseFlowProblem<2> two_phase_flow_problem(0);
2152@endcode
2153in the main function to
2154@code
2155 TwoPhaseFlowProblem<3> two_phase_flow_problem(0);
2156@endcode
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.
2163
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.
2175
2176
2177<a name="step-21-extensions"></a>
2178<a name="step_21-Possibilitiesforextensions"></a><h3>Possibilities for extensions</h3>
2179
2180
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".
2184
2185
2186<a name="step_21-Solvers"></a><h4>Solvers</h4>
2187
2188
2189At present, the program is not particularly fast: the 2d random medium
2190computation took about a day for the 1,000 or so time steps. The corresponding
21913d 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
2194never change.
2195
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.
2205
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
2214SparseMatrix object. We could then hand it off to the SparseMIC class to form
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
2218using the SparseDirectUMFPACK class that produces not only an incomplete, but
2219a complete decomposition of the matrix, which should yield an even better
2220preconditioner.
2221
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
2230mixed form.
2231
2232Using such techniques, it can reasonably be expected that the solution process
2233will be faster by at least an order of magnitude.
2234
2235
2236<a name="step_21-Timestepping"></a><h4>Time stepping</h4>
2237
2238
2239In the introduction we have identified the time step restriction
2240@f[
2241 \triangle t_{n+1} \le \frac h{|\mathbf{u}^{n+1}(\mathbf{x})|}
2242@f]
2243that has to hold globally, i.e. for all @f$\mathbf x@f$. After discretization, we
2244satisfy it by choosing
2245@f[
2246 \triangle t_{n+1} = \frac {\min_K h_K}{\max_{\mathbf{x}}|\mathbf{u}^{n+1}(\mathbf{x})|}.
2247@f]
2248
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.
2252
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.
2257
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&mdash;376. There are certainly many other papers on this topic as well, but
2268this one happened to land on our desk a while back.
2269
2270
2271
2272<a name="step_21-Adaptivity"></a><h4>Adaptivity</h4>
2273
2274
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
2280accuracy.
2281
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
2285it (something that the SolutionTransfer class can help with). These are not
2286insurmountable obstacles, but they do require some additional coding and more
2287than we felt comfortable was worth packing into this tutorial program.
2288 *
2289 *
2290<a name="step_21-PlainProg"></a>
2291<h1> The plain program</h1>
2292@include "step-21.cc"
2293*/
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:4624
Point< 2 > first
Definition grid_out.cc:4623
#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())
Definition loop.h:564
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)
@ 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)
VectorType::value_type * end(VectorType &V)
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 >()), const bool project_to_boundary_first=false)
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