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-32.h
Go to the documentation of this file.
1
1507 *   constexpr double kappa = 1e-6; /* m^2 / s */
1508 *   constexpr double reference_density = 3300; /* kg / m^3 */
1509 *   constexpr double reference_temperature = 293; /* K */
1510 *   constexpr double expansion_coefficient = 2e-5; /* 1/K */
1511 *   constexpr double specific_heat = 1250; /* J / K / kg */
1512 *   constexpr double radiogenic_heating = 7.4e-12; /* W / kg */
1513 *  
1514 *  
1515 *   constexpr double R0 = 6371000. - 2890000.; /* m */
1516 *   constexpr double R1 = 6371000. - 35000.; /* m */
1517 *  
1518 *   constexpr double T0 = 4000 + 273; /* K */
1519 *   constexpr double T1 = 700 + 273; /* K */
1520 *  
1521 *  
1522 * @endcode
1523 *
1524 * The next set of definitions are for functions that encode the density
1525 * as a function of temperature, the gravity vector, and the initial
1526 * values for the temperature. Again, all of these (along with the values
1527 * they compute) are discussed in the introduction:
1528 *
1529 * @code
1530 *   double density(const double temperature)
1531 *   {
1532 *   return (
1533 *   reference_density *
1534 *   (1 - expansion_coefficient * (temperature - reference_temperature)));
1535 *   }
1536 *  
1537 *  
1538 *   template <int dim>
1539 *   Tensor<1, dim> gravity_vector(const Point<dim> &p)
1540 *   {
1541 *   const double r = p.norm();
1542 *   return -(1.245e-6 * r + 7.714e13 / r / r) * p / r;
1543 *   }
1544 *  
1545 *  
1546 *  
1547 *   template <int dim>
1548 *   class TemperatureInitialValues : public Function<dim>
1549 *   {
1550 *   public:
1551 *   TemperatureInitialValues()
1552 *   : Function<dim>(1)
1553 *   {}
1554 *  
1555 *   virtual double value(const Point<dim> &p,
1556 *   const unsigned int component = 0) const override;
1557 *  
1558 *   virtual void vector_value(const Point<dim> &p,
1559 *   Vector<double> &value) const override;
1560 *   };
1561 *  
1562 *  
1563 *  
1564 *   template <int dim>
1565 *   double TemperatureInitialValues<dim>::value(const Point<dim> &p,
1566 *   const unsigned int) const
1567 *   {
1568 *   const double r = p.norm();
1569 *   const double h = R1 - R0;
1570 *  
1571 *   const double s = (r - R0) / h;
1572 *   const double q =
1573 *   (dim == 3) ? std::max(0.0, cos(numbers::PI * abs(p[2] / R1))) : 1.0;
1574 *   const double phi = std::atan2(p[0], p[1]);
1575 *   const double tau = s + 0.2 * s * (1 - s) * std::sin(6 * phi) * q;
1576 *  
1577 *   return T0 * (1.0 - tau) + T1 * tau;
1578 *   }
1579 *  
1580 *  
1581 *   template <int dim>
1582 *   void
1583 *   TemperatureInitialValues<dim>::vector_value(const Point<dim> &p,
1584 *   Vector<double> &values) const
1585 *   {
1586 *   for (unsigned int c = 0; c < this->n_components; ++c)
1587 *   values(c) = TemperatureInitialValues<dim>::value(p, c);
1588 *   }
1589 *  
1590 *  
1591 * @endcode
1592 *
1593 * As mentioned in the introduction we need to rescale the pressure to
1594 * avoid the relative ill-conditioning of the momentum and mass
1595 * conservation equations. The scaling factor is @f$\frac{\eta}{L}@f$ where
1596 * @f$L@f$ was a typical length scale. By experimenting it turns out that a
1597 * good length scale is the diameter of plumes, which is around 10 km:
1598 *
1599 * @code
1600 *   constexpr double pressure_scaling = eta / 10000;
1601 *  
1602 * @endcode
1603 *
1604 * The final number in this namespace is a constant that denotes the
1605 * number of seconds per (average, tropical) year. We use this only when
1606 * generating screen output: internally, all computations of this program
1607 * happen in SI units (kilogram, meter, seconds) but writing geological
1608 * times in seconds yields numbers that one can't relate to reality, and
1609 * so we convert to years using the factor defined here:
1610 *
1611 * @code
1612 *   const double year_in_seconds = 60 * 60 * 24 * 365.2425;
1613 *  
1614 *   } // namespace EquationData
1615 *  
1616 *  
1617 *  
1618 * @endcode
1619 *
1620 *
1621 * <a name="step_32-PreconditioningtheStokessystem"></a>
1622 * <h3>Preconditioning the Stokes system</h3>
1623 *
1624
1625 *
1626 * This namespace implements the preconditioner. As discussed in the
1627 * introduction, this preconditioner differs in a number of key portions
1628 * from the one used in @ref step_31 "step-31". Specifically, it is a right preconditioner,
1629 * implementing the matrix
1630 * @f{align*}{
1631 * \left(\begin{array}{cc}A^{-1} & -A^{-1}B^TS^{-1}
1632 * \\0 & S^{-1}
1633 * \end{array}\right)
1634 * @f}
1635 * where the two inverse matrix operations
1636 * are approximated by linear solvers or, if the right flag is given to the
1637 * constructor of this class, by a single AMG V-cycle for the velocity
1638 * block. The three code blocks of the <code>vmult</code> function implement
1639 * the multiplications with the three blocks of this preconditioner matrix
1640 * and should be self explanatory if you have read through @ref step_31 "step-31" or the
1641 * discussion of composing solvers in @ref step_20 "step-20".
1642 *
1643 * @code
1644 *   namespace LinearSolvers
1645 *   {
1646 *   template <class PreconditionerTypeA, class PreconditionerTypeMp>
1647 *   class BlockSchurPreconditioner : public Subscriptor
1648 *   {
1649 *   public:
1650 *   BlockSchurPreconditioner(const TrilinosWrappers::BlockSparseMatrix &S,
1651 *   const TrilinosWrappers::BlockSparseMatrix &Spre,
1652 *   const PreconditionerTypeMp &Mppreconditioner,
1653 *   const PreconditionerTypeA &Apreconditioner,
1654 *   const bool do_solve_A)
1655 *   : stokes_matrix(&S)
1656 *   , stokes_preconditioner_matrix(&Spre)
1657 *   , mp_preconditioner(Mppreconditioner)
1658 *   , a_preconditioner(Apreconditioner)
1659 *   , do_solve_A(do_solve_A)
1660 *   {}
1661 *  
1662 *   void vmult(TrilinosWrappers::MPI::BlockVector &dst,
1663 *   const TrilinosWrappers::MPI::BlockVector &src) const
1664 *   {
1665 *   TrilinosWrappers::MPI::Vector utmp(src.block(0));
1666 *  
1667 *   {
1668 *   SolverControl solver_control(5000, 1e-6 * src.block(1).l2_norm());
1669 *  
1670 *   SolverCG<TrilinosWrappers::MPI::Vector> solver(solver_control);
1671 *  
1672 *   solver.solve(stokes_preconditioner_matrix->block(1, 1),
1673 *   dst.block(1),
1674 *   src.block(1),
1675 *   mp_preconditioner);
1676 *  
1677 *   dst.block(1) *= -1.0;
1678 *   }
1679 *  
1680 *   {
1681 *   stokes_matrix->block(0, 1).vmult(utmp, dst.block(1));
1682 *   utmp *= -1.0;
1683 *   utmp.add(src.block(0));
1684 *   }
1685 *  
1686 *   if (do_solve_A == true)
1687 *   {
1688 *   SolverControl solver_control(5000, utmp.l2_norm() * 1e-2);
1689 *   TrilinosWrappers::SolverCG solver(solver_control);
1690 *   solver.solve(stokes_matrix->block(0, 0),
1691 *   dst.block(0),
1692 *   utmp,
1693 *   a_preconditioner);
1694 *   }
1695 *   else
1696 *   a_preconditioner.vmult(dst.block(0), utmp);
1697 *   }
1698 *  
1699 *   private:
1700 *   const SmartPointer<const TrilinosWrappers::BlockSparseMatrix>
1701 *   stokes_matrix;
1702 *   const SmartPointer<const TrilinosWrappers::BlockSparseMatrix>
1703 *   stokes_preconditioner_matrix;
1704 *   const PreconditionerTypeMp &mp_preconditioner;
1705 *   const PreconditionerTypeA &a_preconditioner;
1706 *   const bool do_solve_A;
1707 *   };
1708 *   } // namespace LinearSolvers
1709 *  
1710 *  
1711 *  
1712 * @endcode
1713 *
1714 *
1715 * <a name="step_32-Definitionofassemblydatastructures"></a>
1716 * <h3>Definition of assembly data structures</h3>
1717 *
1718
1719 *
1720 * As described in the introduction, we will use the WorkStream mechanism
1721 * discussed in the @ref threads topic to parallelize operations among the
1722 * processors of a single machine. The WorkStream class requires that data
1723 * is passed around in two kinds of data structures, one for scratch data
1724 * and one to pass data from the assembly function to the function that
1725 * copies local contributions into global objects.
1726 *
1727
1728 *
1729 * The following namespace (and the two sub-namespaces) contains a
1730 * collection of data structures that serve this purpose, one pair for each
1731 * of the four operations discussed in the introduction that we will want to
1732 * parallelize. Each assembly routine gets two sets of data: a Scratch array
1733 * that collects all the classes and arrays that are used for the
1734 * calculation of the cell contribution, and a CopyData array that keeps
1735 * local matrices and vectors which will be written into the global
1736 * matrix. Whereas CopyData is a container for the final data that is
1737 * written into the global matrices and vector (and, thus, absolutely
1738 * necessary), the Scratch arrays are merely there for performance reasons
1739 * &mdash; it would be much more expensive to set up a FEValues object on
1740 * each cell, than creating it only once and updating some derivative data.
1741 *
1742
1743 *
1744 * @ref step_31 "step-31" had four assembly routines: One for the preconditioner matrix of
1745 * the Stokes system, one for the Stokes matrix and right hand side, one for
1746 * the temperature matrices and one for the right hand side of the
1747 * temperature equation. We here organize the scratch arrays and CopyData
1748 * objects for each of those four assembly components using a
1749 * <code>struct</code> environment (since we consider these as temporary
1750 * objects we pass around, rather than classes that implement functionality
1751 * of their own, though this is a more subjective point of view to
1752 * distinguish between <code>struct</code>s and <code>class</code>es).
1753 *
1754
1755 *
1756 * Regarding the Scratch objects, each struct is equipped with a constructor
1757 * that creates an @ref FEValues object using the @ref FiniteElement,
1758 * Quadrature, @ref Mapping (which describes the interpolation of curved
1759 * boundaries), and @ref UpdateFlags instances. Moreover, we manually
1760 * implement a copy constructor (since the FEValues class is not copyable by
1761 * itself), and provide some additional vector fields that are used to hold
1762 * intermediate data during the computation of local contributions.
1763 *
1764
1765 *
1766 * Let us start with the scratch arrays and, specifically, the one used for
1767 * assembly of the Stokes preconditioner:
1768 *
1769 * @code
1770 *   namespace Assembly
1771 *   {
1772 *   namespace Scratch
1773 *   {
1774 *   template <int dim>
1775 *   struct StokesPreconditioner
1776 *   {
1777 *   StokesPreconditioner(const FiniteElement<dim> &stokes_fe,
1778 *   const Quadrature<dim> &stokes_quadrature,
1779 *   const Mapping<dim> &mapping,
1780 *   const UpdateFlags update_flags);
1781 *  
1782 *   StokesPreconditioner(const StokesPreconditioner &data);
1783 *  
1784 *  
1785 *   FEValues<dim> stokes_fe_values;
1786 *  
1787 *   std::vector<Tensor<2, dim>> grad_phi_u;
1788 *   std::vector<double> phi_p;
1789 *   };
1790 *  
1791 *   template <int dim>
1792 *   StokesPreconditioner<dim>::StokesPreconditioner(
1793 *   const FiniteElement<dim> &stokes_fe,
1794 *   const Quadrature<dim> &stokes_quadrature,
1795 *   const Mapping<dim> &mapping,
1796 *   const UpdateFlags update_flags)
1797 *   : stokes_fe_values(mapping, stokes_fe, stokes_quadrature, update_flags)
1798 *   , grad_phi_u(stokes_fe.n_dofs_per_cell())
1799 *   , phi_p(stokes_fe.n_dofs_per_cell())
1800 *   {}
1801 *  
1802 *  
1803 *  
1804 *   template <int dim>
1805 *   StokesPreconditioner<dim>::StokesPreconditioner(
1806 *   const StokesPreconditioner &scratch)
1807 *   : stokes_fe_values(scratch.stokes_fe_values.get_mapping(),
1808 *   scratch.stokes_fe_values.get_fe(),
1809 *   scratch.stokes_fe_values.get_quadrature(),
1810 *   scratch.stokes_fe_values.get_update_flags())
1811 *   , grad_phi_u(scratch.grad_phi_u)
1812 *   , phi_p(scratch.phi_p)
1813 *   {}
1814 *  
1815 *  
1816 *  
1817 * @endcode
1818 *
1819 * The next one is the scratch object used for the assembly of the full
1820 * Stokes system. Observe that we derive the StokesSystem scratch class
1821 * from the StokesPreconditioner class above. We do this because all the
1822 * objects that are necessary for the assembly of the preconditioner are
1823 * also needed for the actual matrix system and right hand side, plus
1824 * some extra data. This makes the program more compact. Note also that
1825 * the assembly of the Stokes system and the temperature right hand side
1826 * further down requires data from temperature and velocity,
1827 * respectively, so we actually need two FEValues objects for those two
1828 * cases.
1829 *
1830 * @code
1831 *   template <int dim>
1832 *   struct StokesSystem : public StokesPreconditioner<dim>
1833 *   {
1834 *   StokesSystem(const FiniteElement<dim> &stokes_fe,
1835 *   const Mapping<dim> &mapping,
1836 *   const Quadrature<dim> &stokes_quadrature,
1837 *   const UpdateFlags stokes_update_flags,
1838 *   const FiniteElement<dim> &temperature_fe,
1839 *   const UpdateFlags temperature_update_flags);
1840 *  
1841 *   StokesSystem(const StokesSystem<dim> &data);
1842 *  
1843 *  
1844 *   FEValues<dim> temperature_fe_values;
1845 *  
1846 *   std::vector<Tensor<1, dim>> phi_u;
1847 *   std::vector<SymmetricTensor<2, dim>> grads_phi_u;
1848 *   std::vector<double> div_phi_u;
1849 *  
1850 *   std::vector<double> old_temperature_values;
1851 *   };
1852 *  
1853 *  
1854 *   template <int dim>
1855 *   StokesSystem<dim>::StokesSystem(
1856 *   const FiniteElement<dim> &stokes_fe,
1857 *   const Mapping<dim> &mapping,
1858 *   const Quadrature<dim> &stokes_quadrature,
1859 *   const UpdateFlags stokes_update_flags,
1860 *   const FiniteElement<dim> &temperature_fe,
1861 *   const UpdateFlags temperature_update_flags)
1862 *   : StokesPreconditioner<dim>(stokes_fe,
1863 *   stokes_quadrature,
1864 *   mapping,
1865 *   stokes_update_flags)
1866 *   , temperature_fe_values(mapping,
1867 *   temperature_fe,
1868 *   stokes_quadrature,
1869 *   temperature_update_flags)
1870 *   , phi_u(stokes_fe.n_dofs_per_cell())
1871 *   , grads_phi_u(stokes_fe.n_dofs_per_cell())
1872 *   , div_phi_u(stokes_fe.n_dofs_per_cell())
1873 *   , old_temperature_values(stokes_quadrature.size())
1874 *   {}
1875 *  
1876 *  
1877 *   template <int dim>
1878 *   StokesSystem<dim>::StokesSystem(const StokesSystem<dim> &scratch)
1879 *   : StokesPreconditioner<dim>(scratch)
1880 *   , temperature_fe_values(
1881 *   scratch.temperature_fe_values.get_mapping(),
1882 *   scratch.temperature_fe_values.get_fe(),
1883 *   scratch.temperature_fe_values.get_quadrature(),
1884 *   scratch.temperature_fe_values.get_update_flags())
1885 *   , phi_u(scratch.phi_u)
1886 *   , grads_phi_u(scratch.grads_phi_u)
1887 *   , div_phi_u(scratch.div_phi_u)
1888 *   , old_temperature_values(scratch.old_temperature_values)
1889 *   {}
1890 *  
1891 *  
1892 * @endcode
1893 *
1894 * After defining the objects used in the assembly of the Stokes system,
1895 * we do the same for the assembly of the matrices necessary for the
1896 * temperature system. The general structure is very similar:
1897 *
1898 * @code
1899 *   template <int dim>
1900 *   struct TemperatureMatrix
1901 *   {
1902 *   TemperatureMatrix(const FiniteElement<dim> &temperature_fe,
1903 *   const Mapping<dim> &mapping,
1904 *   const Quadrature<dim> &temperature_quadrature);
1905 *  
1906 *   TemperatureMatrix(const TemperatureMatrix &data);
1907 *  
1908 *  
1909 *   FEValues<dim> temperature_fe_values;
1910 *  
1911 *   std::vector<double> phi_T;
1912 *   std::vector<Tensor<1, dim>> grad_phi_T;
1913 *   };
1914 *  
1915 *  
1916 *   template <int dim>
1917 *   TemperatureMatrix<dim>::TemperatureMatrix(
1918 *   const FiniteElement<dim> &temperature_fe,
1919 *   const Mapping<dim> &mapping,
1920 *   const Quadrature<dim> &temperature_quadrature)
1921 *   : temperature_fe_values(mapping,
1922 *   temperature_fe,
1923 *   temperature_quadrature,
1924 *   update_values | update_gradients |
1925 *   update_JxW_values)
1926 *   , phi_T(temperature_fe.n_dofs_per_cell())
1927 *   , grad_phi_T(temperature_fe.n_dofs_per_cell())
1928 *   {}
1929 *  
1930 *  
1931 *   template <int dim>
1932 *   TemperatureMatrix<dim>::TemperatureMatrix(
1933 *   const TemperatureMatrix &scratch)
1934 *   : temperature_fe_values(
1935 *   scratch.temperature_fe_values.get_mapping(),
1936 *   scratch.temperature_fe_values.get_fe(),
1937 *   scratch.temperature_fe_values.get_quadrature(),
1938 *   scratch.temperature_fe_values.get_update_flags())
1939 *   , phi_T(scratch.phi_T)
1940 *   , grad_phi_T(scratch.grad_phi_T)
1941 *   {}
1942 *  
1943 *  
1944 * @endcode
1945 *
1946 * The final scratch object is used in the assembly of the right hand
1947 * side of the temperature system. This object is significantly larger
1948 * than the ones above because a lot more quantities enter the
1949 * computation of the right hand side of the temperature equation. In
1950 * particular, the temperature values and gradients of the previous two
1951 * time steps need to be evaluated at the quadrature points, as well as
1952 * the velocities and the strain rates (i.e. the symmetric gradients of
1953 * the velocity) that enter the right hand side as friction heating
1954 * terms. Despite the number of terms, the following should be rather
1955 * self explanatory:
1956 *
1957 * @code
1958 *   template <int dim>
1959 *   struct TemperatureRHS
1960 *   {
1961 *   TemperatureRHS(const FiniteElement<dim> &temperature_fe,
1962 *   const FiniteElement<dim> &stokes_fe,
1963 *   const Mapping<dim> &mapping,
1964 *   const Quadrature<dim> &quadrature);
1965 *  
1966 *   TemperatureRHS(const TemperatureRHS &data);
1967 *  
1968 *  
1969 *   FEValues<dim> temperature_fe_values;
1970 *   FEValues<dim> stokes_fe_values;
1971 *  
1972 *   std::vector<double> phi_T;
1973 *   std::vector<Tensor<1, dim>> grad_phi_T;
1974 *  
1975 *   std::vector<Tensor<1, dim>> old_velocity_values;
1976 *   std::vector<Tensor<1, dim>> old_old_velocity_values;
1977 *  
1978 *   std::vector<SymmetricTensor<2, dim>> old_strain_rates;
1979 *   std::vector<SymmetricTensor<2, dim>> old_old_strain_rates;
1980 *  
1981 *   std::vector<double> old_temperature_values;
1982 *   std::vector<double> old_old_temperature_values;
1983 *   std::vector<Tensor<1, dim>> old_temperature_grads;
1984 *   std::vector<Tensor<1, dim>> old_old_temperature_grads;
1985 *   std::vector<double> old_temperature_laplacians;
1986 *   std::vector<double> old_old_temperature_laplacians;
1987 *   };
1988 *  
1989 *  
1990 *   template <int dim>
1991 *   TemperatureRHS<dim>::TemperatureRHS(
1992 *   const FiniteElement<dim> &temperature_fe,
1993 *   const FiniteElement<dim> &stokes_fe,
1994 *   const Mapping<dim> &mapping,
1995 *   const Quadrature<dim> &quadrature)
1996 *   : temperature_fe_values(mapping,
1997 *   temperature_fe,
1998 *   quadrature,
1999 *   update_values | update_gradients |
2000 *   update_hessians | update_quadrature_points |
2001 *   update_JxW_values)
2002 *   , stokes_fe_values(mapping,
2003 *   stokes_fe,
2004 *   quadrature,
2005 *   update_values | update_gradients)
2006 *   , phi_T(temperature_fe.n_dofs_per_cell())
2007 *   , grad_phi_T(temperature_fe.n_dofs_per_cell())
2008 *   ,
2009 *  
2010 *   old_velocity_values(quadrature.size())
2011 *   , old_old_velocity_values(quadrature.size())
2012 *   , old_strain_rates(quadrature.size())
2013 *   , old_old_strain_rates(quadrature.size())
2014 *   ,
2015 *  
2016 *   old_temperature_values(quadrature.size())
2017 *   , old_old_temperature_values(quadrature.size())
2018 *   , old_temperature_grads(quadrature.size())
2019 *   , old_old_temperature_grads(quadrature.size())
2020 *   , old_temperature_laplacians(quadrature.size())
2021 *   , old_old_temperature_laplacians(quadrature.size())
2022 *   {}
2023 *  
2024 *  
2025 *   template <int dim>
2026 *   TemperatureRHS<dim>::TemperatureRHS(const TemperatureRHS &scratch)
2027 *   : temperature_fe_values(
2028 *   scratch.temperature_fe_values.get_mapping(),
2029 *   scratch.temperature_fe_values.get_fe(),
2030 *   scratch.temperature_fe_values.get_quadrature(),
2031 *   scratch.temperature_fe_values.get_update_flags())
2032 *   , stokes_fe_values(scratch.stokes_fe_values.get_mapping(),
2033 *   scratch.stokes_fe_values.get_fe(),
2034 *   scratch.stokes_fe_values.get_quadrature(),
2035 *   scratch.stokes_fe_values.get_update_flags())
2036 *   , phi_T(scratch.phi_T)
2037 *   , grad_phi_T(scratch.grad_phi_T)
2038 *   ,
2039 *  
2040 *   old_velocity_values(scratch.old_velocity_values)
2041 *   , old_old_velocity_values(scratch.old_old_velocity_values)
2042 *   , old_strain_rates(scratch.old_strain_rates)
2043 *   , old_old_strain_rates(scratch.old_old_strain_rates)
2044 *   ,
2045 *  
2046 *   old_temperature_values(scratch.old_temperature_values)
2047 *   , old_old_temperature_values(scratch.old_old_temperature_values)
2048 *   , old_temperature_grads(scratch.old_temperature_grads)
2049 *   , old_old_temperature_grads(scratch.old_old_temperature_grads)
2050 *   , old_temperature_laplacians(scratch.old_temperature_laplacians)
2051 *   , old_old_temperature_laplacians(scratch.old_old_temperature_laplacians)
2052 *   {}
2053 *   } // namespace Scratch
2054 *  
2055 *  
2056 * @endcode
2057 *
2058 * The CopyData objects are even simpler than the Scratch objects as all
2059 * they have to do is to store the results of local computations until
2060 * they can be copied into the global matrix or vector objects. These
2061 * structures therefore only need to provide a constructor, a copy
2062 * operation, and some arrays for local matrix, local vectors and the
2063 * relation between local and global degrees of freedom (a.k.a.
2064 * <code>local_dof_indices</code>). Again, we have one such structure for
2065 * each of the four operations we will parallelize using the WorkStream
2066 * class:
2067 *
2068 * @code
2069 *   namespace CopyData
2070 *   {
2071 *   template <int dim>
2072 *   struct StokesPreconditioner
2073 *   {
2074 *   StokesPreconditioner(const FiniteElement<dim> &stokes_fe);
2075 *   StokesPreconditioner(const StokesPreconditioner &data);
2076 *   StokesPreconditioner &operator=(const StokesPreconditioner &) = default;
2077 *  
2078 *   FullMatrix<double> local_matrix;
2079 *   std::vector<types::global_dof_index> local_dof_indices;
2080 *   };
2081 *  
2082 *   template <int dim>
2083 *   StokesPreconditioner<dim>::StokesPreconditioner(
2084 *   const FiniteElement<dim> &stokes_fe)
2085 *   : local_matrix(stokes_fe.n_dofs_per_cell(), stokes_fe.n_dofs_per_cell())
2086 *   , local_dof_indices(stokes_fe.n_dofs_per_cell())
2087 *   {}
2088 *  
2089 *   template <int dim>
2090 *   StokesPreconditioner<dim>::StokesPreconditioner(
2091 *   const StokesPreconditioner &data)
2092 *   : local_matrix(data.local_matrix)
2093 *   , local_dof_indices(data.local_dof_indices)
2094 *   {}
2095 *  
2096 *  
2097 *  
2098 *   template <int dim>
2099 *   struct StokesSystem : public StokesPreconditioner<dim>
2100 *   {
2101 *   StokesSystem(const FiniteElement<dim> &stokes_fe);
2102 *  
2103 *   Vector<double> local_rhs;
2104 *   };
2105 *  
2106 *   template <int dim>
2107 *   StokesSystem<dim>::StokesSystem(const FiniteElement<dim> &stokes_fe)
2108 *   : StokesPreconditioner<dim>(stokes_fe)
2109 *   , local_rhs(stokes_fe.n_dofs_per_cell())
2110 *   {}
2111 *  
2112 *  
2113 *  
2114 *   template <int dim>
2115 *   struct TemperatureMatrix
2116 *   {
2117 *   TemperatureMatrix(const FiniteElement<dim> &temperature_fe);
2118 *  
2119 *   FullMatrix<double> local_mass_matrix;
2120 *   FullMatrix<double> local_stiffness_matrix;
2121 *   std::vector<types::global_dof_index> local_dof_indices;
2122 *   };
2123 *  
2124 *   template <int dim>
2125 *   TemperatureMatrix<dim>::TemperatureMatrix(
2126 *   const FiniteElement<dim> &temperature_fe)
2127 *   : local_mass_matrix(temperature_fe.n_dofs_per_cell(),
2128 *   temperature_fe.n_dofs_per_cell())
2129 *   , local_stiffness_matrix(temperature_fe.n_dofs_per_cell(),
2130 *   temperature_fe.n_dofs_per_cell())
2131 *   , local_dof_indices(temperature_fe.n_dofs_per_cell())
2132 *   {}
2133 *  
2134 *  
2135 *  
2136 *   template <int dim>
2137 *   struct TemperatureRHS
2138 *   {
2139 *   TemperatureRHS(const FiniteElement<dim> &temperature_fe);
2140 *  
2141 *   Vector<double> local_rhs;
2142 *   std::vector<types::global_dof_index> local_dof_indices;
2143 *   FullMatrix<double> matrix_for_bc;
2144 *   };
2145 *  
2146 *   template <int dim>
2147 *   TemperatureRHS<dim>::TemperatureRHS(
2148 *   const FiniteElement<dim> &temperature_fe)
2149 *   : local_rhs(temperature_fe.n_dofs_per_cell())
2150 *   , local_dof_indices(temperature_fe.n_dofs_per_cell())
2151 *   , matrix_for_bc(temperature_fe.n_dofs_per_cell(),
2152 *   temperature_fe.n_dofs_per_cell())
2153 *   {}
2154 *   } // namespace CopyData
2155 *   } // namespace Assembly
2156 *  
2157 *  
2158 *  
2159 * @endcode
2160 *
2161 *
2162 * <a name="step_32-ThecodeBoussinesqFlowProblemcodeclasstemplate"></a>
2163 * <h3>The <code>BoussinesqFlowProblem</code> class template</h3>
2164 *
2165
2166 *
2167 * This is the declaration of the main class. It is very similar to @ref step_31 "step-31"
2168 * but there are a number differences we will comment on below.
2169 *
2170
2171 *
2172 * The top of the class is essentially the same as in @ref step_31 "step-31", listing the
2173 * public methods and a set of private functions that do the heavy
2174 * lifting. Compared to @ref step_31 "step-31" there are only two additions to this
2175 * section: the function <code>get_cfl_number()</code> that computes the
2176 * maximum CFL number over all cells which we then compute the global time
2177 * step from, and the function <code>get_entropy_variation()</code> that is
2178 * used in the computation of the entropy stabilization. It is akin to the
2179 * <code>get_extrapolated_temperature_range()</code> we have used in @ref step_31 "step-31"
2180 * for this purpose, but works on the entropy instead of the temperature
2181 * instead.
2182 *
2183 * @code
2184 *   template <int dim>
2185 *   class BoussinesqFlowProblem
2186 *   {
2187 *   public:
2188 *   struct Parameters;
2189 *   BoussinesqFlowProblem(Parameters &parameters);
2190 *   void run();
2191 *  
2192 *   private:
2193 *   void setup_dofs();
2194 *   void assemble_stokes_preconditioner();
2195 *   void build_stokes_preconditioner();
2196 *   void assemble_stokes_system();
2197 *   void assemble_temperature_matrix();
2198 *   void assemble_temperature_system(const double maximal_velocity);
2199 *   double get_maximal_velocity() const;
2200 *   double get_cfl_number() const;
2201 *   double get_entropy_variation(const double average_temperature) const;
2202 *   std::pair<double, double> get_extrapolated_temperature_range() const;
2203 *   void solve();
2204 *   void output_results();
2205 *   void refine_mesh(const unsigned int max_grid_level);
2206 *  
2207 *   double compute_viscosity(
2208 *   const std::vector<double> &old_temperature,
2209 *   const std::vector<double> &old_old_temperature,
2210 *   const std::vector<Tensor<1, dim>> &old_temperature_grads,
2211 *   const std::vector<Tensor<1, dim>> &old_old_temperature_grads,
2212 *   const std::vector<double> &old_temperature_laplacians,
2213 *   const std::vector<double> &old_old_temperature_laplacians,
2214 *   const std::vector<Tensor<1, dim>> &old_velocity_values,
2215 *   const std::vector<Tensor<1, dim>> &old_old_velocity_values,
2216 *   const std::vector<SymmetricTensor<2, dim>> &old_strain_rates,
2217 *   const std::vector<SymmetricTensor<2, dim>> &old_old_strain_rates,
2218 *   const double global_u_infty,
2219 *   const double global_T_variation,
2220 *   const double average_temperature,
2221 *   const double global_entropy_variation,
2222 *   const double cell_diameter) const;
2223 *  
2224 *   public:
2225 * @endcode
2226 *
2227 * The first significant new component is the definition of a struct for
2228 * the parameters according to the discussion in the introduction. This
2229 * structure is initialized by reading from a parameter file during
2230 * construction of this object.
2231 *
2232 * @code
2233 *   struct Parameters
2234 *   {
2235 *   Parameters(const std::string &parameter_filename);
2236 *  
2237 *   static void declare_parameters(ParameterHandler &prm);
2238 *   void parse_parameters(ParameterHandler &prm);
2239 *  
2240 *   double end_time;
2241 *  
2242 *   unsigned int initial_global_refinement;
2243 *   unsigned int initial_adaptive_refinement;
2244 *  
2245 *   bool generate_graphical_output;
2246 *   unsigned int graphical_output_interval;
2247 *  
2248 *   unsigned int adaptive_refinement_interval;
2249 *  
2250 *   double stabilization_alpha;
2251 *   double stabilization_c_R;
2252 *   double stabilization_beta;
2253 *  
2254 *   unsigned int stokes_velocity_degree;
2255 *   bool use_locally_conservative_discretization;
2256 *  
2257 *   unsigned int temperature_degree;
2258 *   };
2259 *  
2260 *   private:
2261 *   Parameters &parameters;
2262 *  
2263 * @endcode
2264 *
2265 * The <code>pcout</code> (for <i>%parallel <code>std::cout</code></i>)
2266 * object is used to simplify writing output: each MPI process can use
2267 * this to generate output as usual, but since each of these processes
2268 * will (hopefully) produce the same output it will just be replicated
2269 * many times over; with the ConditionalOStream class, only the output
2270 * generated by one MPI process will actually be printed to screen,
2271 * whereas the output by all the other threads will simply be forgotten.
2272 *
2273 * @code
2274 *   ConditionalOStream pcout;
2275 *  
2276 * @endcode
2277 *
2278 * The following member variables will then again be similar to those in
2279 * @ref step_31 "step-31" (and to other tutorial programs). As mentioned in the
2280 * introduction, we fully distribute computations, so we will have to use
2281 * the parallel::distributed::Triangulation class (see @ref step_40 "step-40") but the
2282 * remainder of these variables is rather standard with two exceptions:
2283 *
2284
2285 *
2286 * - The <code>mapping</code> variable is used to denote a higher-order
2287 * polynomial mapping. As mentioned in the introduction, we use this
2288 * mapping when forming integrals through quadrature for all cells.
2289 *
2290
2291 *
2292 * - In a bit of naming confusion, you will notice below that some of the
2293 * variables from namespace TrilinosWrappers are taken from namespace
2294 * TrilinosWrappers::MPI (such as the right hand side vectors) whereas
2295 * others are not (such as the various matrices). This is due to legacy
2296 * reasons. We will frequently have to query velocities
2297 * and temperatures at arbitrary quadrature points; consequently, rather
2298 * than importing ghost information of a vector whenever we need access
2299 * to degrees of freedom that are relevant locally but owned by another
2300 * processor, we solve linear systems in %parallel but then immediately
2301 * initialize a vector including ghost entries of the solution for further
2302 * processing. The various <code>*_solution</code> vectors are therefore
2303 * filled immediately after solving their respective linear system in
2304 * %parallel and will always contain values for all
2305 * @ref GlossLocallyRelevantDof "locally relevant degrees of freedom";
2306 * the fully distributed vectors that we obtain from the solution process
2307 * and that only ever contain the
2308 * @ref GlossLocallyOwnedDof "locally owned degrees of freedom" are
2309 * destroyed immediately after the solution process and after we have
2310 * copied the relevant values into the member variable vectors.
2311 *
2312 * @code
2313 *   parallel::distributed::Triangulation<dim> triangulation;
2314 *   double global_Omega_diameter;
2315 *  
2316 *   const MappingQ<dim> mapping;
2317 *  
2318 *   const FESystem<dim> stokes_fe;
2319 *   DoFHandler<dim> stokes_dof_handler;
2320 *   AffineConstraints<double> stokes_constraints;
2321 *  
2322 *   TrilinosWrappers::BlockSparseMatrix stokes_matrix;
2323 *   TrilinosWrappers::BlockSparseMatrix stokes_preconditioner_matrix;
2324 *  
2325 *   TrilinosWrappers::MPI::BlockVector stokes_solution;
2326 *   TrilinosWrappers::MPI::BlockVector old_stokes_solution;
2327 *   TrilinosWrappers::MPI::BlockVector stokes_rhs;
2328 *  
2329 *  
2330 *   const FE_Q<dim> temperature_fe;
2331 *   DoFHandler<dim> temperature_dof_handler;
2332 *   AffineConstraints<double> temperature_constraints;
2333 *  
2334 *   TrilinosWrappers::SparseMatrix temperature_mass_matrix;
2335 *   TrilinosWrappers::SparseMatrix temperature_stiffness_matrix;
2336 *   TrilinosWrappers::SparseMatrix temperature_matrix;
2337 *  
2338 *   TrilinosWrappers::MPI::Vector temperature_solution;
2339 *   TrilinosWrappers::MPI::Vector old_temperature_solution;
2340 *   TrilinosWrappers::MPI::Vector old_old_temperature_solution;
2341 *   TrilinosWrappers::MPI::Vector temperature_rhs;
2342 *  
2343 *  
2344 *   double time_step;
2345 *   double old_time_step;
2346 *   unsigned int timestep_number;
2347 *  
2348 *   std::shared_ptr<TrilinosWrappers::PreconditionAMG> Amg_preconditioner;
2349 *   std::shared_ptr<TrilinosWrappers::PreconditionJacobi> Mp_preconditioner;
2350 *   std::shared_ptr<TrilinosWrappers::PreconditionJacobi> T_preconditioner;
2351 *  
2352 *   bool rebuild_stokes_matrix;
2353 *   bool rebuild_stokes_preconditioner;
2354 *   bool rebuild_temperature_matrices;
2355 *   bool rebuild_temperature_preconditioner;
2356 *  
2357 * @endcode
2358 *
2359 * The next member variable, <code>computing_timer</code> is used to
2360 * conveniently account for compute time spent in certain "sections" of
2361 * the code that are repeatedly entered. For example, we will enter (and
2362 * leave) sections for Stokes matrix assembly and would like to accumulate
2363 * the run time spent in this section over all time steps. Every so many
2364 * time steps as well as at the end of the program (through the destructor
2365 * of the TimerOutput class) we will then produce a nice summary of the
2366 * times spent in the different sections into which we categorize the
2367 * run-time of this program.
2368 *
2369 * @code
2370 *   TimerOutput computing_timer;
2371 *  
2372 * @endcode
2373 *
2374 * After these member variables we have a number of auxiliary functions
2375 * that have been broken out of the ones listed above. Specifically, there
2376 * are first three functions that we call from <code>setup_dofs</code> and
2377 * then the ones that do the assembling of linear systems:
2378 *
2379 * @code
2380 *   void setup_stokes_matrix(
2381 *   const std::vector<IndexSet> &stokes_partitioning,
2382 *   const std::vector<IndexSet> &stokes_relevant_partitioning);
2383 *   void setup_stokes_preconditioner(
2384 *   const std::vector<IndexSet> &stokes_partitioning,
2385 *   const std::vector<IndexSet> &stokes_relevant_partitioning);
2386 *   void setup_temperature_matrices(
2387 *   const IndexSet &temperature_partitioning,
2388 *   const IndexSet &temperature_relevant_partitioning);
2389 *  
2390 *  
2391 * @endcode
2392 *
2393 * Following the @ref MTWorkStream "task-based parallelization" paradigm,
2394 * we split all the assembly routines into two parts: a first part that
2395 * can do all the calculations on a certain cell without taking care of
2396 * other threads, and a second part (which is writing the local data into
2397 * the global matrices and vectors) which can be entered by only one
2398 * thread at a time. In order to implement that, we provide functions for
2399 * each of those two steps for all the four assembly routines that we use
2400 * in this program. The following eight functions do exactly this:
2401 *
2402 * @code
2403 *   void local_assemble_stokes_preconditioner(
2404 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
2405 *   Assembly::Scratch::StokesPreconditioner<dim> &scratch,
2406 *   Assembly::CopyData::StokesPreconditioner<dim> &data);
2407 *  
2408 *   void copy_local_to_global_stokes_preconditioner(
2409 *   const Assembly::CopyData::StokesPreconditioner<dim> &data);
2410 *  
2411 *  
2412 *   void local_assemble_stokes_system(
2413 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
2414 *   Assembly::Scratch::StokesSystem<dim> &scratch,
2415 *   Assembly::CopyData::StokesSystem<dim> &data);
2416 *  
2417 *   void copy_local_to_global_stokes_system(
2418 *   const Assembly::CopyData::StokesSystem<dim> &data);
2419 *  
2420 *  
2421 *   void local_assemble_temperature_matrix(
2422 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
2423 *   Assembly::Scratch::TemperatureMatrix<dim> &scratch,
2424 *   Assembly::CopyData::TemperatureMatrix<dim> &data);
2425 *  
2426 *   void copy_local_to_global_temperature_matrix(
2427 *   const Assembly::CopyData::TemperatureMatrix<dim> &data);
2428 *  
2429 *  
2430 *  
2431 *   void local_assemble_temperature_rhs(
2432 *   const std::pair<double, double> global_T_range,
2433 *   const double global_max_velocity,
2434 *   const double global_entropy_variation,
2435 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
2436 *   Assembly::Scratch::TemperatureRHS<dim> &scratch,
2437 *   Assembly::CopyData::TemperatureRHS<dim> &data);
2438 *  
2439 *   void copy_local_to_global_temperature_rhs(
2440 *   const Assembly::CopyData::TemperatureRHS<dim> &data);
2441 *  
2442 * @endcode
2443 *
2444 * Finally, we forward declare a member class that we will define later on
2445 * and that will be used to compute a number of quantities from our
2446 * solution vectors that we'd like to put into the output files for
2447 * visualization.
2448 *
2449 * @code
2450 *   class Postprocessor;
2451 *   };
2452 *  
2453 *  
2454 * @endcode
2455 *
2456 *
2457 * <a name="step_32-BoussinesqFlowProblemclassimplementation"></a>
2458 * <h3>BoussinesqFlowProblem class implementation</h3>
2459 *
2460
2461 *
2462 *
2463 * <a name="step_32-BoussinesqFlowProblemParameters"></a>
2464 * <h4>BoussinesqFlowProblem::Parameters</h4>
2465 *
2466
2467 *
2468 * Here comes the definition of the parameters for the Stokes problem. We
2469 * allow to set the end time for the simulation, the level of refinements
2470 * (both global and adaptive, which in the sum specify what maximum level
2471 * the cells are allowed to have), and the interval between refinements in
2472 * the time stepping.
2473 *
2474
2475 *
2476 * Then, we let the user specify constants for the stabilization parameters
2477 * (as discussed in the introduction), the polynomial degree for the Stokes
2478 * velocity space, whether to use the locally conservative discretization
2479 * based on FE_DGP elements for the pressure or not (FE_Q elements for
2480 * pressure), and the polynomial degree for the temperature interpolation.
2481 *
2482
2483 *
2484 * The constructor checks for a valid input file (if not, a file with
2485 * default parameters for the quantities is written), and eventually parses
2486 * the parameters.
2487 *
2488 * @code
2489 *   template <int dim>
2490 *   BoussinesqFlowProblem<dim>::Parameters::Parameters(
2491 *   const std::string &parameter_filename)
2492 *   : end_time(1e8)
2493 *   , initial_global_refinement(2)
2494 *   , initial_adaptive_refinement(2)
2495 *   , adaptive_refinement_interval(10)
2496 *   , stabilization_alpha(2)
2497 *   , stabilization_c_R(0.11)
2498 *   , stabilization_beta(0.078)
2499 *   , stokes_velocity_degree(2)
2500 *   , use_locally_conservative_discretization(true)
2501 *   , temperature_degree(2)
2502 *   {
2503 *   ParameterHandler prm;
2504 *   BoussinesqFlowProblem<dim>::Parameters::declare_parameters(prm);
2505 *  
2506 *   std::ifstream parameter_file(parameter_filename);
2507 *  
2508 *   if (!parameter_file)
2509 *   {
2510 *   parameter_file.close();
2511 *  
2512 *   std::ofstream parameter_out(parameter_filename);
2513 *   prm.print_parameters(parameter_out, ParameterHandler::PRM);
2514 *  
2515 *   AssertThrow(
2516 *   false,
2517 *   ExcMessage(
2518 *   "Input parameter file <" + parameter_filename +
2519 *   "> not found. Creating a template file of the same name."));
2520 *   }
2521 *  
2522 *   prm.parse_input(parameter_file);
2523 *   parse_parameters(prm);
2524 *   }
2525 *  
2526 *  
2527 *  
2528 * @endcode
2529 *
2530 * Next we have a function that declares the parameters that we expect in
2531 * the input file, together with their data types, default values and a
2532 * description:
2533 *
2534 * @code
2535 *   template <int dim>
2536 *   void BoussinesqFlowProblem<dim>::Parameters::declare_parameters(
2537 *   ParameterHandler &prm)
2538 *   {
2539 *   prm.declare_entry("End time",
2540 *   "1e8",
2541 *   Patterns::Double(0),
2542 *   "The end time of the simulation in years.");
2543 *   prm.declare_entry("Initial global refinement",
2544 *   "2",
2545 *   Patterns::Integer(0),
2546 *   "The number of global refinement steps performed on "
2547 *   "the initial coarse mesh, before the problem is first "
2548 *   "solved there.");
2549 *   prm.declare_entry("Initial adaptive refinement",
2550 *   "2",
2551 *   Patterns::Integer(0),
2552 *   "The number of adaptive refinement steps performed after "
2553 *   "initial global refinement.");
2554 *   prm.declare_entry("Time steps between mesh refinement",
2555 *   "10",
2556 *   Patterns::Integer(1),
2557 *   "The number of time steps after which the mesh is to be "
2558 *   "adapted based on computed error indicators.");
2559 *   prm.declare_entry("Generate graphical output",
2560 *   "false",
2561 *   Patterns::Bool(),
2562 *   "Whether graphical output is to be generated or not. "
2563 *   "You may not want to get graphical output if the number "
2564 *   "of processors is large.");
2565 *   prm.declare_entry("Time steps between graphical output",
2566 *   "50",
2567 *   Patterns::Integer(1),
2568 *   "The number of time steps between each generation of "
2569 *   "graphical output files.");
2570 *  
2571 *   prm.enter_subsection("Stabilization parameters");
2572 *   {
2573 *   prm.declare_entry("alpha",
2574 *   "2",
2575 *   Patterns::Double(1, 2),
2576 *   "The exponent in the entropy viscosity stabilization.");
2577 *   prm.declare_entry("c_R",
2578 *   "0.11",
2579 *   Patterns::Double(0),
2580 *   "The c_R factor in the entropy viscosity "
2581 *   "stabilization.");
2582 *   prm.declare_entry("beta",
2583 *   "0.078",
2584 *   Patterns::Double(0),
2585 *   "The beta factor in the artificial viscosity "
2586 *   "stabilization. An appropriate value for 2d is 0.052 "
2587 *   "and 0.078 for 3d.");
2588 *   }
2589 *   prm.leave_subsection();
2590 *  
2591 *   prm.enter_subsection("Discretization");
2592 *   {
2593 *   prm.declare_entry(
2594 *   "Stokes velocity polynomial degree",
2595 *   "2",
2596 *   Patterns::Integer(1),
2597 *   "The polynomial degree to use for the velocity variables "
2598 *   "in the Stokes system.");
2599 *   prm.declare_entry(
2600 *   "Temperature polynomial degree",
2601 *   "2",
2602 *   Patterns::Integer(1),
2603 *   "The polynomial degree to use for the temperature variable.");
2604 *   prm.declare_entry(
2605 *   "Use locally conservative discretization",
2606 *   "true",
2607 *   Patterns::Bool(),
2608 *   "Whether to use a Stokes discretization that is locally "
2609 *   "conservative at the expense of a larger number of degrees "
2610 *   "of freedom, or to go with a cheaper discretization "
2611 *   "that does not locally conserve mass (although it is "
2612 *   "globally conservative.");
2613 *   }
2614 *   prm.leave_subsection();
2615 *   }
2616 *  
2617 *  
2618 *  
2619 * @endcode
2620 *
2621 * And then we need a function that reads the contents of the
2622 * ParameterHandler object we get by reading the input file and puts the
2623 * results into variables that store the values of the parameters we have
2624 * previously declared:
2625 *
2626 * @code
2627 *   template <int dim>
2628 *   void BoussinesqFlowProblem<dim>::Parameters::parse_parameters(
2629 *   ParameterHandler &prm)
2630 *   {
2631 *   end_time = prm.get_double("End time");
2632 *   initial_global_refinement = prm.get_integer("Initial global refinement");
2633 *   initial_adaptive_refinement =
2634 *   prm.get_integer("Initial adaptive refinement");
2635 *  
2636 *   adaptive_refinement_interval =
2637 *   prm.get_integer("Time steps between mesh refinement");
2638 *  
2639 *   generate_graphical_output = prm.get_bool("Generate graphical output");
2640 *   graphical_output_interval =
2641 *   prm.get_integer("Time steps between graphical output");
2642 *  
2643 *   prm.enter_subsection("Stabilization parameters");
2644 *   {
2645 *   stabilization_alpha = prm.get_double("alpha");
2646 *   stabilization_c_R = prm.get_double("c_R");
2647 *   stabilization_beta = prm.get_double("beta");
2648 *   }
2649 *   prm.leave_subsection();
2650 *  
2651 *   prm.enter_subsection("Discretization");
2652 *   {
2653 *   stokes_velocity_degree =
2654 *   prm.get_integer("Stokes velocity polynomial degree");
2655 *   temperature_degree = prm.get_integer("Temperature polynomial degree");
2656 *   use_locally_conservative_discretization =
2657 *   prm.get_bool("Use locally conservative discretization");
2658 *   }
2659 *   prm.leave_subsection();
2660 *   }
2661 *  
2662 *  
2663 *  
2664 * @endcode
2665 *
2666 *
2667 * <a name="step_32-BoussinesqFlowProblemBoussinesqFlowProblem"></a>
2668 * <h4>BoussinesqFlowProblem::BoussinesqFlowProblem</h4>
2669 *
2670
2671 *
2672 * The constructor of the problem is very similar to the constructor in
2673 * @ref step_31 "step-31". What is different is the %parallel communication: Trilinos uses
2674 * a message passing interface (MPI) for data distribution. When entering
2675 * the BoussinesqFlowProblem class, we have to decide how the parallelization
2676 * is to be done. We choose a rather simple strategy and let all processors
2677 * that are running the program work together, specified by the communicator
2678 * <code>MPI_COMM_WORLD</code>. Next, we create the output stream (as we
2679 * already did in @ref step_18 "step-18") that only generates output on the first MPI
2680 * process and is completely forgetful on all others. The implementation of
2681 * this idea is to check the process number when <code>pcout</code> gets a
2682 * true argument, and it uses the <code>std::cout</code> stream for
2683 * output. If we are one processor five, for instance, then we will give a
2684 * <code>false</code> argument to <code>pcout</code>, which means that the
2685 * output of that processor will not be printed. With the exception of the
2686 * mapping object (for which we use polynomials of degree 4) all but the
2687 * final member variable are exactly the same as in @ref step_31 "step-31".
2688 *
2689
2690 *
2691 * This final object, the TimerOutput object, is then told to restrict
2692 * output to the <code>pcout</code> stream (processor 0), and then we
2693 * specify that we want to get a summary table at the end of the program
2694 * which shows us wallclock times (as opposed to CPU times). We will
2695 * manually also request intermediate summaries every so many time steps in
2696 * the <code>run()</code> function below.
2697 *
2698 * @code
2699 *   template <int dim>
2700 *   BoussinesqFlowProblem<dim>::BoussinesqFlowProblem(Parameters &parameters_)
2701 *   : parameters(parameters_)
2702 *   , pcout(std::cout, (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0))
2703 *   ,
2704 *  
2705 *   triangulation(MPI_COMM_WORLD,
2709 *   ,
2710 *  
2711 *   global_Omega_diameter(0.)
2712 *   ,
2713 *  
2714 *   mapping(4)
2715 *   ,
2716 *  
2717 *   stokes_fe(FE_Q<dim>(parameters.stokes_velocity_degree) ^ dim,
2718 *   (parameters.use_locally_conservative_discretization ?
2719 *   static_cast<const FiniteElement<dim> &>(
2720 *   FE_DGP<dim>(parameters.stokes_velocity_degree - 1)) :
2721 *   static_cast<const FiniteElement<dim> &>(
2722 *   FE_Q<dim>(parameters.stokes_velocity_degree - 1))))
2723 *   ,
2724 *  
2725 *   stokes_dof_handler(triangulation)
2726 *   ,
2727 *  
2728 *   temperature_fe(parameters.temperature_degree)
2729 *   , temperature_dof_handler(triangulation)
2730 *   ,
2731 *  
2732 *   time_step(0)
2733 *   , old_time_step(0)
2734 *   , timestep_number(0)
2735 *   , rebuild_stokes_matrix(true)
2736 *   , rebuild_stokes_preconditioner(true)
2737 *   , rebuild_temperature_matrices(true)
2738 *   , rebuild_temperature_preconditioner(true)
2739 *   ,
2740 *  
2741 *   computing_timer(MPI_COMM_WORLD,
2742 *   pcout,
2743 *   TimerOutput::summary,
2744 *   TimerOutput::wall_times)
2745 *   {}
2746 *  
2747 *  
2748 *  
2749 * @endcode
2750 *
2751 *
2752 * <a name="step_32-TheBoussinesqFlowProblemhelperfunctions"></a>
2753 * <h4>The BoussinesqFlowProblem helper functions</h4>
2754 *
2755 * <a name="step_32-BoussinesqFlowProblemget_maximal_velocity"></a>
2756 * <h5>BoussinesqFlowProblem::get_maximal_velocity</h5>
2757 *
2758
2759 *
2760 * Except for two small details, the function to compute the global maximum
2761 * of the velocity is the same as in @ref step_31 "step-31". The first detail is actually
2762 * common to all functions that implement loops over all cells in the
2763 * triangulation: When operating in %parallel, each processor can only work
2764 * on a chunk of cells since each processor only has a certain part of the
2765 * entire triangulation. This chunk of cells that we want to work on is
2766 * identified via a so-called <code>subdomain_id</code>, as we also did in
2767 * @ref step_18 "step-18". All we need to change is hence to perform the cell-related
2768 * operations only on cells that are owned by the current process (as
2769 * opposed to ghost or artificial cells), i.e. for which the subdomain id
2770 * equals the number of the process ID. Since this is a commonly used
2771 * operation, there is a shortcut for this operation: we can ask whether the
2772 * cell is owned by the current processor using
2773 * <code>cell-@>is_locally_owned()</code>.
2774 *
2775
2776 *
2777 * The second difference is the way we calculate the maximum value. Before,
2778 * we could simply have a <code>double</code> variable that we checked
2779 * against on each quadrature point for each cell. Now, we have to be a bit
2780 * more careful since each processor only operates on a subset of
2781 * cells. What we do is to first let each processor calculate the maximum
2782 * among its cells, and then do a global communication operation
2783 * <code>Utilities::MPI::max</code> that computes the maximum value among
2784 * all the maximum values of the individual processors. MPI provides such a
2785 * call, but it's even simpler to use the respective function in namespace
2786 * Utilities::MPI using the MPI communicator object since that will do the
2787 * right thing even if we work without MPI and on a single machine only. The
2788 * call to <code>Utilities::MPI::max</code> needs two arguments, namely the
2789 * local maximum (input) and the MPI communicator, which is MPI_COMM_WORLD
2790 * in this example.
2791 *
2792 * @code
2793 *   template <int dim>
2794 *   double BoussinesqFlowProblem<dim>::get_maximal_velocity() const
2795 *   {
2796 *   const QIterated<dim> quadrature_formula(QTrapezoid<1>(),
2797 *   parameters.stokes_velocity_degree);
2798 *   const unsigned int n_q_points = quadrature_formula.size();
2799 *  
2800 *   FEValues<dim> fe_values(mapping,
2801 *   stokes_fe,
2802 *   quadrature_formula,
2803 *   update_values);
2804 *   std::vector<Tensor<1, dim>> velocity_values(n_q_points);
2805 *  
2806 *   const FEValuesExtractors::Vector velocities(0);
2807 *  
2808 *   double max_local_velocity = 0;
2809 *  
2810 *   for (const auto &cell : stokes_dof_handler.active_cell_iterators())
2811 *   if (cell->is_locally_owned())
2812 *   {
2813 *   fe_values.reinit(cell);
2814 *   fe_values[velocities].get_function_values(stokes_solution,
2815 *   velocity_values);
2816 *  
2817 *   for (unsigned int q = 0; q < n_q_points; ++q)
2818 *   max_local_velocity =
2819 *   std::max(max_local_velocity, velocity_values[q].norm());
2820 *   }
2821 *  
2822 *   return Utilities::MPI::max(max_local_velocity, MPI_COMM_WORLD);
2823 *   }
2824 *  
2825 *  
2826 * @endcode
2827 *
2828 *
2829 * <a name="step_32-BoussinesqFlowProblemget_cfl_number"></a>
2830 * <h5>BoussinesqFlowProblem::get_cfl_number</h5>
2831 *
2832
2833 *
2834 * The next function does something similar, but we now compute the CFL
2835 * number, i.e., maximal velocity on a cell divided by the cell
2836 * diameter. This number is necessary to determine the time step size, as we
2837 * use a semi-explicit time stepping scheme for the temperature equation
2838 * (see @ref step_31 "step-31" for a discussion). We compute it in the same way as above:
2839 * Compute the local maximum over all locally owned cells, then exchange it
2840 * via MPI to find the global maximum.
2841 *
2842 * @code
2843 *   template <int dim>
2844 *   double BoussinesqFlowProblem<dim>::get_cfl_number() const
2845 *   {
2846 *   const QIterated<dim> quadrature_formula(QTrapezoid<1>(),
2847 *   parameters.stokes_velocity_degree);
2848 *   const unsigned int n_q_points = quadrature_formula.size();
2849 *  
2850 *   FEValues<dim> fe_values(mapping,
2851 *   stokes_fe,
2852 *   quadrature_formula,
2853 *   update_values);
2854 *   std::vector<Tensor<1, dim>> velocity_values(n_q_points);
2855 *  
2856 *   const FEValuesExtractors::Vector velocities(0);
2857 *  
2858 *   double max_local_cfl = 0;
2859 *  
2860 *   for (const auto &cell : stokes_dof_handler.active_cell_iterators())
2861 *   if (cell->is_locally_owned())
2862 *   {
2863 *   fe_values.reinit(cell);
2864 *   fe_values[velocities].get_function_values(stokes_solution,
2865 *   velocity_values);
2866 *  
2867 *   double max_local_velocity = 1e-10;
2868 *   for (unsigned int q = 0; q < n_q_points; ++q)
2869 *   max_local_velocity =
2870 *   std::max(max_local_velocity, velocity_values[q].norm());
2871 *   max_local_cfl =
2872 *   std::max(max_local_cfl, max_local_velocity / cell->diameter());
2873 *   }
2874 *  
2875 *   return Utilities::MPI::max(max_local_cfl, MPI_COMM_WORLD);
2876 *   }
2877 *  
2878 *  
2879 * @endcode
2880 *
2881 *
2882 * <a name="step_32-BoussinesqFlowProblemget_entropy_variation"></a>
2883 * <h5>BoussinesqFlowProblem::get_entropy_variation</h5>
2884 *
2885
2886 *
2887 * Next comes the computation of the global entropy variation
2888 * @f$\|E(T)-\bar{E}(T)\|_\infty@f$ where the entropy @f$E@f$ is defined as
2889 * discussed in the introduction. This is needed for the evaluation of the
2890 * stabilization in the temperature equation as explained in the
2891 * introduction. The entropy variation is actually only needed if we use
2892 * @f$\alpha=2@f$ as a power in the residual computation. The infinity norm is
2893 * computed by the maxima over quadrature points, as usual in discrete
2894 * computations.
2895 *
2896
2897 *
2898 * In order to compute this quantity, we first have to find the
2899 * space-average @f$\bar{E}(T)@f$ and then evaluate the maximum. However, that
2900 * means that we would need to perform two loops. We can avoid the overhead
2901 * by noting that @f$\|E(T)-\bar{E}(T)\|_\infty =
2902 * \max\big(E_{\textrm{max}}(T)-\bar{E}(T),
2903 * \bar{E}(T)-E_{\textrm{min}}(T)\big)@f$, i.e., the maximum out of the
2904 * deviation from the average entropy in positive and negative
2905 * directions. The four quantities we need for the latter formula (maximum
2906 * entropy, minimum entropy, average entropy, area) can all be evaluated in
2907 * the same loop over all cells, so we choose this simpler variant.
2908 *
2909 * @code
2910 *   template <int dim>
2911 *   double BoussinesqFlowProblem<dim>::get_entropy_variation(
2912 *   const double average_temperature) const
2913 *   {
2914 *   if (parameters.stabilization_alpha != 2)
2915 *   return 1.;
2916 *  
2917 *   const QGauss<dim> quadrature_formula(parameters.temperature_degree + 1);
2918 *   const unsigned int n_q_points = quadrature_formula.size();
2919 *  
2920 *   FEValues<dim> fe_values(temperature_fe,
2921 *   quadrature_formula,
2922 *   update_values | update_JxW_values);
2923 *   std::vector<double> old_temperature_values(n_q_points);
2924 *   std::vector<double> old_old_temperature_values(n_q_points);
2925 *  
2926 * @endcode
2927 *
2928 * In the two functions above we computed the maximum of numbers that were
2929 * all non-negative, so we knew that zero was certainly a lower bound. On
2930 * the other hand, here we need to find the maximum deviation from the
2931 * average value, i.e., we will need to know the maximal and minimal
2932 * values of the entropy for which we don't a priori know the sign.
2933 *
2934
2935 *
2936 * To compute it, we can therefore start with the largest and smallest
2937 * possible values we can store in a double precision number: The minimum
2938 * is initialized with a bigger and the maximum with a smaller number than
2939 * any one that is going to appear. We are then guaranteed that these
2940 * numbers will be overwritten in the loop on the first cell or, if this
2941 * processor does not own any cells, in the communication step at the
2942 * latest. The following loop then computes the minimum and maximum local
2943 * entropy as well as keeps track of the area/volume of the part of the
2944 * domain we locally own and the integral over the entropy on it:
2945 *
2946 * @code
2947 *   double min_entropy = std::numeric_limits<double>::max(),
2948 *   max_entropy = -std::numeric_limits<double>::max(), area = 0,
2949 *   entropy_integrated = 0;
2950 *  
2951 *   for (const auto &cell : temperature_dof_handler.active_cell_iterators())
2952 *   if (cell->is_locally_owned())
2953 *   {
2954 *   fe_values.reinit(cell);
2955 *   fe_values.get_function_values(old_temperature_solution,
2956 *   old_temperature_values);
2957 *   fe_values.get_function_values(old_old_temperature_solution,
2958 *   old_old_temperature_values);
2959 *   for (unsigned int q = 0; q < n_q_points; ++q)
2960 *   {
2961 *   const double T =
2962 *   (old_temperature_values[q] + old_old_temperature_values[q]) / 2;
2963 *   const double entropy =
2964 *   ((T - average_temperature) * (T - average_temperature));
2965 *  
2966 *   min_entropy = std::min(min_entropy, entropy);
2967 *   max_entropy = std::max(max_entropy, entropy);
2968 *   area += fe_values.JxW(q);
2969 *   entropy_integrated += fe_values.JxW(q) * entropy;
2970 *   }
2971 *   }
2972 *  
2973 * @endcode
2974 *
2975 * Now we only need to exchange data between processors: we need to sum
2976 * the two integrals (<code>area</code>, <code>entropy_integrated</code>),
2977 * and get the extrema for maximum and minimum. We could do this through
2978 * four different data exchanges, but we can it with two:
2979 * Utilities::MPI::sum also exists in a variant that takes an array of
2980 * values that are all to be summed up. And we can also utilize the
2981 * Utilities::MPI::max function by realizing that forming the minimum over
2982 * the minimal entropies equals forming the negative of the maximum over
2983 * the negative of the minimal entropies; this maximum can then be
2984 * combined with forming the maximum over the maximal entropies.
2985 *
2986 * @code
2987 *   const double local_sums[2] = {entropy_integrated, area},
2988 *   local_maxima[2] = {-min_entropy, max_entropy};
2989 *   double global_sums[2], global_maxima[2];
2990 *  
2991 *   Utilities::MPI::sum(local_sums, MPI_COMM_WORLD, global_sums);
2992 *   Utilities::MPI::max(local_maxima, MPI_COMM_WORLD, global_maxima);
2993 *  
2994 * @endcode
2995 *
2996 * Having computed everything this way, we can then compute the average
2997 * entropy and find the @f$L^\infty@f$ norm by taking the larger of the
2998 * deviation of the maximum or minimum from the average:
2999 *
3000 * @code
3001 *   const double average_entropy = global_sums[0] / global_sums[1];
3002 *   const double entropy_diff = std::max(global_maxima[1] - average_entropy,
3003 *   average_entropy - (-global_maxima[0]));
3004 *   return entropy_diff;
3005 *   }
3006 *  
3007 *  
3008 *  
3009 * @endcode
3010 *
3011 *
3012 * <a name="step_32-BoussinesqFlowProblemget_extrapolated_temperature_range"></a>
3013 * <h5>BoussinesqFlowProblem::get_extrapolated_temperature_range</h5>
3014 *
3015
3016 *
3017 * The next function computes the minimal and maximal value of the
3018 * extrapolated temperature over the entire domain. Again, this is only a
3019 * slightly modified version of the respective function in @ref step_31 "step-31". As in
3020 * the function above, we collect local minima and maxima and then compute
3021 * the global extrema using the same trick as above.
3022 *
3023
3024 *
3025 * As already discussed in @ref step_31 "step-31", the function needs to distinguish
3026 * between the first and all following time steps because it uses a higher
3027 * order temperature extrapolation scheme when at least two previous time
3028 * steps are available.
3029 *
3030 * @code
3031 *   template <int dim>
3032 *   std::pair<double, double>
3033 *   BoussinesqFlowProblem<dim>::get_extrapolated_temperature_range() const
3034 *   {
3035 *   const QIterated<dim> quadrature_formula(QTrapezoid<1>(),
3036 *   parameters.temperature_degree);
3037 *   const unsigned int n_q_points = quadrature_formula.size();
3038 *  
3039 *   FEValues<dim> fe_values(mapping,
3040 *   temperature_fe,
3041 *   quadrature_formula,
3042 *   update_values);
3043 *   std::vector<double> old_temperature_values(n_q_points);
3044 *   std::vector<double> old_old_temperature_values(n_q_points);
3045 *  
3046 *   double min_local_temperature = std::numeric_limits<double>::max(),
3047 *   max_local_temperature = -std::numeric_limits<double>::max();
3048 *  
3049 *   if (timestep_number != 0)
3050 *   {
3051 *   for (const auto &cell : temperature_dof_handler.active_cell_iterators())
3052 *   if (cell->is_locally_owned())
3053 *   {
3054 *   fe_values.reinit(cell);
3055 *   fe_values.get_function_values(old_temperature_solution,
3056 *   old_temperature_values);
3057 *   fe_values.get_function_values(old_old_temperature_solution,
3058 *   old_old_temperature_values);
3059 *  
3060 *   for (unsigned int q = 0; q < n_q_points; ++q)
3061 *   {
3062 *   const double temperature =
3063 *   (1. + time_step / old_time_step) *
3064 *   old_temperature_values[q] -
3065 *   time_step / old_time_step * old_old_temperature_values[q];
3066 *  
3067 *   min_local_temperature =
3068 *   std::min(min_local_temperature, temperature);
3069 *   max_local_temperature =
3070 *   std::max(max_local_temperature, temperature);
3071 *   }
3072 *   }
3073 *   }
3074 *   else
3075 *   {
3076 *   for (const auto &cell : temperature_dof_handler.active_cell_iterators())
3077 *   if (cell->is_locally_owned())
3078 *   {
3079 *   fe_values.reinit(cell);
3080 *   fe_values.get_function_values(old_temperature_solution,
3081 *   old_temperature_values);
3082 *  
3083 *   for (unsigned int q = 0; q < n_q_points; ++q)
3084 *   {
3085 *   const double temperature = old_temperature_values[q];
3086 *  
3087 *   min_local_temperature =
3088 *   std::min(min_local_temperature, temperature);
3089 *   max_local_temperature =
3090 *   std::max(max_local_temperature, temperature);
3091 *   }
3092 *   }
3093 *   }
3094 *  
3095 *   double local_extrema[2] = {-min_local_temperature, max_local_temperature};
3096 *   double global_extrema[2];
3097 *   Utilities::MPI::max(local_extrema, MPI_COMM_WORLD, global_extrema);
3098 *  
3099 *   return std::make_pair(-global_extrema[0], global_extrema[1]);
3100 *   }
3101 *  
3102 *  
3103 * @endcode
3104 *
3105 *
3106 * <a name="step_32-BoussinesqFlowProblemcompute_viscosity"></a>
3107 * <h5>BoussinesqFlowProblem::compute_viscosity</h5>
3108 *
3109
3110 *
3111 * The function that calculates the viscosity is purely local and so needs
3112 * no communication at all. It is mostly the same as in @ref step_31 "step-31" but with an
3113 * updated formulation of the viscosity if @f$\alpha=2@f$ is chosen:
3114 *
3115 * @code
3116 *   template <int dim>
3117 *   double BoussinesqFlowProblem<dim>::compute_viscosity(
3118 *   const std::vector<double> &old_temperature,
3119 *   const std::vector<double> &old_old_temperature,
3120 *   const std::vector<Tensor<1, dim>> &old_temperature_grads,
3121 *   const std::vector<Tensor<1, dim>> &old_old_temperature_grads,
3122 *   const std::vector<double> &old_temperature_laplacians,
3123 *   const std::vector<double> &old_old_temperature_laplacians,
3124 *   const std::vector<Tensor<1, dim>> &old_velocity_values,
3125 *   const std::vector<Tensor<1, dim>> &old_old_velocity_values,
3126 *   const std::vector<SymmetricTensor<2, dim>> &old_strain_rates,
3127 *   const std::vector<SymmetricTensor<2, dim>> &old_old_strain_rates,
3128 *   const double global_u_infty,
3129 *   const double global_T_variation,
3130 *   const double average_temperature,
3131 *   const double global_entropy_variation,
3132 *   const double cell_diameter) const
3133 *   {
3134 *   if (global_u_infty == 0)
3135 *   return 5e-3 * cell_diameter;
3136 *  
3137 *   const unsigned int n_q_points = old_temperature.size();
3138 *  
3139 *   double max_residual = 0;
3140 *   double max_velocity = 0;
3141 *  
3142 *   for (unsigned int q = 0; q < n_q_points; ++q)
3143 *   {
3144 *   const Tensor<1, dim> u =
3145 *   (old_velocity_values[q] + old_old_velocity_values[q]) / 2;
3146 *  
3147 *   const SymmetricTensor<2, dim> strain_rate =
3148 *   (old_strain_rates[q] + old_old_strain_rates[q]) / 2;
3149 *  
3150 *   const double T = (old_temperature[q] + old_old_temperature[q]) / 2;
3151 *   const double dT_dt =
3152 *   (old_temperature[q] - old_old_temperature[q]) / old_time_step;
3153 *   const double u_grad_T =
3154 *   u * (old_temperature_grads[q] + old_old_temperature_grads[q]) / 2;
3155 *  
3156 *   const double kappa_Delta_T =
3157 *   EquationData::kappa *
3158 *   (old_temperature_laplacians[q] + old_old_temperature_laplacians[q]) /
3159 *   2;
3160 *   const double gamma =
3161 *   ((EquationData::radiogenic_heating * EquationData::density(T) +
3162 *   2 * EquationData::eta * strain_rate * strain_rate) /
3163 *   (EquationData::density(T) * EquationData::specific_heat));
3164 *  
3165 *   double residual = std::abs(dT_dt + u_grad_T - kappa_Delta_T - gamma);
3166 *   if (parameters.stabilization_alpha == 2)
3167 *   residual *= std::abs(T - average_temperature);
3168 *  
3169 *   max_residual = std::max(residual, max_residual);
3170 *   max_velocity = std::max(std::sqrt(u * u), max_velocity);
3171 *   }
3172 *  
3173 *   const double max_viscosity =
3174 *   (parameters.stabilization_beta * max_velocity * cell_diameter);
3175 *   if (timestep_number == 0)
3176 *   return max_viscosity;
3177 *   else
3178 *   {
3179 *   Assert(old_time_step > 0, ExcInternalError());
3180 *  
3181 *   double entropy_viscosity;
3182 *   if (parameters.stabilization_alpha == 2)
3183 *   entropy_viscosity =
3184 *   (parameters.stabilization_c_R * cell_diameter * cell_diameter *
3185 *   max_residual / global_entropy_variation);
3186 *   else
3187 *   entropy_viscosity =
3188 *   (parameters.stabilization_c_R * cell_diameter *
3189 *   global_Omega_diameter * max_velocity * max_residual /
3190 *   (global_u_infty * global_T_variation));
3191 *  
3192 *   return std::min(max_viscosity, entropy_viscosity);
3193 *   }
3194 *   }
3195 *  
3196 *  
3197 *  
3198 * @endcode
3199 *
3200 *
3201 * <a name="step_32-TheBoussinesqFlowProblemsetupfunctions"></a>
3202 * <h4>The BoussinesqFlowProblem setup functions</h4>
3203 *
3204
3205 *
3206 * The following three functions set up the Stokes matrix, the matrix used
3207 * for the Stokes preconditioner, and the temperature matrix. The code is
3208 * mostly the same as in @ref step_31 "step-31", but it has been broken out into three
3209 * functions of their own for simplicity.
3210 *
3211
3212 *
3213 * The main functional difference between the code here and that in @ref step_31 "step-31"
3214 * is that the matrices we want to set up are distributed across multiple
3215 * processors. Since we still want to build up the sparsity pattern first
3216 * for efficiency reasons, we could continue to build the <i>entire</i>
3217 * sparsity pattern as a BlockDynamicSparsityPattern, as we did in
3218 * @ref step_31 "step-31". However, that would be inefficient: every processor would build
3219 * the same sparsity pattern, but only initialize a small part of the matrix
3220 * using it. It also violates the principle that every processor should only
3221 * work on those cells it owns (and, if necessary the layer of ghost cells
3222 * around it).
3223 *
3224
3225 *
3226 * Rather, we use an object of type TrilinosWrappers::BlockSparsityPattern,
3227 * which is (obviously) a wrapper around a sparsity pattern object provided
3228 * by Trilinos. The advantage is that the Trilinos sparsity pattern class
3229 * can communicate across multiple processors: if this processor fills in
3230 * all the nonzero entries that result from the cells it owns, and every
3231 * other processor does so as well, then at the end after some MPI
3232 * communication initiated by the <code>compress()</code> call, we will have
3233 * the globally assembled sparsity pattern available with which the global
3234 * matrix can be initialized.
3235 *
3236
3237 *
3238 * There is one important aspect when initializing Trilinos sparsity
3239 * patterns in parallel: In addition to specifying the locally owned rows
3240 * and columns of the matrices via the @p stokes_partitioning index set, we
3241 * also supply information about all the rows we are possibly going to write
3242 * into when assembling on a certain processor. The set of locally relevant
3243 * rows contains all such rows (possibly also a few unnecessary ones, but it
3244 * is difficult to find the exact row indices before actually getting
3245 * indices on all cells and resolving constraints). This additional
3246 * information allows to exactly determine the structure for the
3247 * off-processor data found during assembly. While Trilinos matrices are
3248 * able to collect this information on the fly as well (when initializing
3249 * them from some other reinit method), it is less efficient and leads to
3250 * problems when assembling matrices with multiple threads. In this program,
3251 * we pessimistically assume that only one processor at a time can write
3252 * into the matrix while assembly (whereas the computation is parallel),
3253 * which is fine for Trilinos matrices. In practice, one can do better by
3254 * hinting WorkStream at cells that do not share vertices, allowing for
3255 * parallelism among those cells (see the graph coloring algorithms and
3256 * WorkStream with colored iterators argument). However, that only works
3257 * when only one MPI processor is present because Trilinos' internal data
3258 * structures for accumulating off-processor data on the fly are not thread
3259 * safe. With the initialization presented here, there is no such problem
3260 * and one could safely introduce graph coloring for this algorithm.
3261 *
3262
3263 *
3264 * The only other change we need to make is to tell the
3265 * DoFTools::make_sparsity_pattern() function that it is only supposed to
3266 * work on a subset of cells, namely the ones whose
3267 * <code>subdomain_id</code> equals the number of the current processor, and
3268 * to ignore all other cells.
3269 *
3270
3271 *
3272 * This strategy is replicated across all three of the following functions.
3273 *
3274
3275 *
3276 * Note that Trilinos matrices store the information contained in the
3277 * sparsity patterns, so we can safely release the <code>sp</code> variable
3278 * once the matrix has been given the sparsity structure.
3279 *
3280 * @code
3281 *   template <int dim>
3282 *   void BoussinesqFlowProblem<dim>::setup_stokes_matrix(
3283 *   const std::vector<IndexSet> &stokes_partitioning,
3284 *   const std::vector<IndexSet> &stokes_relevant_partitioning)
3285 *   {
3286 *   stokes_matrix.clear();
3287 *  
3288 *   TrilinosWrappers::BlockSparsityPattern sp(stokes_partitioning,
3289 *   stokes_partitioning,
3290 *   stokes_relevant_partitioning,
3291 *   MPI_COMM_WORLD);
3292 *  
3293 *   Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1);
3294 *   for (unsigned int c = 0; c < dim + 1; ++c)
3295 *   for (unsigned int d = 0; d < dim + 1; ++d)
3296 *   if (!((c == dim) && (d == dim)))
3297 *   coupling[c][d] = DoFTools::always;
3298 *   else
3299 *   coupling[c][d] = DoFTools::none;
3300 *  
3301 *   DoFTools::make_sparsity_pattern(stokes_dof_handler,
3302 *   coupling,
3303 *   sp,
3304 *   stokes_constraints,
3305 *   false,
3306 *   Utilities::MPI::this_mpi_process(
3307 *   MPI_COMM_WORLD));
3308 *   sp.compress();
3309 *  
3310 *   stokes_matrix.reinit(sp);
3311 *   }
3312 *  
3313 *  
3314 *  
3315 *   template <int dim>
3316 *   void BoussinesqFlowProblem<dim>::setup_stokes_preconditioner(
3317 *   const std::vector<IndexSet> &stokes_partitioning,
3318 *   const std::vector<IndexSet> &stokes_relevant_partitioning)
3319 *   {
3320 *   Amg_preconditioner.reset();
3321 *   Mp_preconditioner.reset();
3322 *  
3323 *   stokes_preconditioner_matrix.clear();
3324 *  
3325 *   TrilinosWrappers::BlockSparsityPattern sp(stokes_partitioning,
3326 *   stokes_partitioning,
3327 *   stokes_relevant_partitioning,
3328 *   MPI_COMM_WORLD);
3329 *  
3330 *   Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1);
3331 *   for (unsigned int c = 0; c < dim + 1; ++c)
3332 *   for (unsigned int d = 0; d < dim + 1; ++d)
3333 *   if (c == d)
3334 *   coupling[c][d] = DoFTools::always;
3335 *   else
3336 *   coupling[c][d] = DoFTools::none;
3337 *  
3338 *   DoFTools::make_sparsity_pattern(stokes_dof_handler,
3339 *   coupling,
3340 *   sp,
3341 *   stokes_constraints,
3342 *   false,
3343 *   Utilities::MPI::this_mpi_process(
3344 *   MPI_COMM_WORLD));
3345 *   sp.compress();
3346 *  
3347 *   stokes_preconditioner_matrix.reinit(sp);
3348 *   }
3349 *  
3350 *  
3351 *   template <int dim>
3352 *   void BoussinesqFlowProblem<dim>::setup_temperature_matrices(
3353 *   const IndexSet &temperature_partitioner,
3354 *   const IndexSet &temperature_relevant_partitioner)
3355 *   {
3356 *   T_preconditioner.reset();
3357 *   temperature_mass_matrix.clear();
3358 *   temperature_stiffness_matrix.clear();
3359 *   temperature_matrix.clear();
3360 *  
3361 *   TrilinosWrappers::SparsityPattern sp(temperature_partitioner,
3362 *   temperature_partitioner,
3363 *   temperature_relevant_partitioner,
3364 *   MPI_COMM_WORLD);
3365 *   DoFTools::make_sparsity_pattern(temperature_dof_handler,
3366 *   sp,
3367 *   temperature_constraints,
3368 *   false,
3369 *   Utilities::MPI::this_mpi_process(
3370 *   MPI_COMM_WORLD));
3371 *   sp.compress();
3372 *  
3373 *   temperature_matrix.reinit(sp);
3374 *   temperature_mass_matrix.reinit(sp);
3375 *   temperature_stiffness_matrix.reinit(sp);
3376 *   }
3377 *  
3378 *  
3379 *  
3380 * @endcode
3381 *
3382 * The remainder of the setup function (after splitting out the three
3383 * functions above) mostly has to deal with the things we need to do for
3384 * parallelization across processors. Because setting all of this up is a
3385 * significant compute time expense of the program, we put everything we do
3386 * here into a timer group so that we can get summary information about the
3387 * fraction of time spent in this part of the program at its end.
3388 *
3389
3390 *
3391 * At the top as usual we enumerate degrees of freedom and sort them by
3392 * component/block, followed by writing their numbers to the screen from
3393 * processor zero. The DoFHandler::distributed_dofs() function, when applied
3394 * to a parallel::distributed::Triangulation object, sorts degrees of
3395 * freedom in such a way that all degrees of freedom associated with
3396 * subdomain zero come before all those associated with subdomain one,
3397 * etc. For the Stokes part, this entails, however, that velocities and
3398 * pressures become intermixed, but this is trivially solved by sorting
3399 * again by blocks; it is worth noting that this latter operation leaves the
3400 * relative ordering of all velocities and pressures alone, i.e. within the
3401 * velocity block we will still have all those associated with subdomain
3402 * zero before all velocities associated with subdomain one, etc. This is
3403 * important since we store each of the blocks of this matrix distributed
3404 * across all processors and want this to be done in such a way that each
3405 * processor stores that part of the matrix that is roughly equal to the
3406 * degrees of freedom located on those cells that it will actually work on.
3407 *
3408
3409 *
3410 * When printing the numbers of degrees of freedom, note that these numbers
3411 * are going to be large if we use many processors. Consequently, we let the
3412 * stream put a comma separator in between every three digits. The state of
3413 * the stream, using the locale, is saved from before to after this
3414 * operation. While slightly opaque, the code works because the default
3415 * locale (which we get using the constructor call
3416 * <code>std::locale("")</code>) implies printing numbers with a comma
3417 * separator for every third digit (i.e., thousands, millions, billions).
3418 *
3419
3420 *
3421 * In this function as well as many below, we measure how much time
3422 * we spend here and collect that in a section called "Setup dof
3423 * systems" across function invocations. This is done using an
3424 * TimerOutput::Scope object that gets a timer going in the section
3425 * with above name of the `computing_timer` object upon construction
3426 * of the local variable; the timer is stopped again when the
3427 * destructor of the `timing_section` variable is called. This, of
3428 * course, happens either at the end of the function, or if we leave
3429 * the function through a `return` statement or when an exception is
3430 * thrown somewhere -- in other words, whenever we leave this
3431 * function in any way. The use of such "scope" objects therefore
3432 * makes sure that we do not have to manually add code that tells
3433 * the timer to stop at every location where this function may be
3434 * left.
3435 *
3436 * @code
3437 *   template <int dim>
3438 *   void BoussinesqFlowProblem<dim>::setup_dofs()
3439 *   {
3440 *   TimerOutput::Scope timing_section(computing_timer, "Setup dof systems");
3441 *  
3442 *   stokes_dof_handler.distribute_dofs(stokes_fe);
3443 *  
3444 *   std::vector<unsigned int> stokes_sub_blocks(dim + 1, 0);
3445 *   stokes_sub_blocks[dim] = 1;
3446 *   DoFRenumbering::component_wise(stokes_dof_handler, stokes_sub_blocks);
3447 *  
3448 *   temperature_dof_handler.distribute_dofs(temperature_fe);
3449 *  
3450 *   const std::vector<types::global_dof_index> stokes_dofs_per_block =
3451 *   DoFTools::count_dofs_per_fe_block(stokes_dof_handler, stokes_sub_blocks);
3452 *  
3453 *   const types::global_dof_index n_u = stokes_dofs_per_block[0],
3454 *   n_p = stokes_dofs_per_block[1],
3455 *   n_T = temperature_dof_handler.n_dofs();
3456 *  
3457 *   std::locale s = pcout.get_stream().getloc();
3458 *   pcout.get_stream().imbue(std::locale(""));
3459 *   pcout << "Number of active cells: " << triangulation.n_global_active_cells()
3460 *   << " (on " << triangulation.n_levels() << " levels)" << std::endl
3461 *   << "Number of degrees of freedom: " << n_u + n_p + n_T << " (" << n_u
3462 *   << '+' << n_p << '+' << n_T << ')' << std::endl
3463 *   << std::endl;
3464 *   pcout.get_stream().imbue(s);
3465 *  
3466 *  
3467 * @endcode
3468 *
3469 * After this, we have to set up the various partitioners (of type
3470 * <code>IndexSet</code>, see the introduction) that describe which parts
3471 * of each matrix or vector will be stored where, then call the functions
3472 * that actually set up the matrices, and at the end also resize the
3473 * various vectors we keep around in this program.
3474 *
3475
3476 *
3477 *
3478 * @code
3479 *   const IndexSet &stokes_locally_owned_index_set =
3480 *   stokes_dof_handler.locally_owned_dofs();
3481 *   const IndexSet stokes_locally_relevant_set =
3482 *   DoFTools::extract_locally_relevant_dofs(stokes_dof_handler);
3483 *  
3484 *   std::vector<IndexSet> stokes_partitioning;
3485 *   stokes_partitioning.push_back(
3486 *   stokes_locally_owned_index_set.get_view(0, n_u));
3487 *   stokes_partitioning.push_back(
3488 *   stokes_locally_owned_index_set.get_view(n_u, n_u + n_p));
3489 *  
3490 *   std::vector<IndexSet> stokes_relevant_partitioning;
3491 *   stokes_relevant_partitioning.push_back(
3492 *   stokes_locally_relevant_set.get_view(0, n_u));
3493 *   stokes_relevant_partitioning.push_back(
3494 *   stokes_locally_relevant_set.get_view(n_u, n_u + n_p));
3495 *  
3496 *   const IndexSet temperature_partitioning =
3497 *   temperature_dof_handler.locally_owned_dofs();
3498 *   const IndexSet temperature_relevant_partitioning =
3499 *   DoFTools::extract_locally_relevant_dofs(temperature_dof_handler);
3500 *  
3501 * @endcode
3502 *
3503 * Following this, we can compute constraints for the solution vectors,
3504 * including hanging node constraints and homogeneous and inhomogeneous
3505 * boundary values for the Stokes and temperature fields. Note that as for
3506 * everything else, the constraint objects can not hold <i>all</i>
3507 * constraints on every processor. Rather, each processor needs to store
3508 * only those that are actually necessary for correctness given that it
3509 * only assembles linear systems on cells it owns. As discussed in the
3510 * @ref distributed_paper "this paper", the set of constraints we need to
3511 * know about is exactly the set of constraints on all locally relevant
3512 * degrees of freedom, so this is what we use to initialize the constraint
3513 * objects.
3514 *
3515 * @code
3516 *   {
3517 *   stokes_constraints.clear();
3518 *   stokes_constraints.reinit(stokes_locally_owned_index_set,
3519 *   stokes_locally_relevant_set);
3520 *  
3521 *   DoFTools::make_hanging_node_constraints(stokes_dof_handler,
3522 *   stokes_constraints);
3523 *  
3524 *   const FEValuesExtractors::Vector velocity_components(0);
3525 *   VectorTools::interpolate_boundary_values(
3526 *   stokes_dof_handler,
3527 *   0,
3528 *   Functions::ZeroFunction<dim>(dim + 1),
3529 *   stokes_constraints,
3530 *   stokes_fe.component_mask(velocity_components));
3531 *  
3532 *   std::set<types::boundary_id> no_normal_flux_boundaries;
3533 *   no_normal_flux_boundaries.insert(1);
3534 *   VectorTools::compute_no_normal_flux_constraints(stokes_dof_handler,
3535 *   0,
3536 *   no_normal_flux_boundaries,
3537 *   stokes_constraints,
3538 *   mapping);
3539 *   stokes_constraints.close();
3540 *   }
3541 *   {
3542 *   temperature_constraints.clear();
3543 *   temperature_constraints.reinit(temperature_partitioning,
3544 *   temperature_relevant_partitioning);
3545 *  
3546 *   DoFTools::make_hanging_node_constraints(temperature_dof_handler,
3547 *   temperature_constraints);
3548 *   VectorTools::interpolate_boundary_values(
3549 *   temperature_dof_handler,
3550 *   0,
3551 *   EquationData::TemperatureInitialValues<dim>(),
3552 *   temperature_constraints);
3553 *   VectorTools::interpolate_boundary_values(
3554 *   temperature_dof_handler,
3555 *   1,
3556 *   EquationData::TemperatureInitialValues<dim>(),
3557 *   temperature_constraints);
3558 *   temperature_constraints.close();
3559 *   }
3560 *  
3561 * @endcode
3562 *
3563 * All this done, we can then initialize the various matrix and vector
3564 * objects to their proper sizes. At the end, we also record that all
3565 * matrices and preconditioners have to be re-computed at the beginning of
3566 * the next time step. Note how we initialize the vectors for the Stokes
3567 * and temperature right hand sides: These are writable vectors (last
3568 * boolean argument set to @p true) that have the correct one-to-one
3569 * partitioning of locally owned elements but are still given the relevant
3570 * partitioning for means of figuring out the vector entries that are
3571 * going to be set right away. As for matrices, this allows for writing
3572 * local contributions into the vector with multiple threads (always
3573 * assuming that the same vector entry is not accessed by multiple threads
3574 * at the same time). The other vectors only allow for read access of
3575 * individual elements, including ghosts, but are not suitable for
3576 * solvers.
3577 *
3578 * @code
3579 *   setup_stokes_matrix(stokes_partitioning, stokes_relevant_partitioning);
3580 *   setup_stokes_preconditioner(stokes_partitioning,
3581 *   stokes_relevant_partitioning);
3582 *   setup_temperature_matrices(temperature_partitioning,
3583 *   temperature_relevant_partitioning);
3584 *  
3585 *   stokes_rhs.reinit(stokes_partitioning,
3586 *   stokes_relevant_partitioning,
3587 *   MPI_COMM_WORLD,
3588 *   true);
3589 *   stokes_solution.reinit(stokes_relevant_partitioning, MPI_COMM_WORLD);
3590 *   old_stokes_solution.reinit(stokes_solution);
3591 *  
3592 *   temperature_rhs.reinit(temperature_partitioning,
3593 *   temperature_relevant_partitioning,
3594 *   MPI_COMM_WORLD,
3595 *   true);
3596 *   temperature_solution.reinit(temperature_relevant_partitioning,
3597 *   MPI_COMM_WORLD);
3598 *   old_temperature_solution.reinit(temperature_solution);
3599 *   old_old_temperature_solution.reinit(temperature_solution);
3600 *  
3601 *   rebuild_stokes_matrix = true;
3602 *   rebuild_stokes_preconditioner = true;
3603 *   rebuild_temperature_matrices = true;
3604 *   rebuild_temperature_preconditioner = true;
3605 *   }
3606 *  
3607 *  
3608 *  
3609 * @endcode
3610 *
3611 *
3612 * <a name="step_32-TheBoussinesqFlowProblemassemblyfunctions"></a>
3613 * <h4>The BoussinesqFlowProblem assembly functions</h4>
3614 *
3615
3616 *
3617 * Following the discussion in the introduction and in the @ref threads
3618 * topic, we split the assembly functions into different parts:
3619 *
3620
3621 *
3622 * <ul> <li> The local calculations of matrices and right hand sides, given
3623 * a certain cell as input (these functions are named
3624 * <code>local_assemble_*</code> below). The resulting function is, in other
3625 * words, essentially the body of the loop over all cells in @ref step_31 "step-31". Note,
3626 * however, that these functions store the result from the local
3627 * calculations in variables of classes from the CopyData namespace.
3628 *
3629
3630 *
3631 * <li>These objects are then given to the second step which writes the
3632 * local data into the global data structures (these functions are named
3633 * <code>copy_local_to_global_*</code> below). These functions are pretty
3634 * trivial.
3635 *
3636
3637 *
3638 * <li>These two subfunctions are then used in the respective assembly
3639 * routine (called <code>assemble_*</code> below), where a WorkStream object
3640 * is set up and runs over all the cells that belong to the processor's
3641 * subdomain. </ul>
3642 *
3643
3644 *
3645 *
3646 * <a name="step_32-Stokespreconditionerassembly"></a>
3647 * <h5>Stokes preconditioner assembly</h5>
3648 *
3649
3650 *
3651 * Let us start with the functions that builds the Stokes
3652 * preconditioner. The first two of these are pretty trivial, given the
3653 * discussion above. Note in particular that the main point in using the
3654 * scratch data object is that we want to avoid allocating any objects on
3655 * the free space each time we visit a new cell. As a consequence, the
3656 * assembly function below only has automatic local variables, and
3657 * everything else is accessed through the scratch data object, which is
3658 * allocated only once before we start the loop over all cells:
3659 *
3660 * @code
3661 *   template <int dim>
3662 *   void BoussinesqFlowProblem<dim>::local_assemble_stokes_preconditioner(
3663 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
3664 *   Assembly::Scratch::StokesPreconditioner<dim> &scratch,
3665 *   Assembly::CopyData::StokesPreconditioner<dim> &data)
3666 *   {
3667 *   const unsigned int dofs_per_cell = stokes_fe.n_dofs_per_cell();
3668 *   const unsigned int n_q_points =
3669 *   scratch.stokes_fe_values.n_quadrature_points;
3670 *  
3671 *   const FEValuesExtractors::Vector velocities(0);
3672 *   const FEValuesExtractors::Scalar pressure(dim);
3673 *  
3674 *   scratch.stokes_fe_values.reinit(cell);
3675 *   cell->get_dof_indices(data.local_dof_indices);
3676 *  
3677 *   data.local_matrix = 0;
3678 *  
3679 *   for (unsigned int q = 0; q < n_q_points; ++q)
3680 *   {
3681 *   for (unsigned int k = 0; k < dofs_per_cell; ++k)
3682 *   {
3683 *   scratch.grad_phi_u[k] =
3684 *   scratch.stokes_fe_values[velocities].gradient(k, q);
3685 *   scratch.phi_p[k] = scratch.stokes_fe_values[pressure].value(k, q);
3686 *   }
3687 *  
3688 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
3689 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
3690 *   data.local_matrix(i, j) +=
3691 *   (EquationData::eta *
3692 *   scalar_product(scratch.grad_phi_u[i], scratch.grad_phi_u[j]) +
3693 *   (1. / EquationData::eta) * EquationData::pressure_scaling *
3694 *   EquationData::pressure_scaling *
3695 *   (scratch.phi_p[i] * scratch.phi_p[j])) *
3696 *   scratch.stokes_fe_values.JxW(q);
3697 *   }
3698 *   }
3699 *  
3700 *  
3701 *  
3702 *   template <int dim>
3703 *   void BoussinesqFlowProblem<dim>::copy_local_to_global_stokes_preconditioner(
3704 *   const Assembly::CopyData::StokesPreconditioner<dim> &data)
3705 *   {
3706 *   stokes_constraints.distribute_local_to_global(data.local_matrix,
3707 *   data.local_dof_indices,
3708 *   stokes_preconditioner_matrix);
3709 *   }
3710 *  
3711 *  
3712 * @endcode
3713 *
3714 * Now for the function that actually puts things together, using the
3715 * WorkStream functions. WorkStream::run needs a start and end iterator to
3716 * enumerate the cells it is supposed to work on. Typically, one would use
3717 * DoFHandler::begin_active() and DoFHandler::end() for that but here we
3718 * actually only want the subset of cells that in fact are owned by the
3719 * current processor. This is where the FilteredIterator class comes into
3720 * play: you give it a range of cells and it provides an iterator that only
3721 * iterates over that subset of cells that satisfy a certain predicate (a
3722 * predicate is a function of one argument that either returns true or
3723 * false). The predicate we use here is IteratorFilters::LocallyOwnedCell,
3724 * i.e., it returns true exactly if the cell is owned by the current
3725 * processor. The resulting iterator range is then exactly what we need.
3726 *
3727
3728 *
3729 * With this obstacle out of the way, we call the WorkStream::run
3730 * function with this set of cells, scratch and copy objects, and
3731 * with pointers to two functions: the local assembly and
3732 * copy-local-to-global function. These functions need to have very
3733 * specific signatures: three arguments in the first and one
3734 * argument in the latter case (see the documentation of the
3735 * WorkStream::run function for the meaning of these arguments).
3736 * Note how we use a lambda functions to
3737 * create a function object that satisfies this requirement. It uses
3738 * function arguments for the local assembly function that specify
3739 * cell, scratch data, and copy data, as well as function argument
3740 * for the copy function that expects the
3741 * data to be written into the global matrix (also see the discussion in
3742 * @ref step_13 "step-13"'s <code>assemble_linear_system()</code> function). On the other
3743 * hand, the implicit zeroth argument of member functions (namely
3744 * the <code>this</code> pointer of the object on which that member
3745 * function is to operate on) is <i>bound</i> to the
3746 * <code>this</code> pointer of the current function and is captured. The
3747 * WorkStream::run function, as a consequence, does not need to know
3748 * anything about the object these functions work on.
3749 *
3750
3751 *
3752 * When the WorkStream is executed, it will create several local assembly
3753 * routines of the first kind for several cells and let some available
3754 * processors work on them. The function that needs to be synchronized,
3755 * i.e., the write operation into the global matrix, however, is executed by
3756 * only one thread at a time in the prescribed order. Of course, this only
3757 * holds for the parallelization on a single MPI process. Different MPI
3758 * processes will have their own WorkStream objects and do that work
3759 * completely independently (and in different memory spaces). In a
3760 * distributed calculation, some data will accumulate at degrees of freedom
3761 * that are not owned by the respective processor. It would be inefficient
3762 * to send data around every time we encounter such a dof. What happens
3763 * instead is that the Trilinos sparse matrix will keep that data and send
3764 * it to the owner at the end of assembly, by calling the
3765 * <code>compress()</code> command.
3766 *
3767 * @code
3768 *   template <int dim>
3769 *   void BoussinesqFlowProblem<dim>::assemble_stokes_preconditioner()
3770 *   {
3771 *   stokes_preconditioner_matrix = 0;
3772 *  
3773 *   const QGauss<dim> quadrature_formula(parameters.stokes_velocity_degree + 1);
3774 *  
3775 *   using CellFilter =
3777 *  
3778 *   auto worker =
3779 *   [this](const typename DoFHandler<dim>::active_cell_iterator &cell,
3780 *   Assembly::Scratch::StokesPreconditioner<dim> &scratch,
3781 *   Assembly::CopyData::StokesPreconditioner<dim> &data) {
3782 *   this->local_assemble_stokes_preconditioner(cell, scratch, data);
3783 *   };
3784 *  
3785 *   auto copier =
3786 *   [this](const Assembly::CopyData::StokesPreconditioner<dim> &data) {
3787 *   this->copy_local_to_global_stokes_preconditioner(data);
3788 *   };
3789 *  
3791 *   stokes_dof_handler.begin_active()),
3792 *   CellFilter(IteratorFilters::LocallyOwnedCell(),
3793 *   stokes_dof_handler.end()),
3794 *   worker,
3795 *   copier,
3796 *   Assembly::Scratch::StokesPreconditioner<dim>(
3797 *   stokes_fe,
3798 *   quadrature_formula,
3799 *   mapping,
3801 *   Assembly::CopyData::StokesPreconditioner<dim>(stokes_fe));
3802 *  
3803 *   stokes_preconditioner_matrix.compress(VectorOperation::add);
3804 *   }
3805 *  
3806 *  
3807 *  
3808 * @endcode
3809 *
3810 * The final function in this block initiates assembly of the Stokes
3811 * preconditioner matrix and then in fact builds the Stokes
3812 * preconditioner. It is mostly the same as in the serial case. The only
3813 * difference to @ref step_31 "step-31" is that we use a Jacobi preconditioner for the
3814 * pressure mass matrix instead of IC, as discussed in the introduction.
3815 *
3816 * @code
3817 *   template <int dim>
3818 *   void BoussinesqFlowProblem<dim>::build_stokes_preconditioner()
3819 *   {
3820 *   if (rebuild_stokes_preconditioner == false)
3821 *   return;
3822 *  
3823 *   TimerOutput::Scope timer_section(computing_timer,
3824 *   " Build Stokes preconditioner");
3825 *   pcout << " Rebuilding Stokes preconditioner..." << std::flush;
3826 *  
3827 *   assemble_stokes_preconditioner();
3828 *  
3829 *   const FEValuesExtractors::Vector velocity_components(0);
3830 *   const std::vector<std::vector<bool>> constant_modes =
3832 *   stokes_dof_handler, stokes_fe.component_mask(velocity_components));
3833 *  
3834 *   Mp_preconditioner =
3835 *   std::make_shared<TrilinosWrappers::PreconditionJacobi>();
3836 *   Amg_preconditioner = std::make_shared<TrilinosWrappers::PreconditionAMG>();
3837 *  
3839 *   Amg_data.constant_modes = constant_modes;
3840 *   Amg_data.elliptic = true;
3841 *   Amg_data.higher_order_elements = true;
3842 *   Amg_data.smoother_sweeps = 2;
3843 *   Amg_data.aggregation_threshold = 0.02;
3844 *  
3845 *   Mp_preconditioner->initialize(stokes_preconditioner_matrix.block(1, 1));
3846 *   Amg_preconditioner->initialize(stokes_preconditioner_matrix.block(0, 0),
3847 *   Amg_data);
3848 *  
3849 *   rebuild_stokes_preconditioner = false;
3850 *  
3851 *   pcout << std::endl;
3852 *   }
3853 *  
3854 *  
3855 * @endcode
3856 *
3857 *
3858 * <a name="step_32-Stokessystemassembly"></a>
3859 * <h5>Stokes system assembly</h5>
3860 *
3861
3862 *
3863 * The next three functions implement the assembly of the Stokes system,
3864 * again split up into a part performing local calculations, one for writing
3865 * the local data into the global matrix and vector, and one for actually
3866 * running the loop over all cells with the help of the WorkStream
3867 * class. Note that the assembly of the Stokes matrix needs only to be done
3868 * in case we have changed the mesh. Otherwise, just the
3869 * (temperature-dependent) right hand side needs to be calculated
3870 * here. Since we are working with distributed matrices and vectors, we have
3871 * to call the respective <code>compress()</code> functions in the end of
3872 * the assembly in order to send non-local data to the owner process.
3873 *
3874 * @code
3875 *   template <int dim>
3876 *   void BoussinesqFlowProblem<dim>::local_assemble_stokes_system(
3877 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
3878 *   Assembly::Scratch::StokesSystem<dim> &scratch,
3879 *   Assembly::CopyData::StokesSystem<dim> &data)
3880 *   {
3881 *   const unsigned int dofs_per_cell =
3882 *   scratch.stokes_fe_values.get_fe().n_dofs_per_cell();
3883 *   const unsigned int n_q_points =
3884 *   scratch.stokes_fe_values.n_quadrature_points;
3885 *  
3886 *   const FEValuesExtractors::Vector velocities(0);
3887 *   const FEValuesExtractors::Scalar pressure(dim);
3888 *  
3889 *   scratch.stokes_fe_values.reinit(cell);
3890 *  
3891 *   const typename DoFHandler<dim>::active_cell_iterator temperature_cell =
3892 *   cell->as_dof_handler_iterator(temperature_dof_handler);
3893 *   scratch.temperature_fe_values.reinit(temperature_cell);
3894 *  
3895 *   if (rebuild_stokes_matrix)
3896 *   data.local_matrix = 0;
3897 *   data.local_rhs = 0;
3898 *  
3899 *   scratch.temperature_fe_values.get_function_values(
3900 *   old_temperature_solution, scratch.old_temperature_values);
3901 *  
3902 *   for (unsigned int q = 0; q < n_q_points; ++q)
3903 *   {
3904 *   const double old_temperature = scratch.old_temperature_values[q];
3905 *  
3906 *   for (unsigned int k = 0; k < dofs_per_cell; ++k)
3907 *   {
3908 *   scratch.phi_u[k] = scratch.stokes_fe_values[velocities].value(k, q);
3909 *   if (rebuild_stokes_matrix)
3910 *   {
3911 *   scratch.grads_phi_u[k] =
3912 *   scratch.stokes_fe_values[velocities].symmetric_gradient(k, q);
3913 *   scratch.div_phi_u[k] =
3914 *   scratch.stokes_fe_values[velocities].divergence(k, q);
3915 *   scratch.phi_p[k] =
3916 *   scratch.stokes_fe_values[pressure].value(k, q);
3917 *   }
3918 *   }
3919 *  
3920 *   if (rebuild_stokes_matrix == true)
3921 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
3922 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
3923 *   data.local_matrix(i, j) +=
3924 *   (EquationData::eta * 2 *
3925 *   (scratch.grads_phi_u[i] * scratch.grads_phi_u[j]) -
3926 *   (EquationData::pressure_scaling * scratch.div_phi_u[i] *
3927 *   scratch.phi_p[j]) -
3928 *   (EquationData::pressure_scaling * scratch.phi_p[i] *
3929 *   scratch.div_phi_u[j])) *
3930 *   scratch.stokes_fe_values.JxW(q);
3931 *  
3932 *   const Tensor<1, dim> gravity = EquationData::gravity_vector(
3933 *   scratch.stokes_fe_values.quadrature_point(q));
3934 *  
3935 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
3936 *   data.local_rhs(i) += (EquationData::density(old_temperature) *
3937 *   gravity * scratch.phi_u[i]) *
3938 *   scratch.stokes_fe_values.JxW(q);
3939 *   }
3940 *  
3941 *   cell->get_dof_indices(data.local_dof_indices);
3942 *   }
3943 *  
3944 *  
3945 *  
3946 *   template <int dim>
3947 *   void BoussinesqFlowProblem<dim>::copy_local_to_global_stokes_system(
3948 *   const Assembly::CopyData::StokesSystem<dim> &data)
3949 *   {
3950 *   if (rebuild_stokes_matrix == true)
3951 *   stokes_constraints.distribute_local_to_global(data.local_matrix,
3952 *   data.local_rhs,
3953 *   data.local_dof_indices,
3954 *   stokes_matrix,
3955 *   stokes_rhs);
3956 *   else
3957 *   stokes_constraints.distribute_local_to_global(data.local_rhs,
3958 *   data.local_dof_indices,
3959 *   stokes_rhs);
3960 *   }
3961 *  
3962 *  
3963 *  
3964 *   template <int dim>
3965 *   void BoussinesqFlowProblem<dim>::assemble_stokes_system()
3966 *   {
3967 *   TimerOutput::Scope timer_section(computing_timer,
3968 *   " Assemble Stokes system");
3969 *  
3970 *   if (rebuild_stokes_matrix == true)
3971 *   stokes_matrix = 0;
3972 *  
3973 *   stokes_rhs = 0;
3974 *  
3975 *   const QGauss<dim> quadrature_formula(parameters.stokes_velocity_degree + 1);
3976 *  
3977 *   using CellFilter =
3979 *  
3980 *   WorkStream::run(
3981 *   CellFilter(IteratorFilters::LocallyOwnedCell(),
3982 *   stokes_dof_handler.begin_active()),
3983 *   CellFilter(IteratorFilters::LocallyOwnedCell(), stokes_dof_handler.end()),
3984 *   [this](const typename DoFHandler<dim>::active_cell_iterator &cell,
3985 *   Assembly::Scratch::StokesSystem<dim> &scratch,
3986 *   Assembly::CopyData::StokesSystem<dim> &data) {
3987 *   this->local_assemble_stokes_system(cell, scratch, data);
3988 *   },
3989 *   [this](const Assembly::CopyData::StokesSystem<dim> &data) {
3990 *   this->copy_local_to_global_stokes_system(data);
3991 *   },
3992 *   Assembly::Scratch::StokesSystem<dim>(
3993 *   stokes_fe,
3994 *   mapping,
3995 *   quadrature_formula,
3997 *   (rebuild_stokes_matrix == true ? update_gradients : UpdateFlags(0))),
3998 *   temperature_fe,
3999 *   update_values),
4000 *   Assembly::CopyData::StokesSystem<dim>(stokes_fe));
4001 *  
4002 *   if (rebuild_stokes_matrix == true)
4003 *   stokes_matrix.compress(VectorOperation::add);
4004 *   stokes_rhs.compress(VectorOperation::add);
4005 *  
4006 *   rebuild_stokes_matrix = false;
4007 *  
4008 *   pcout << std::endl;
4009 *   }
4010 *  
4011 *  
4012 * @endcode
4013 *
4014 *
4015 * <a name="step_32-Temperaturematrixassembly"></a>
4016 * <h5>Temperature matrix assembly</h5>
4017 *
4018
4019 *
4020 * The task to be performed by the next three functions is to calculate a
4021 * mass matrix and a Laplace matrix on the temperature system. These will be
4022 * combined in order to yield the semi-implicit time stepping matrix that
4023 * consists of the mass matrix plus a time step-dependent weight factor
4024 * times the Laplace matrix. This function is again essentially the body of
4025 * the loop over all cells from @ref step_31 "step-31".
4026 *
4027
4028 *
4029 * The two following functions perform similar services as the ones above.
4030 *
4031 * @code
4032 *   template <int dim>
4033 *   void BoussinesqFlowProblem<dim>::local_assemble_temperature_matrix(
4034 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
4035 *   Assembly::Scratch::TemperatureMatrix<dim> &scratch,
4036 *   Assembly::CopyData::TemperatureMatrix<dim> &data)
4037 *   {
4038 *   const unsigned int dofs_per_cell =
4039 *   scratch.temperature_fe_values.get_fe().n_dofs_per_cell();
4040 *   const unsigned int n_q_points =
4041 *   scratch.temperature_fe_values.n_quadrature_points;
4042 *  
4043 *   scratch.temperature_fe_values.reinit(cell);
4044 *   cell->get_dof_indices(data.local_dof_indices);
4045 *  
4046 *   data.local_mass_matrix = 0;
4047 *   data.local_stiffness_matrix = 0;
4048 *  
4049 *   for (unsigned int q = 0; q < n_q_points; ++q)
4050 *   {
4051 *   for (unsigned int k = 0; k < dofs_per_cell; ++k)
4052 *   {
4053 *   scratch.grad_phi_T[k] =
4054 *   scratch.temperature_fe_values.shape_grad(k, q);
4055 *   scratch.phi_T[k] = scratch.temperature_fe_values.shape_value(k, q);
4056 *   }
4057 *  
4058 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
4059 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
4060 *   {
4061 *   data.local_mass_matrix(i, j) +=
4062 *   (scratch.phi_T[i] * scratch.phi_T[j] *
4063 *   scratch.temperature_fe_values.JxW(q));
4064 *   data.local_stiffness_matrix(i, j) +=
4065 *   (EquationData::kappa * scratch.grad_phi_T[i] *
4066 *   scratch.grad_phi_T[j] * scratch.temperature_fe_values.JxW(q));
4067 *   }
4068 *   }
4069 *   }
4070 *  
4071 *  
4072 *  
4073 *   template <int dim>
4074 *   void BoussinesqFlowProblem<dim>::copy_local_to_global_temperature_matrix(
4075 *   const Assembly::CopyData::TemperatureMatrix<dim> &data)
4076 *   {
4077 *   temperature_constraints.distribute_local_to_global(data.local_mass_matrix,
4078 *   data.local_dof_indices,
4079 *   temperature_mass_matrix);
4080 *   temperature_constraints.distribute_local_to_global(
4081 *   data.local_stiffness_matrix,
4082 *   data.local_dof_indices,
4083 *   temperature_stiffness_matrix);
4084 *   }
4085 *  
4086 *  
4087 *   template <int dim>
4088 *   void BoussinesqFlowProblem<dim>::assemble_temperature_matrix()
4089 *   {
4090 *   if (rebuild_temperature_matrices == false)
4091 *   return;
4092 *  
4093 *   TimerOutput::Scope timer_section(computing_timer,
4094 *   " Assemble temperature matrices");
4095 *   temperature_mass_matrix = 0;
4096 *   temperature_stiffness_matrix = 0;
4097 *  
4098 *   const QGauss<dim> quadrature_formula(parameters.temperature_degree + 2);
4099 *  
4100 *   using CellFilter =
4102 *  
4103 *   WorkStream::run(
4104 *   CellFilter(IteratorFilters::LocallyOwnedCell(),
4105 *   temperature_dof_handler.begin_active()),
4106 *   CellFilter(IteratorFilters::LocallyOwnedCell(),
4107 *   temperature_dof_handler.end()),
4108 *   [this](const typename DoFHandler<dim>::active_cell_iterator &cell,
4109 *   Assembly::Scratch::TemperatureMatrix<dim> &scratch,
4110 *   Assembly::CopyData::TemperatureMatrix<dim> &data) {
4111 *   this->local_assemble_temperature_matrix(cell, scratch, data);
4112 *   },
4113 *   [this](const Assembly::CopyData::TemperatureMatrix<dim> &data) {
4114 *   this->copy_local_to_global_temperature_matrix(data);
4115 *   },
4116 *   Assembly::Scratch::TemperatureMatrix<dim>(temperature_fe,
4117 *   mapping,
4118 *   quadrature_formula),
4119 *   Assembly::CopyData::TemperatureMatrix<dim>(temperature_fe));
4120 *  
4121 *   temperature_mass_matrix.compress(VectorOperation::add);
4122 *   temperature_stiffness_matrix.compress(VectorOperation::add);
4123 *  
4124 *   rebuild_temperature_matrices = false;
4125 *   rebuild_temperature_preconditioner = true;
4126 *   }
4127 *  
4128 *  
4129 * @endcode
4130 *
4131 *
4132 * <a name="step_32-Temperaturerighthandsideassembly"></a>
4133 * <h5>Temperature right hand side assembly</h5>
4134 *
4135
4136 *
4137 * This is the last assembly function. It calculates the right hand side of
4138 * the temperature system, which includes the convection and the
4139 * stabilization terms. It includes a lot of evaluations of old solutions at
4140 * the quadrature points (which are necessary for calculating the artificial
4141 * viscosity of stabilization), but is otherwise similar to the other
4142 * assembly functions. Notice, once again, how we resolve the dilemma of
4143 * having inhomogeneous boundary conditions, by just making a right hand
4144 * side at this point (compare the comments for the <code>project()</code>
4145 * function above): We create some matrix columns with exactly the values
4146 * that would be entered for the temperature @ref GlossStiffnessMatrix "stiffness matrix", in case we
4147 * have inhomogeneously constrained dofs. That will account for the correct
4148 * balance of the right hand side vector with the matrix system of
4149 * temperature.
4150 *
4151 * @code
4152 *   template <int dim>
4153 *   void BoussinesqFlowProblem<dim>::local_assemble_temperature_rhs(
4154 *   const std::pair<double, double> global_T_range,
4155 *   const double global_max_velocity,
4156 *   const double global_entropy_variation,
4157 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
4158 *   Assembly::Scratch::TemperatureRHS<dim> &scratch,
4159 *   Assembly::CopyData::TemperatureRHS<dim> &data)
4160 *   {
4161 *   const bool use_bdf2_scheme = (timestep_number != 0);
4162 *  
4163 *   const unsigned int dofs_per_cell =
4164 *   scratch.temperature_fe_values.get_fe().n_dofs_per_cell();
4165 *   const unsigned int n_q_points =
4166 *   scratch.temperature_fe_values.n_quadrature_points;
4167 *  
4168 *   const FEValuesExtractors::Vector velocities(0);
4169 *  
4170 *   data.local_rhs = 0;
4171 *   data.matrix_for_bc = 0;
4172 *   cell->get_dof_indices(data.local_dof_indices);
4173 *  
4174 *   scratch.temperature_fe_values.reinit(cell);
4175 *  
4176 *   typename DoFHandler<dim>::active_cell_iterator stokes_cell =
4177 *   cell->as_dof_handler_iterator(stokes_dof_handler);
4178 *   scratch.stokes_fe_values.reinit(stokes_cell);
4179 *  
4180 *   scratch.temperature_fe_values.get_function_values(
4181 *   old_temperature_solution, scratch.old_temperature_values);
4182 *   scratch.temperature_fe_values.get_function_values(
4183 *   old_old_temperature_solution, scratch.old_old_temperature_values);
4184 *  
4185 *   scratch.temperature_fe_values.get_function_gradients(
4186 *   old_temperature_solution, scratch.old_temperature_grads);
4187 *   scratch.temperature_fe_values.get_function_gradients(
4188 *   old_old_temperature_solution, scratch.old_old_temperature_grads);
4189 *  
4190 *   scratch.temperature_fe_values.get_function_laplacians(
4191 *   old_temperature_solution, scratch.old_temperature_laplacians);
4192 *   scratch.temperature_fe_values.get_function_laplacians(
4193 *   old_old_temperature_solution, scratch.old_old_temperature_laplacians);
4194 *  
4195 *   scratch.stokes_fe_values[velocities].get_function_values(
4196 *   stokes_solution, scratch.old_velocity_values);
4197 *   scratch.stokes_fe_values[velocities].get_function_values(
4198 *   old_stokes_solution, scratch.old_old_velocity_values);
4199 *   scratch.stokes_fe_values[velocities].get_function_symmetric_gradients(
4200 *   stokes_solution, scratch.old_strain_rates);
4201 *   scratch.stokes_fe_values[velocities].get_function_symmetric_gradients(
4202 *   old_stokes_solution, scratch.old_old_strain_rates);
4203 *  
4204 *   const double nu =
4205 *   compute_viscosity(scratch.old_temperature_values,
4206 *   scratch.old_old_temperature_values,
4207 *   scratch.old_temperature_grads,
4208 *   scratch.old_old_temperature_grads,
4209 *   scratch.old_temperature_laplacians,
4210 *   scratch.old_old_temperature_laplacians,
4211 *   scratch.old_velocity_values,
4212 *   scratch.old_old_velocity_values,
4213 *   scratch.old_strain_rates,
4214 *   scratch.old_old_strain_rates,
4215 *   global_max_velocity,
4216 *   global_T_range.second - global_T_range.first,
4217 *   0.5 * (global_T_range.second + global_T_range.first),
4218 *   global_entropy_variation,
4219 *   cell->diameter());
4220 *  
4221 *   for (unsigned int q = 0; q < n_q_points; ++q)
4222 *   {
4223 *   for (unsigned int k = 0; k < dofs_per_cell; ++k)
4224 *   {
4225 *   scratch.phi_T[k] = scratch.temperature_fe_values.shape_value(k, q);
4226 *   scratch.grad_phi_T[k] =
4227 *   scratch.temperature_fe_values.shape_grad(k, q);
4228 *   }
4229 *  
4230 *  
4231 *   const double T_term_for_rhs =
4232 *   (use_bdf2_scheme ?
4233 *   (scratch.old_temperature_values[q] *
4234 *   (1 + time_step / old_time_step) -
4235 *   scratch.old_old_temperature_values[q] * (time_step * time_step) /
4236 *   (old_time_step * (time_step + old_time_step))) :
4237 *   scratch.old_temperature_values[q]);
4238 *  
4239 *   const double ext_T =
4240 *   (use_bdf2_scheme ? (scratch.old_temperature_values[q] *
4241 *   (1 + time_step / old_time_step) -
4242 *   scratch.old_old_temperature_values[q] *
4243 *   time_step / old_time_step) :
4244 *   scratch.old_temperature_values[q]);
4245 *  
4246 *   const Tensor<1, dim> ext_grad_T =
4247 *   (use_bdf2_scheme ? (scratch.old_temperature_grads[q] *
4248 *   (1 + time_step / old_time_step) -
4249 *   scratch.old_old_temperature_grads[q] * time_step /
4250 *   old_time_step) :
4251 *   scratch.old_temperature_grads[q]);
4252 *  
4253 *   const Tensor<1, dim> extrapolated_u =
4254 *   (use_bdf2_scheme ?
4255 *   (scratch.old_velocity_values[q] * (1 + time_step / old_time_step) -
4256 *   scratch.old_old_velocity_values[q] * time_step / old_time_step) :
4257 *   scratch.old_velocity_values[q]);
4258 *  
4259 *   const SymmetricTensor<2, dim> extrapolated_strain_rate =
4260 *   (use_bdf2_scheme ?
4261 *   (scratch.old_strain_rates[q] * (1 + time_step / old_time_step) -
4262 *   scratch.old_old_strain_rates[q] * time_step / old_time_step) :
4263 *   scratch.old_strain_rates[q]);
4264 *  
4265 *   const double gamma =
4266 *   ((EquationData::radiogenic_heating * EquationData::density(ext_T) +
4267 *   2 * EquationData::eta * extrapolated_strain_rate *
4268 *   extrapolated_strain_rate) /
4269 *   (EquationData::density(ext_T) * EquationData::specific_heat));
4270 *  
4271 *   for (unsigned int i = 0; i < dofs_per_cell; ++i)
4272 *   {
4273 *   data.local_rhs(i) +=
4274 *   (T_term_for_rhs * scratch.phi_T[i] -
4275 *   time_step * extrapolated_u * ext_grad_T * scratch.phi_T[i] -
4276 *   time_step * nu * ext_grad_T * scratch.grad_phi_T[i] +
4277 *   time_step * gamma * scratch.phi_T[i]) *
4278 *   scratch.temperature_fe_values.JxW(q);
4279 *  
4280 *   if (temperature_constraints.is_inhomogeneously_constrained(
4281 *   data.local_dof_indices[i]))
4282 *   {
4283 *   for (unsigned int j = 0; j < dofs_per_cell; ++j)
4284 *   data.matrix_for_bc(j, i) +=
4285 *   (scratch.phi_T[i] * scratch.phi_T[j] *
4286 *   (use_bdf2_scheme ? ((2 * time_step + old_time_step) /
4287 *   (time_step + old_time_step)) :
4288 *   1.) +
4289 *   scratch.grad_phi_T[i] * scratch.grad_phi_T[j] *
4290 *   EquationData::kappa * time_step) *
4291 *   scratch.temperature_fe_values.JxW(q);
4292 *   }
4293 *   }
4294 *   }
4295 *   }
4296 *  
4297 *  
4298 *   template <int dim>
4299 *   void BoussinesqFlowProblem<dim>::copy_local_to_global_temperature_rhs(
4300 *   const Assembly::CopyData::TemperatureRHS<dim> &data)
4301 *   {
4302 *   temperature_constraints.distribute_local_to_global(data.local_rhs,
4303 *   data.local_dof_indices,
4304 *   temperature_rhs,
4305 *   data.matrix_for_bc);
4306 *   }
4307 *  
4308 *  
4309 *  
4310 * @endcode
4311 *
4312 * In the function that runs the WorkStream for actually calculating the
4313 * right hand side, we also generate the final matrix. As mentioned above,
4314 * it is a sum of the mass matrix and the Laplace matrix, times some time
4315 * step-dependent weight. This weight is specified by the BDF-2 time
4316 * integration scheme, see the introduction in @ref step_31 "step-31". What is new in this
4317 * tutorial program (in addition to the use of MPI parallelization and the
4318 * WorkStream class), is that we now precompute the temperature
4319 * preconditioner as well. The reason is that the setup of the Jacobi
4320 * preconditioner takes a noticeable time compared to the solver because we
4321 * usually only need between 10 and 20 iterations for solving the
4322 * temperature system (this might sound strange, as Jacobi really only
4323 * consists of a diagonal, but in Trilinos it is derived from more general
4324 * framework for point relaxation preconditioners which is a bit
4325 * inefficient). Hence, it is more efficient to precompute the
4326 * preconditioner, even though the matrix entries may slightly change
4327 * because the time step might change. This is not too big a problem because
4328 * we remesh every few time steps (and regenerate the preconditioner then).
4329 *
4330 * @code
4331 *   template <int dim>
4332 *   void BoussinesqFlowProblem<dim>::assemble_temperature_system(
4333 *   const double maximal_velocity)
4334 *   {
4335 *   const bool use_bdf2_scheme = (timestep_number != 0);
4336 *  
4337 *   if (use_bdf2_scheme == true)
4338 *   {
4339 *   temperature_matrix.copy_from(temperature_mass_matrix);
4340 *   temperature_matrix *=
4341 *   (2 * time_step + old_time_step) / (time_step + old_time_step);
4342 *   temperature_matrix.add(time_step, temperature_stiffness_matrix);
4343 *   }
4344 *   else
4345 *   {
4346 *   temperature_matrix.copy_from(temperature_mass_matrix);
4347 *   temperature_matrix.add(time_step, temperature_stiffness_matrix);
4348 *   }
4349 *  
4350 *   if (rebuild_temperature_preconditioner == true)
4351 *   {
4352 *   T_preconditioner =
4353 *   std::make_shared<TrilinosWrappers::PreconditionJacobi>();
4354 *   T_preconditioner->initialize(temperature_matrix);
4355 *   rebuild_temperature_preconditioner = false;
4356 *   }
4357 *  
4358 * @endcode
4359 *
4360 * The next part is computing the right hand side vectors. To do so, we
4361 * first compute the average temperature @f$T_m@f$ that we use for evaluating
4362 * the artificial viscosity stabilization through the residual @f$E(T) =
4363 * (T-T_m)^2@f$. We do this by defining the midpoint between maximum and
4364 * minimum temperature as average temperature in the definition of the
4365 * entropy viscosity. An alternative would be to use the integral average,
4366 * but the results are not very sensitive to this choice. The rest then
4367 * only requires calling WorkStream::run again, binding the arguments to
4368 * the <code>local_assemble_temperature_rhs</code> function that are the
4369 * same in every call to the correct values:
4370 *
4371 * @code
4372 *   temperature_rhs = 0;
4373 *  
4374 *   const QGauss<dim> quadrature_formula(parameters.temperature_degree + 2);
4375 *   const std::pair<double, double> global_T_range =
4376 *   get_extrapolated_temperature_range();
4377 *  
4378 *   const double average_temperature =
4379 *   0.5 * (global_T_range.first + global_T_range.second);
4380 *   const double global_entropy_variation =
4381 *   get_entropy_variation(average_temperature);
4382 *  
4383 *   using CellFilter =
4385 *  
4386 *   auto worker =
4387 *   [this, global_T_range, maximal_velocity, global_entropy_variation](
4388 *   const typename DoFHandler<dim>::active_cell_iterator &cell,
4389 *   Assembly::Scratch::TemperatureRHS<dim> &scratch,
4390 *   Assembly::CopyData::TemperatureRHS<dim> &data) {
4391 *   this->local_assemble_temperature_rhs(global_T_range,
4392 *   maximal_velocity,
4393 *   global_entropy_variation,
4394 *   cell,
4395 *   scratch,
4396 *   data);
4397 *   };
4398 *  
4399 *   auto copier = [this](const Assembly::CopyData::TemperatureRHS<dim> &data) {
4400 *   this->copy_local_to_global_temperature_rhs(data);
4401 *   };
4402 *  
4404 *   temperature_dof_handler.begin_active()),
4405 *   CellFilter(IteratorFilters::LocallyOwnedCell(),
4406 *   temperature_dof_handler.end()),
4407 *   worker,
4408 *   copier,
4409 *   Assembly::Scratch::TemperatureRHS<dim>(
4410 *   temperature_fe, stokes_fe, mapping, quadrature_formula),
4411 *   Assembly::CopyData::TemperatureRHS<dim>(temperature_fe));
4412 *  
4413 *   temperature_rhs.compress(VectorOperation::add);
4414 *   }
4415 *  
4416 *  
4417 *  
4418 * @endcode
4419 *
4420 *
4421 * <a name="step_32-BoussinesqFlowProblemsolve"></a>
4422 * <h4>BoussinesqFlowProblem::solve</h4>
4423 *
4424
4425 *
4426 * This function solves the linear systems in each time step of the
4427 * Boussinesq problem. First, we work on the Stokes system and then on the
4428 * temperature system. In essence, it does the same things as the respective
4429 * function in @ref step_31 "step-31". However, there are a few changes here.
4430 *
4431
4432 *
4433 * The first change is related to the way we store our solution: we keep the
4434 * vectors with locally owned degrees of freedom plus ghost nodes on each
4435 * MPI node. When we enter a solver which is supposed to perform
4436 * matrix-vector products with a distributed matrix, this is not the
4437 * appropriate form, though. There, we will want to have the solution vector
4438 * to be distributed in the same way as the matrix, i.e. without any
4439 * ghosts. So what we do first is to generate a distributed vector called
4440 * <code>distributed_stokes_solution</code> and put only the locally owned
4441 * dofs into that, which is neatly done by the <code>operator=</code> of the
4442 * Trilinos vector.
4443 *
4444
4445 *
4446 * Next, we scale the pressure solution (or rather, the initial guess) for
4447 * the solver so that it matches with the length scales in the matrices, as
4448 * discussed in the introduction. We also immediately scale the pressure
4449 * solution back to the correct units after the solution is completed. We
4450 * also need to set the pressure values at hanging nodes to zero. This we
4451 * also did in @ref step_31 "step-31" in order not to disturb the Schur complement by some
4452 * vector entries that actually are irrelevant during the solve stage. As a
4453 * difference to @ref step_31 "step-31", here we do it only for the locally owned pressure
4454 * dofs. After solving for the Stokes solution, each processor copies the
4455 * distributed solution back into the solution vector that also includes
4456 * ghost elements.
4457 *
4458
4459 *
4460 * The third and most obvious change is that we have two variants for the
4461 * Stokes solver: A fast solver that sometimes breaks down, and a robust
4462 * solver that is slower. This is what we already discussed in the
4463 * introduction. Here is how we realize it: First, we perform 30 iterations
4464 * with the fast solver based on the simple preconditioner based on the AMG
4465 * V-cycle instead of an approximate solve (this is indicated by the
4466 * <code>false</code> argument to the
4467 * <code>LinearSolvers::BlockSchurPreconditioner</code> object). If we
4468 * converge, everything is fine. If we do not converge, the solver control
4469 * object will throw an exception SolverControl::NoConvergence. Usually,
4470 * this would abort the program because we don't catch them in our usual
4471 * <code>solve()</code> functions. This is certainly not what we want to
4472 * happen here. Rather, we want to switch to the strong solver and continue
4473 * the solution process with whatever vector we got so far. Hence, we catch
4474 * the exception with the C++ try/catch mechanism. We then simply go through
4475 * the same solver sequence again in the <code>catch</code> clause, this
4476 * time passing the @p true flag to the preconditioner for the strong
4477 * solver, signaling an approximate CG solve.
4478 *
4479 * @code
4480 *   template <int dim>
4481 *   void BoussinesqFlowProblem<dim>::solve()
4482 *   {
4483 *   {
4484 *   TimerOutput::Scope timer_section(computing_timer,
4485 *   " Solve Stokes system");
4486 *  
4487 *   pcout << " Solving Stokes system... " << std::flush;
4488 *  
4489 *   TrilinosWrappers::MPI::BlockVector distributed_stokes_solution(
4490 *   stokes_rhs);
4491 *   distributed_stokes_solution = stokes_solution;
4492 *  
4493 *   distributed_stokes_solution.block(1) /= EquationData::pressure_scaling;
4494 *  
4495 *   const unsigned int
4496 *   start = (distributed_stokes_solution.block(0).size() +
4497 *   distributed_stokes_solution.block(1).local_range().first),
4498 *   end = (distributed_stokes_solution.block(0).size() +
4499 *   distributed_stokes_solution.block(1).local_range().second);
4500 *   for (unsigned int i = start; i < end; ++i)
4501 *   if (stokes_constraints.is_constrained(i))
4502 *   distributed_stokes_solution(i) = 0;
4503 *  
4504 *  
4505 *   PrimitiveVectorMemory<TrilinosWrappers::MPI::BlockVector> mem;
4506 *  
4507 *   unsigned int n_iterations = 0;
4508 *   const double solver_tolerance = 1e-8 * stokes_rhs.l2_norm();
4509 *   SolverControl solver_control(30, solver_tolerance);
4510 *  
4511 *   try
4512 *   {
4513 *   const LinearSolvers::BlockSchurPreconditioner<
4514 *   TrilinosWrappers::PreconditionAMG,
4515 *   TrilinosWrappers::PreconditionJacobi>
4516 *   preconditioner(stokes_matrix,
4517 *   stokes_preconditioner_matrix,
4518 *   *Mp_preconditioner,
4519 *   *Amg_preconditioner,
4520 *   false);
4521 *  
4522 *   SolverFGMRES<TrilinosWrappers::MPI::BlockVector> solver(
4523 *   solver_control,
4524 *   mem,
4525 *   SolverFGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData(
4526 *   30));
4527 *   solver.solve(stokes_matrix,
4528 *   distributed_stokes_solution,
4529 *   stokes_rhs,
4530 *   preconditioner);
4531 *  
4532 *   n_iterations = solver_control.last_step();
4533 *   }
4534 *  
4535 *   catch (SolverControl::NoConvergence &)
4536 *   {
4537 *   const LinearSolvers::BlockSchurPreconditioner<
4538 *   TrilinosWrappers::PreconditionAMG,
4539 *   TrilinosWrappers::PreconditionJacobi>
4540 *   preconditioner(stokes_matrix,
4541 *   stokes_preconditioner_matrix,
4542 *   *Mp_preconditioner,
4543 *   *Amg_preconditioner,
4544 *   true);
4545 *  
4546 *   SolverControl solver_control_refined(stokes_matrix.m(),
4547 *   solver_tolerance);
4548 *   SolverFGMRES<TrilinosWrappers::MPI::BlockVector> solver(
4549 *   solver_control_refined,
4550 *   mem,
4551 *   SolverFGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData(
4552 *   50));
4553 *   solver.solve(stokes_matrix,
4554 *   distributed_stokes_solution,
4555 *   stokes_rhs,
4556 *   preconditioner);
4557 *  
4558 *   n_iterations =
4559 *   (solver_control.last_step() + solver_control_refined.last_step());
4560 *   }
4561 *  
4562 *  
4563 *   stokes_constraints.distribute(distributed_stokes_solution);
4564 *  
4565 *   distributed_stokes_solution.block(1) *= EquationData::pressure_scaling;
4566 *  
4567 *   stokes_solution = distributed_stokes_solution;
4568 *   pcout << n_iterations << " iterations." << std::endl;
4569 *   }
4570 *  
4571 *  
4572 * @endcode
4573 *
4574 * Now let's turn to the temperature part: First, we compute the time step
4575 * size. We found that we need smaller time steps for 3d than for 2d for
4576 * the shell geometry. This is because the cells are more distorted in
4577 * that case (it is the smallest edge length that determines the CFL
4578 * number). Instead of computing the time step from maximum velocity and
4579 * minimal mesh size as in @ref step_31 "step-31", we compute local CFL numbers, i.e., on
4580 * each cell we compute the maximum velocity times the mesh size, and
4581 * compute the maximum of them. Hence, we need to choose the factor in
4582 * front of the time step slightly smaller. (We later re-considered this
4583 * approach towards time stepping. If you're curious about this, you may
4584 * want to read the time stepping section in @cite HDGB17 .)
4585 *
4586
4587 *
4588 * After temperature right hand side assembly, we solve the linear
4589 * system for temperature (with fully distributed vectors without
4590 * ghost elements and using the solution from the last timestep as
4591 * our initial guess for the iterative solver), apply constraints,
4592 * and copy the vector back to one with ghosts.
4593 *
4594
4595 *
4596 * In the end, we extract the temperature range similarly to @ref step_31 "step-31" to
4597 * produce some output (for example in order to help us choose the
4598 * stabilization constants, as discussed in the introduction). The only
4599 * difference is that we need to exchange maxima over all processors.
4600 *
4601 * @code
4602 *   {
4603 *   TimerOutput::Scope timer_section(computing_timer,
4604 *   " Assemble temperature rhs");
4605 *  
4606 *   old_time_step = time_step;
4607 *  
4608 *   const double scaling = (dim == 3 ? 0.25 : 1.0);
4609 *   time_step = (scaling / (2.1 * dim * std::sqrt(1. * dim)) /
4610 *   (parameters.temperature_degree * get_cfl_number()));
4611 *  
4612 *   const double maximal_velocity = get_maximal_velocity();
4613 *   pcout << " Maximal velocity: "
4614 *   << maximal_velocity * EquationData::year_in_seconds * 100
4615 *   << " cm/year" << std::endl;
4616 *   pcout << " "
4617 *   << "Time step: " << time_step / EquationData::year_in_seconds
4618 *   << " years" << std::endl;
4619 *  
4620 *   assemble_temperature_system(maximal_velocity);
4621 *   }
4622 *  
4623 *   {
4624 *   TimerOutput::Scope timer_section(computing_timer,
4625 *   " Solve temperature system");
4626 *  
4627 *   SolverControl solver_control(temperature_matrix.m(),
4628 *   1e-12 * temperature_rhs.l2_norm());
4629 *   SolverCG<TrilinosWrappers::MPI::Vector> cg(solver_control);
4630 *  
4631 *   TrilinosWrappers::MPI::Vector distributed_temperature_solution(
4632 *   temperature_rhs);
4633 *   distributed_temperature_solution = old_temperature_solution;
4634 *  
4635 *   cg.solve(temperature_matrix,
4636 *   distributed_temperature_solution,
4637 *   temperature_rhs,
4638 *   *T_preconditioner);
4639 *  
4640 *   temperature_constraints.distribute(distributed_temperature_solution);
4641 *   temperature_solution = distributed_temperature_solution;
4642 *  
4643 *   pcout << " " << solver_control.last_step()
4644 *   << " CG iterations for temperature" << std::endl;
4645 *  
4646 *   double temperature[2] = {std::numeric_limits<double>::max(),
4647 *   -std::numeric_limits<double>::max()};
4648 *   double global_temperature[2];
4649 *  
4650 *   for (unsigned int i =
4651 *   distributed_temperature_solution.local_range().first;
4652 *   i < distributed_temperature_solution.local_range().second;
4653 *   ++i)
4654 *   {
4655 *   temperature[0] =
4656 *   std::min<double>(temperature[0],
4657 *   distributed_temperature_solution(i));
4658 *   temperature[1] =
4659 *   std::max<double>(temperature[1],
4660 *   distributed_temperature_solution(i));
4661 *   }
4662 *  
4663 *   temperature[0] *= -1.0;
4664 *   Utilities::MPI::max(temperature, MPI_COMM_WORLD, global_temperature);
4665 *   global_temperature[0] *= -1.0;
4666 *  
4667 *   pcout << " Temperature range: " << global_temperature[0] << ' '
4668 *   << global_temperature[1] << std::endl;
4669 *   }
4670 *   }
4671 *  
4672 *  
4673 * @endcode
4674 *
4675 *
4676 * <a name="step_32-BoussinesqFlowProblemoutput_results"></a>
4677 * <h4>BoussinesqFlowProblem::output_results</h4>
4678 *
4679
4680 *
4681 * Next comes the function that generates the output. The quantities to
4682 * output could be introduced manually like we did in @ref step_31 "step-31". An
4683 * alternative is to hand this task over to a class PostProcessor that
4684 * inherits from the class DataPostprocessor, which can be attached to
4685 * DataOut. This allows us to output derived quantities from the solution,
4686 * like the friction heating included in this example. It overloads the
4687 * virtual function DataPostprocessor::evaluate_vector_field(),
4688 * which is then internally called from DataOut::build_patches(). We have to
4689 * give it values of the numerical solution, its derivatives, normals to the
4690 * cell, the actual evaluation points and any additional quantities. This
4691 * follows the same procedure as discussed in @ref step_29 "step-29" and other programs.
4692 *
4693 * @code
4694 *   template <int dim>
4695 *   class BoussinesqFlowProblem<dim>::Postprocessor
4696 *   : public DataPostprocessor<dim>
4697 *   {
4698 *   public:
4699 *   Postprocessor(const unsigned int partition, const double minimal_pressure);
4700 *  
4701 *   virtual void evaluate_vector_field(
4702 *   const DataPostprocessorInputs::Vector<dim> &inputs,
4703 *   std::vector<Vector<double>> &computed_quantities) const override;
4704 *  
4705 *   virtual std::vector<std::string> get_names() const override;
4706 *  
4707 *   virtual std::vector<
4708 *   DataComponentInterpretation::DataComponentInterpretation>
4709 *   get_data_component_interpretation() const override;
4710 *  
4711 *   virtual UpdateFlags get_needed_update_flags() const override;
4712 *  
4713 *   private:
4714 *   const unsigned int partition;
4715 *   const double minimal_pressure;
4716 *   };
4717 *  
4718 *  
4719 *   template <int dim>
4720 *   BoussinesqFlowProblem<dim>::Postprocessor::Postprocessor(
4721 *   const unsigned int partition,
4722 *   const double minimal_pressure)
4723 *   : partition(partition)
4724 *   , minimal_pressure(minimal_pressure)
4725 *   {}
4726 *  
4727 *  
4728 * @endcode
4729 *
4730 * Here we define the names for the variables we want to output. These are
4731 * the actual solution values for velocity, pressure, and temperature, as
4732 * well as the friction heating and to each cell the number of the processor
4733 * that owns it. This allows us to visualize the partitioning of the domain
4734 * among the processors. Except for the velocity, which is vector-valued,
4735 * all other quantities are scalar.
4736 *
4737 * @code
4738 *   template <int dim>
4739 *   std::vector<std::string>
4740 *   BoussinesqFlowProblem<dim>::Postprocessor::get_names() const
4741 *   {
4742 *   std::vector<std::string> solution_names(dim, "velocity");
4743 *   solution_names.emplace_back("p");
4744 *   solution_names.emplace_back("T");
4745 *   solution_names.emplace_back("friction_heating");
4746 *   solution_names.emplace_back("partition");
4747 *  
4748 *   return solution_names;
4749 *   }
4750 *  
4751 *  
4752 *   template <int dim>
4753 *   std::vector<DataComponentInterpretation::DataComponentInterpretation>
4754 *   BoussinesqFlowProblem<dim>::Postprocessor::get_data_component_interpretation()
4755 *   const
4756 *   {
4757 *   std::vector<DataComponentInterpretation::DataComponentInterpretation>
4758 *   interpretation(dim,
4759 *   DataComponentInterpretation::component_is_part_of_vector);
4760 *  
4761 *   interpretation.push_back(DataComponentInterpretation::component_is_scalar);
4762 *   interpretation.push_back(DataComponentInterpretation::component_is_scalar);
4763 *   interpretation.push_back(DataComponentInterpretation::component_is_scalar);
4764 *   interpretation.push_back(DataComponentInterpretation::component_is_scalar);
4765 *  
4766 *   return interpretation;
4767 *   }
4768 *  
4769 *  
4770 *   template <int dim>
4771 *   UpdateFlags
4772 *   BoussinesqFlowProblem<dim>::Postprocessor::get_needed_update_flags() const
4773 *   {
4774 *   return update_values | update_gradients | update_quadrature_points;
4775 *   }
4776 *  
4777 *  
4778 * @endcode
4779 *
4780 * Now we implement the function that computes the derived quantities. As we
4781 * also did for the output, we rescale the velocity from its SI units to
4782 * something more readable, namely cm/year. Next, the pressure is scaled to
4783 * be between 0 and the maximum pressure. This makes it more easily
4784 * comparable -- in essence making all pressure variables positive or
4785 * zero. Temperature is taken as is, and the friction heating is computed as
4786 * @f$2 \eta \varepsilon(\mathbf{u}) \cdot \varepsilon(\mathbf{u})@f$.
4787 *
4788
4789 *
4790 * The quantities we output here are more for illustration, rather than for
4791 * actual scientific value. We come back to this briefly in the results
4792 * section of this program and explain what one may in fact be interested in.
4793 *
4794 * @code
4795 *   template <int dim>
4796 *   void BoussinesqFlowProblem<dim>::Postprocessor::evaluate_vector_field(
4797 *   const DataPostprocessorInputs::Vector<dim> &inputs,
4798 *   std::vector<Vector<double>> &computed_quantities) const
4799 *   {
4800 *   const unsigned int n_evaluation_points = inputs.solution_values.size();
4801 *   Assert(inputs.solution_gradients.size() == n_evaluation_points,
4802 *   ExcInternalError());
4803 *   Assert(computed_quantities.size() == n_evaluation_points,
4804 *   ExcInternalError());
4805 *   Assert(inputs.solution_values[0].size() == dim + 2, ExcInternalError());
4806 *  
4807 *   for (unsigned int p = 0; p < n_evaluation_points; ++p)
4808 *   {
4809 *   for (unsigned int d = 0; d < dim; ++d)
4810 *   computed_quantities[p](d) = (inputs.solution_values[p](d) *
4811 *   EquationData::year_in_seconds * 100);
4812 *  
4813 *   const double pressure =
4814 *   (inputs.solution_values[p](dim) - minimal_pressure);
4815 *   computed_quantities[p](dim) = pressure;
4816 *  
4817 *   const double temperature = inputs.solution_values[p](dim + 1);
4818 *   computed_quantities[p](dim + 1) = temperature;
4819 *  
4820 *   Tensor<2, dim> grad_u;
4821 *   for (unsigned int d = 0; d < dim; ++d)
4822 *   grad_u[d] = inputs.solution_gradients[p][d];
4823 *   const SymmetricTensor<2, dim> strain_rate = symmetrize(grad_u);
4824 *   computed_quantities[p](dim + 2) =
4825 *   2 * EquationData::eta * strain_rate * strain_rate;
4826 *  
4827 *   computed_quantities[p](dim + 3) = partition;
4828 *   }
4829 *   }
4830 *  
4831 *  
4832 * @endcode
4833 *
4834 * The <code>output_results()</code> function has a similar task to the one
4835 * in @ref step_31 "step-31". However, here we are going to demonstrate a different
4836 * technique on how to merge output from different DoFHandler objects. The
4837 * way we're going to achieve this recombination is to create a joint
4838 * DoFHandler that collects both components, the Stokes solution and the
4839 * temperature solution. This can be nicely done by combining the finite
4840 * elements from the two systems to form one FESystem, and let this
4841 * collective system define a new DoFHandler object. To be sure that
4842 * everything was done correctly, we perform a sanity check that ensures
4843 * that we got all the dofs from both Stokes and temperature even in the
4844 * combined system. We then combine the data vectors. Unfortunately, there
4845 * is no straight-forward relation that tells us how to sort Stokes and
4846 * temperature vector into the joint vector. The way we can get around this
4847 * trouble is to rely on the information collected in the FESystem. For each
4848 * dof on a cell, the joint finite element knows to which equation component
4849 * (velocity component, pressure, or temperature) it belongs – that's the
4850 * information we need! So we step through all cells (with iterators into
4851 * all three DoFHandlers moving in sync), and for each joint cell dof, we
4852 * read out that component using the FiniteElement::system_to_base_index
4853 * function (see there for a description of what the various parts of its
4854 * return value contain). We also need to keep track whether we're on a
4855 * Stokes dof or a temperature dof, which is contained in
4856 * joint_fe.system_to_base_index(i).first.first. Eventually, the dof_indices
4857 * data structures on either of the three systems tell us how the relation
4858 * between global vector and local dofs looks like on the present cell,
4859 * which concludes this tedious work. We make sure that each processor only
4860 * works on the subdomain it owns locally (and not on ghost or artificial
4861 * cells) when building the joint solution vector. The same will then have
4862 * to be done in DataOut::build_patches(), but that function does so
4863 * automatically.
4864 *
4865
4866 *
4867 * What we end up with is a set of patches that we can write using the
4868 * functions in DataOutBase in a variety of output formats. Here, we then
4869 * have to pay attention that what each processor writes is really only its
4870 * own part of the domain, i.e. we will want to write each processor's
4871 * contribution into a separate file. This we do by adding an additional
4872 * number to the filename when we write the solution. This is not really
4873 * new, we did it similarly in @ref step_40 "step-40". Note that we write in the compressed
4874 * format @p .vtu instead of plain vtk files, which saves quite some
4875 * storage.
4876 *
4877
4878 *
4879 * All the rest of the work is done in the PostProcessor class.
4880 *
4881 * @code
4882 *   template <int dim>
4883 *   void BoussinesqFlowProblem<dim>::output_results()
4884 *   {
4885 *   TimerOutput::Scope timer_section(computing_timer, "Postprocessing");
4886 *  
4887 *   const FESystem<dim> joint_fe(stokes_fe, 1, temperature_fe, 1);
4888 *  
4889 *   DoFHandler<dim> joint_dof_handler(triangulation);
4890 *   joint_dof_handler.distribute_dofs(joint_fe);
4891 *   Assert(joint_dof_handler.n_dofs() ==
4892 *   stokes_dof_handler.n_dofs() + temperature_dof_handler.n_dofs(),
4893 *   ExcInternalError());
4894 *  
4895 *   TrilinosWrappers::MPI::Vector joint_solution;
4896 *   joint_solution.reinit(joint_dof_handler.locally_owned_dofs(),
4897 *   MPI_COMM_WORLD);
4898 *  
4899 *   {
4900 *   std::vector<types::global_dof_index> local_joint_dof_indices(
4901 *   joint_fe.n_dofs_per_cell());
4902 *   std::vector<types::global_dof_index> local_stokes_dof_indices(
4903 *   stokes_fe.n_dofs_per_cell());
4904 *   std::vector<types::global_dof_index> local_temperature_dof_indices(
4905 *   temperature_fe.n_dofs_per_cell());
4906 *  
4907 *   typename DoFHandler<dim>::active_cell_iterator
4908 *   joint_cell = joint_dof_handler.begin_active(),
4909 *   joint_endc = joint_dof_handler.end(),
4910 *   stokes_cell = stokes_dof_handler.begin_active(),
4911 *   temperature_cell = temperature_dof_handler.begin_active();
4912 *   for (; joint_cell != joint_endc;
4913 *   ++joint_cell, ++stokes_cell, ++temperature_cell)
4914 *   if (joint_cell->is_locally_owned())
4915 *   {
4916 *   joint_cell->get_dof_indices(local_joint_dof_indices);
4917 *   stokes_cell->get_dof_indices(local_stokes_dof_indices);
4918 *   temperature_cell->get_dof_indices(local_temperature_dof_indices);
4919 *  
4920 *   for (unsigned int i = 0; i < joint_fe.n_dofs_per_cell(); ++i)
4921 *   if (joint_fe.system_to_base_index(i).first.first == 0)
4922 *   {
4923 *   Assert(joint_fe.system_to_base_index(i).second <
4924 *   local_stokes_dof_indices.size(),
4925 *   ExcInternalError());
4926 *  
4927 *   joint_solution(local_joint_dof_indices[i]) = stokes_solution(
4928 *   local_stokes_dof_indices[joint_fe.system_to_base_index(i)
4929 *   .second]);
4930 *   }
4931 *   else
4932 *   {
4933 *   Assert(joint_fe.system_to_base_index(i).first.first == 1,
4934 *   ExcInternalError());
4935 *   Assert(joint_fe.system_to_base_index(i).second <
4936 *   local_temperature_dof_indices.size(),
4937 *   ExcInternalError());
4938 *   joint_solution(local_joint_dof_indices[i]) =
4939 *   temperature_solution(
4940 *   local_temperature_dof_indices
4941 *   [joint_fe.system_to_base_index(i).second]);
4942 *   }
4943 *   }
4944 *   }
4945 *  
4946 *   joint_solution.compress(VectorOperation::insert);
4947 *  
4948 *   const IndexSet locally_relevant_joint_dofs =
4949 *   DoFTools::extract_locally_relevant_dofs(joint_dof_handler);
4950 *   TrilinosWrappers::MPI::Vector locally_relevant_joint_solution;
4951 *   locally_relevant_joint_solution.reinit(locally_relevant_joint_dofs,
4952 *   MPI_COMM_WORLD);
4953 *   locally_relevant_joint_solution = joint_solution;
4954 *  
4955 *   Postprocessor postprocessor(Utilities::MPI::this_mpi_process(
4956 *   MPI_COMM_WORLD),
4957 *   stokes_solution.block(1).min());
4958 *  
4959 *   DataOut<dim> data_out;
4960 *   data_out.attach_dof_handler(joint_dof_handler);
4961 *   data_out.add_data_vector(locally_relevant_joint_solution, postprocessor);
4962 *   data_out.build_patches();
4963 *  
4964 *   static int out_index = 0;
4965 *   data_out.write_vtu_with_pvtu_record(
4966 *   "./", "solution", out_index, MPI_COMM_WORLD, 5);
4967 *  
4968 *   ++out_index;
4969 *   }
4970 *  
4971 *  
4972 *  
4973 * @endcode
4974 *
4975 *
4976 * <a name="step_32-BoussinesqFlowProblemrefine_mesh"></a>
4977 * <h4>BoussinesqFlowProblem::refine_mesh</h4>
4978 *
4979
4980 *
4981 * This function isn't really new either. Since the <code>setup_dofs</code>
4982 * function that we call in the middle has its own timer section, we split
4983 * timing this function into two sections. It will also allow us to easily
4984 * identify which of the two is more expensive.
4985 *
4986
4987 *
4988 * One thing of note, however, is that we only want to compute error
4989 * indicators on the locally owned subdomain. In order to achieve this, we
4990 * pass one additional argument to the KellyErrorEstimator::estimate
4991 * function. Note that the vector for error estimates is resized to the
4992 * number of active cells present on the current process, which is less than
4993 * the total number of active cells on all processors (but more than the
4994 * number of locally owned active cells); each processor only has a few
4995 * coarse cells around the locally owned ones, as also explained in @ref step_40 "step-40".
4996 *
4997
4998 *
4999 * The local error estimates are then handed to a %parallel version of
5001 * also @ref step_40 "step-40") which looks at the errors and finds the cells that need
5002 * refinement by comparing the error values across processors. As in
5003 * @ref step_31 "step-31", we want to limit the maximum grid level. So in case some cells
5004 * have been marked that are already at the finest level, we simply clear
5005 * the refine flags.
5006 *
5007 * @code
5008 *   template <int dim>
5009 *   void
5010 *   BoussinesqFlowProblem<dim>::refine_mesh(const unsigned int max_grid_level)
5011 *   {
5013 *   temperature_trans(temperature_dof_handler);
5016 *   stokes_trans(stokes_dof_handler);
5017 *  
5018 *   {
5019 *   TimerOutput::Scope timer_section(computing_timer,
5020 *   "Refine mesh structure, part 1");
5021 *  
5022 *   Vector<float> estimated_error_per_cell(triangulation.n_active_cells());
5023 *  
5025 *   temperature_dof_handler,
5026 *   QGauss<dim - 1>(parameters.temperature_degree + 1),
5027 *   std::map<types::boundary_id, const Function<dim> *>(),
5028 *   temperature_solution,
5029 *   estimated_error_per_cell,
5030 *   ComponentMask(),
5031 *   nullptr,
5032 *   0,
5033 *   triangulation.locally_owned_subdomain());
5034 *  
5036 *   triangulation, estimated_error_per_cell, 0.3, 0.1);
5037 *  
5038 *   if (triangulation.n_levels() > max_grid_level)
5039 *   for (typename Triangulation<dim>::active_cell_iterator cell =
5040 *   triangulation.begin_active(max_grid_level);
5041 *   cell != triangulation.end();
5042 *   ++cell)
5043 *   cell->clear_refine_flag();
5044 *  
5045 * @endcode
5046 *
5047 * With all flags marked as necessary, we can then tell the
5048 * parallel::distributed::SolutionTransfer objects to get ready to
5049 * transfer data from one mesh to the next, which they will do when
5050 * notified by
5051 * Triangulation as part of the @p execute_coarsening_and_refinement() call.
5052 * The syntax is similar to the non-%parallel solution transfer (with the
5053 * exception that here a pointer to the vector entries is enough). The
5054 * remainder of the function further down below is then concerned with
5055 * setting up the data structures again after mesh refinement and
5056 * restoring the solution vectors on the new mesh.
5057 *
5058 * @code
5059 *   const std::vector<const TrilinosWrappers::MPI::Vector *> x_temperature = {
5060 *   &temperature_solution, &old_temperature_solution};
5061 *   const std::vector<const TrilinosWrappers::MPI::BlockVector *> x_stokes = {
5062 *   &stokes_solution, &old_stokes_solution};
5063 *  
5064 *   triangulation.prepare_coarsening_and_refinement();
5065 *  
5066 *   temperature_trans.prepare_for_coarsening_and_refinement(x_temperature);
5067 *   stokes_trans.prepare_for_coarsening_and_refinement(x_stokes);
5068 *  
5069 *   triangulation.execute_coarsening_and_refinement();
5070 *   }
5071 *  
5072 *   setup_dofs();
5073 *  
5074 *   {
5075 *   TimerOutput::Scope timer_section(computing_timer,
5076 *   "Refine mesh structure, part 2");
5077 *  
5078 *   {
5079 *   TrilinosWrappers::MPI::Vector distributed_temp1(temperature_rhs);
5080 *   TrilinosWrappers::MPI::Vector distributed_temp2(temperature_rhs);
5081 *  
5082 *   std::vector<TrilinosWrappers::MPI::Vector *> tmp = {&distributed_temp1,
5083 *   &distributed_temp2};
5084 *   temperature_trans.interpolate(tmp);
5085 *  
5086 * @endcode
5087 *
5088 * enforce constraints to make the interpolated solution conforming on
5089 * the new mesh:
5090 *
5091 * @code
5092 *   temperature_constraints.distribute(distributed_temp1);
5093 *   temperature_constraints.distribute(distributed_temp2);
5094 *  
5095 *   temperature_solution = distributed_temp1;
5096 *   old_temperature_solution = distributed_temp2;
5097 *   }
5098 *  
5099 *   {
5100 *   TrilinosWrappers::MPI::BlockVector distributed_stokes(stokes_rhs);
5101 *   TrilinosWrappers::MPI::BlockVector old_distributed_stokes(stokes_rhs);
5102 *  
5103 *   std::vector<TrilinosWrappers::MPI::BlockVector *> stokes_tmp = {
5104 *   &distributed_stokes, &old_distributed_stokes};
5105 *  
5106 *   stokes_trans.interpolate(stokes_tmp);
5107 *  
5108 * @endcode
5109 *
5110 * enforce constraints to make the interpolated solution conforming on
5111 * the new mesh:
5112 *
5113 * @code
5114 *   stokes_constraints.distribute(distributed_stokes);
5115 *   stokes_constraints.distribute(old_distributed_stokes);
5116 *  
5117 *   stokes_solution = distributed_stokes;
5118 *   old_stokes_solution = old_distributed_stokes;
5119 *   }
5120 *   }
5121 *   }
5122 *  
5123 *  
5124 *  
5125 * @endcode
5126 *
5127 *
5128 * <a name="step_32-BoussinesqFlowProblemrun"></a>
5129 * <h4>BoussinesqFlowProblem::run</h4>
5130 *
5131
5132 *
5133 * This is the final and controlling function in this class. It, in fact,
5134 * runs the entire rest of the program and is, once more, very similar to
5135 * @ref step_31 "step-31". The only substantial difference is that we use a different mesh
5136 * now (a GridGenerator::hyper_shell instead of a simple cube geometry).
5137 *
5138 * @code
5139 *   template <int dim>
5140 *   void BoussinesqFlowProblem<dim>::run()
5141 *   {
5143 *   Point<dim>(),
5144 *   EquationData::R0,
5145 *   EquationData::R1,
5146 *   (dim == 3) ? 96 : 12,
5147 *   true);
5148 *  
5149 *   global_Omega_diameter = GridTools::diameter(triangulation);
5150 *  
5151 *   triangulation.refine_global(parameters.initial_global_refinement);
5152 *  
5153 *   setup_dofs();
5154 *  
5155 *   unsigned int pre_refinement_step = 0;
5156 *  
5157 *   start_time_iteration:
5158 *  
5159 *   {
5160 *   TrilinosWrappers::MPI::Vector solution(
5161 *   temperature_dof_handler.locally_owned_dofs());
5162 * @endcode
5163 *
5164 * VectorTools::project supports parallel vector classes with most
5165 * standard finite elements via deal.II's own native MatrixFree framework:
5166 * since we use standard Lagrange elements of moderate order this function
5167 * works well here.
5168 *
5169 * @code
5170 *   VectorTools::project(temperature_dof_handler,
5171 *   temperature_constraints,
5172 *   QGauss<dim>(parameters.temperature_degree + 2),
5173 *   EquationData::TemperatureInitialValues<dim>(),
5174 *   solution);
5175 * @endcode
5176 *
5177 * Having so computed the current temperature field, let us set the member
5178 * variable that holds the temperature nodes. Strictly speaking, we really
5179 * only need to set <code>old_temperature_solution</code> since the first
5180 * thing we will do is to compute the Stokes solution that only requires
5181 * the previous time step's temperature field. That said, nothing good can
5182 * come from not initializing the other vectors as well (especially since
5183 * it's a relatively cheap operation and we only have to do it once at the
5184 * beginning of the program) if we ever want to extend our numerical
5185 * method or physical model, and so we initialize
5186 * <code>old_temperature_solution</code> and
5187 * <code>old_old_temperature_solution</code> as well. The assignment makes
5188 * sure that the vectors on the left hand side (which where initialized to
5189 * contain ghost elements as well) also get the correct ghost elements. In
5190 * other words, the assignment here requires communication between
5191 * processors:
5192 *
5193 * @code
5194 *   temperature_solution = solution;
5195 *   old_temperature_solution = solution;
5196 *   old_old_temperature_solution = solution;
5197 *   }
5198 *  
5199 *   timestep_number = 0;
5200 *   time_step = old_time_step = 0;
5201 *  
5202 *   double time = 0;
5203 *  
5204 *   do
5205 *   {
5206 *   pcout << "Timestep " << timestep_number
5207 *   << ": t=" << time / EquationData::year_in_seconds << " years"
5208 *   << std::endl;
5209 *  
5210 *   assemble_stokes_system();
5211 *   build_stokes_preconditioner();
5212 *   assemble_temperature_matrix();
5213 *  
5214 *   solve();
5215 *  
5216 *   pcout << std::endl;
5217 *  
5218 *   if ((timestep_number == 0) &&
5219 *   (pre_refinement_step < parameters.initial_adaptive_refinement))
5220 *   {
5221 *   refine_mesh(parameters.initial_global_refinement +
5222 *   parameters.initial_adaptive_refinement);
5223 *   ++pre_refinement_step;
5224 *   goto start_time_iteration;
5225 *   }
5226 *   else if ((timestep_number > 0) &&
5227 *   (timestep_number % parameters.adaptive_refinement_interval ==
5228 *   0))
5229 *   refine_mesh(parameters.initial_global_refinement +
5230 *   parameters.initial_adaptive_refinement);
5231 *  
5232 *   if ((parameters.generate_graphical_output == true) &&
5233 *   (timestep_number % parameters.graphical_output_interval == 0))
5234 *   output_results();
5235 *  
5236 * @endcode
5237 *
5238 * In order to speed up linear solvers, we extrapolate the solutions
5239 * from the old time levels to the new one. This gives a very good
5240 * initial guess, cutting the number of iterations needed in solvers
5241 * by more than one half. We do not need to extrapolate in the last
5242 * iteration, so if we reached the final time, we stop here.
5243 *
5244
5245 *
5246 * As the last thing during a time step (before actually bumping up
5247 * the number of the time step), we check whether the current time
5248 * step number is divisible by 100, and if so we let the computing
5249 * timer print a summary of CPU times spent so far.
5250 *
5251 * @code
5252 *   if (time > parameters.end_time * EquationData::year_in_seconds)
5253 *   break;
5254 *  
5255 *   TrilinosWrappers::MPI::BlockVector old_old_stokes_solution;
5256 *   old_old_stokes_solution = old_stokes_solution;
5257 *   old_stokes_solution = stokes_solution;
5258 *   old_old_temperature_solution = old_temperature_solution;
5259 *   old_temperature_solution = temperature_solution;
5260 *   if (old_time_step > 0)
5261 *   {
5262 * @endcode
5263 *
5264 * Trilinos sadd does not like ghost vectors even as input. Copy
5265 * into distributed vectors for now:
5266 *
5267 * @code
5268 *   {
5269 *   TrilinosWrappers::MPI::BlockVector distr_solution(stokes_rhs);
5270 *   distr_solution = stokes_solution;
5271 *   TrilinosWrappers::MPI::BlockVector distr_old_solution(stokes_rhs);
5272 *   distr_old_solution = old_old_stokes_solution;
5273 *   distr_solution.sadd(1. + time_step / old_time_step,
5274 *   -time_step / old_time_step,
5275 *   distr_old_solution);
5276 *   stokes_solution = distr_solution;
5277 *   }
5278 *   {
5279 *   TrilinosWrappers::MPI::Vector distr_solution(temperature_rhs);
5280 *   distr_solution = temperature_solution;
5281 *   TrilinosWrappers::MPI::Vector distr_old_solution(temperature_rhs);
5282 *   distr_old_solution = old_old_temperature_solution;
5283 *   distr_solution.sadd(1. + time_step / old_time_step,
5284 *   -time_step / old_time_step,
5285 *   distr_old_solution);
5286 *   temperature_solution = distr_solution;
5287 *   }
5288 *   }
5289 *  
5290 *   if ((timestep_number > 0) && (timestep_number % 100 == 0))
5291 *   computing_timer.print_summary();
5292 *  
5293 *   time += time_step;
5294 *   ++timestep_number;
5295 *   }
5296 *   while (true);
5297 *  
5298 * @endcode
5299 *
5300 * If we are generating graphical output, do so also for the last time
5301 * step unless we had just done so before we left the do-while loop
5302 *
5303 * @code
5304 *   if ((parameters.generate_graphical_output == true) &&
5305 *   !((timestep_number - 1) % parameters.graphical_output_interval == 0))
5306 *   output_results();
5307 *   }
5308 *   } // namespace Step32
5309 *  
5310 *  
5311 *  
5312 * @endcode
5313 *
5314 *
5315 * <a name="step_32-Thecodemaincodefunction"></a>
5316 * <h3>The <code>main</code> function</h3>
5317 *
5318
5319 *
5320 * The main function is short as usual and very similar to the one in
5321 * @ref step_31 "step-31". Since we use a parameter file which is specified as an argument in
5322 * the command line, we have to read it in here and pass it on to the
5323 * Parameters class for parsing. If no filename is given in the command line,
5324 * we simply use the <code>step-32.prm</code> file which is distributed
5325 * together with the program.
5326 *
5327
5328 *
5329 * Because 3d computations are simply very slow unless you throw a lot of
5330 * processors at them, the program defaults to 2d. You can get the 3d version
5331 * by changing the constant dimension below to 3.
5332 *
5333 * @code
5334 *   int main(int argc, char *argv[])
5335 *   {
5336 *   try
5337 *   {
5338 *   using namespace Step32;
5339 *   using namespace dealii;
5340 *  
5341 *   Utilities::MPI::MPI_InitFinalize mpi_initialization(
5342 *   argc, argv, numbers::invalid_unsigned_int);
5343 *  
5344 *   std::string parameter_filename;
5345 *   if (argc >= 2)
5346 *   parameter_filename = argv[1];
5347 *   else
5348 *   parameter_filename = "step-32.prm";
5349 *  
5350 *   const int dim = 2;
5351 *   BoussinesqFlowProblem<dim>::Parameters parameters(parameter_filename);
5352 *   BoussinesqFlowProblem<dim> flow_problem(parameters);
5353 *   flow_problem.run();
5354 *   }
5355 *   catch (std::exception &exc)
5356 *   {
5357 *   std::cerr << std::endl
5358 *   << std::endl
5359 *   << "----------------------------------------------------"
5360 *   << std::endl;
5361 *   std::cerr << "Exception on processing: " << std::endl
5362 *   << exc.what() << std::endl
5363 *   << "Aborting!" << std::endl
5364 *   << "----------------------------------------------------"
5365 *   << std::endl;
5366 *  
5367 *   return 1;
5368 *   }
5369 *   catch (...)
5370 *   {
5371 *   std::cerr << std::endl
5372 *   << std::endl
5373 *   << "----------------------------------------------------"
5374 *   << std::endl;
5375 *   std::cerr << "Unknown exception!" << std::endl
5376 *   << "Aborting!" << std::endl
5377 *   << "----------------------------------------------------"
5378 *   << std::endl;
5379 *   return 1;
5380 *   }
5381 *  
5382 *   return 0;
5383 *   }
5384 * @endcode
5385<a name="step_32-Results"></a><h1>Results</h1>
5386
5387
5388When run, the program simulates convection in 3d in much the same way
5389as @ref step_31 "step-31" did, though with an entirely different testcase.
5390
5391
5392<a name="step_32-Comparisonofresultswithstep31"></a><h3>Comparison of results with step-31</h3>
5393
5394
5395Before we go to this testcase, however, let us show a few results from a
5396slightly earlier version of this program that was solving exactly the
5397testcase we used in @ref step_31 "step-31", just that we now solve it in parallel and with
5398much higher resolution. We show these results mainly for comparison.
5399
5400Here are two images that show this higher resolution if we choose a 3d
5401computation in <code>main()</code> and if we set
5402<code>initial_refinement=3</code> and
5403<code>n_pre_refinement_steps=4</code>. At the time steps shown, the
5404meshes had around 72,000 and 236,000 cells, for a total of 2,680,000
5405and 8,250,000 degrees of freedom, respectively, more than an order of
5406magnitude more than we had available in @ref step_31 "step-31":
5407
5408<table align="center" class="doxtable">
5409 <tr>
5410 <td>
5411 <img src="https://www.dealii.org/images/steps/developer/step-32.3d.cube.0.png" alt="">
5412 </td>
5413 </tr>
5414 <tr>
5415 <td>
5416 <img src="https://www.dealii.org/images/steps/developer/step-32.3d.cube.1.png" alt="">
5417 </td>
5418 </tr>
5419</table>
5420
5421The computation was done on a subset of 50 processors of the Brazos
5422cluster at Texas A&amp;M University.
5423
5424
5425<a name="step_32-Resultsfora2dcircularshelltestcase"></a><h3>Results for a 2d circular shell testcase</h3>
5426
5427
5428Next, we will run @ref step_32 "step-32" with the parameter file in the directory with one
5429change: we increase the final time to 1e9. Here we are using 16 processors. The
5430command to launch is (note that @ref step_32 "step-32".prm is the default):
5431
5432<code>
5433<pre>
5434\$ mpirun -np 16 ./step-32
5435</pre>
5436</code>
5437
5438Note that running a job on a cluster typically requires going through a job
5439scheduler, which we won't discuss here. The output will look roughly like
5440this:
5441
5442<code>
5443<pre>
5444\$ mpirun -np 16 ./step-32
5445Number of active cells: 12,288 (on 6 levels)
5446Number of degrees of freedom: 186,624 (99,840+36,864+49,920)
5447
5448Timestep 0: t=0 years
5449
5450 Rebuilding Stokes preconditioner...
5451 Solving Stokes system... 41 iterations.
5452 Maximal velocity: 60.4935 cm/year
5453 Time step: 18166.9 years
5454 17 CG iterations for temperature
5455 Temperature range: 973 4273.16
5456
5457Number of active cells: 15,921 (on 7 levels)
5458Number of degrees of freedom: 252,723 (136,640+47,763+68,320)
5459
5460Timestep 0: t=0 years
5461
5462 Rebuilding Stokes preconditioner...
5463 Solving Stokes system... 50 iterations.
5464 Maximal velocity: 60.3223 cm/year
5465 Time step: 10557.6 years
5466 19 CG iterations for temperature
5467 Temperature range: 973 4273.16
5468
5469Number of active cells: 19,926 (on 8 levels)
5470Number of degrees of freedom: 321,246 (174,312+59,778+87,156)
5471
5472Timestep 0: t=0 years
5473
5474 Rebuilding Stokes preconditioner...
5475 Solving Stokes system... 50 iterations.
5476 Maximal velocity: 57.8396 cm/year
5477 Time step: 5453.78 years
5478 18 CG iterations for temperature
5479 Temperature range: 973 4273.16
5480
5481Timestep 1: t=5453.78 years
5482
5483 Solving Stokes system... 49 iterations.
5484 Maximal velocity: 59.0231 cm/year
5485 Time step: 5345.86 years
5486 18 CG iterations for temperature
5487 Temperature range: 973 4273.16
5488
5489Timestep 2: t=10799.6 years
5490
5491 Solving Stokes system... 24 iterations.
5492 Maximal velocity: 60.2139 cm/year
5493 Time step: 5241.51 years
5494 17 CG iterations for temperature
5495 Temperature range: 973 4273.16
5496
5497[...]
5498
5499Timestep 100: t=272151 years
5500
5501 Solving Stokes system... 21 iterations.
5502 Maximal velocity: 161.546 cm/year
5503 Time step: 1672.96 years
5504 17 CG iterations for temperature
5505 Temperature range: 973 4282.57
5506
5507Number of active cells: 56,085 (on 8 levels)
5508Number of degrees of freedom: 903,408 (490,102+168,255+245,051)
5509
5510
5511
5512+---------------------------------------------+------------+------------+
5513| Total wallclock time elapsed since start | 115s | |
5514| | | |
5515| Section | no. calls | wall time | % of total |
5516+---------------------------------+-----------+------------+------------+
5517| Assemble Stokes system | 103 | 2.82s | 2.5% |
5518| Assemble temperature matrices | 12 | 0.452s | 0.39% |
5519| Assemble temperature rhs | 103 | 11.5s | 10% |
5520| Build Stokes preconditioner | 12 | 2.09s | 1.8% |
5521| Solve Stokes system | 103 | 90.4s | 79% |
5522| Solve temperature system | 103 | 1.53s | 1.3% |
5523| Postprocessing | 3 | 0.532s | 0.46% |
5524| Refine mesh structure, part 1 | 12 | 0.93s | 0.81% |
5525| Refine mesh structure, part 2 | 12 | 0.384s | 0.33% |
5526| Setup dof systems | 13 | 2.96s | 2.6% |
5527+---------------------------------+-----------+------------+------------+
5528
5529[...]
5530
5531+---------------------------------------------+------------+------------+
5532| Total wallclock time elapsed since start | 9.14e+04s | |
5533| | | |
5534| Section | no. calls | wall time | % of total |
5535+---------------------------------+-----------+------------+------------+
5536| Assemble Stokes system | 47045 | 2.05e+03s | 2.2% |
5537| Assemble temperature matrices | 4707 | 310s | 0.34% |
5538| Assemble temperature rhs | 47045 | 8.7e+03s | 9.5% |
5539| Build Stokes preconditioner | 4707 | 1.48e+03s | 1.6% |
5540| Solve Stokes system | 47045 | 7.34e+04s | 80% |
5541| Solve temperature system | 47045 | 1.46e+03s | 1.6% |
5542| Postprocessing | 1883 | 222s | 0.24% |
5543| Refine mesh structure, part 1 | 4706 | 641s | 0.7% |
5544| Refine mesh structure, part 2 | 4706 | 259s | 0.28% |
5545| Setup dof systems | 4707 | 1.86e+03s | 2% |
5546+---------------------------------+-----------+------------+------------+
5547</pre>
5548</code>
5549
5550The simulation terminates when the time reaches the 1 billion years
5551selected in the input file. You can extrapolate from this how long a
5552simulation would take for a different final time (the time step size
5553ultimately settles on somewhere around 20,000 years, so computing for
5554two billion years will take 100,000 time steps, give or take 20%). As
5555can be seen here, we spend most of the compute time in assembling
5556linear systems and &mdash; above all &mdash; in solving Stokes
5557systems.
5558
5559
5560To demonstrate the output we show the output from every 1250th time step here:
5561<table>
5562 <tr>
5563 <td>
5564 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-000.png" alt="">
5565 </td>
5566 <td>
5567 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-050.png" alt="">
5568 </td>
5569 <td>
5570 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-100.png" alt="">
5571 </td>
5572 </tr>
5573 <tr>
5574 <td>
5575 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-150.png" alt="">
5576 </td>
5577 <td>
5578 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-200.png" alt="">
5579 </td>
5580 <td>
5581 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-250.png" alt="">
5582 </td>
5583 </tr>
5584 <tr>
5585 <td>
5586 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-300.png" alt="">
5587 </td>
5588 <td>
5589 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-350.png" alt="">
5590 </td>
5591 <td>
5592 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-400.png" alt="">
5593 </td>
5594 </tr>
5595 <tr>
5596 <td>
5597 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-450.png" alt="">
5598 </td>
5599 <td>
5600 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-500.png" alt="">
5601 </td>
5602 <td>
5603 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-550.png" alt="">
5604 </td>
5605 </tr>
5606 <tr>
5607 <td>
5608 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-time-600.png" alt="">
5609 </td>
5610 <td>
5611 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-cells.png" alt="">
5612 </td>
5613 <td>
5614 <img src="https://www.dealii.org/images/steps/developer/step-32-2d-partition.png" alt="">
5615 </td>
5616 </tr>
5617</table>
5618
5619The last two images show the grid as well as the partitioning of the mesh for
5620the same computation with 16 subdomains and 16 processors. The full dynamics of
5621this simulation are really only visible by looking at an animation, for example
5622the one <a
5623href="https://www.dealii.org/images/steps/developer/step-32-2d-temperature.webm">shown
5624on this site</a>. This image is well worth watching due to its artistic quality
5625and entrancing depiction of the evolution of the magma plumes.
5626
5627If you watch the movie, you'll see that the convection pattern goes
5628through several stages: First, it gets rid of the instable temperature
5629layering with the hot material overlain by the dense cold
5630material. After this great driver is removed and we have a sort of
5631stable situation, a few blobs start to separate from the hot boundary
5632layer at the inner ring and rise up, with a few cold fingers also
5633dropping down from the outer boundary layer. During this phase, the solution
5634remains mostly symmetric, reflecting the 12-fold symmetry of the
5635original mesh. In a final phase, the fluid enters vigorous chaotic
5636stirring in which all symmetries are lost. This is a pattern that then
5637continues to dominate flow.
5638
5639These different phases can also be identified if we look at the
5640maximal velocity as a function of time in the simulation:
5641
5642<img src="https://www.dealii.org/images/steps/developer/step-32.2d.t_vs_vmax.png" alt="">
5643
5644Here, the velocity (shown in centimeters per year) becomes very large,
5645to the order of several meters per year) at the beginning when the
5646temperature layering is instable. It then calms down to relatively
5647small values before picking up again in the chaotic stirring
5648regime. There, it remains in the range of 10-40 centimeters per year,
5649quite within the physically expected region.
5650
5651
5652<a name="step_32-Resultsfora3dsphericalshelltestcase"></a><h3>Results for a 3d spherical shell testcase</h3>
5653
5654
56553d computations are very expensive computationally. Furthermore, as
5656seen above, interesting behavior only starts after quite a long time
5657requiring more CPU hours than is available on a typical
5658cluster. Consequently, rather than showing a complete simulation here,
5659let us simply show a couple of pictures we have obtained using the
5660successor to this program, called <i>ASPECT</i> (short for <i>Advanced
5661%Solver for Problems in Earth's ConvecTion</i>), that is being
5662developed independently of deal.II and that already incorporates some
5663of the extensions discussed below. The following two pictures show
5664isocontours of the temperature and the partition of the domain (along
5665with the mesh) onto 512 processors:
5666
5667<p align="center">
5668<img src="https://www.dealii.org/images/steps/developer/step-32.3d-sphere.solution.png" alt="">
5669
5670<img src="https://www.dealii.org/images/steps/developer/step-32.3d-sphere.partition.png" alt="">
5671</p>
5672
5673
5674<a name="step-32-extensions"></a>
5675<a name="step_32-Possibilitiesforextensions"></a><h3>Possibilities for extensions</h3>
5676
5677
5678There are many directions in which this program could be extended. As
5679mentioned at the end of the introduction, most of these are under active
5680development in the <i>ASPECT</i> (short for <i>Advanced %Solver for Problems
5681in Earth's ConvecTion</i>) code at the time this tutorial program is being
5682finished. Specifically, the following are certainly topics that one should
5683address to make the program more useful:
5684
5685<ul>
5686 <li> <b>Adiabatic heating/cooling:</b>
5687 The temperature field we get in our simulations after a while
5688 is mostly constant with boundary layers at the inner and outer
5689 boundary, and streamers of cold and hot material mixing
5690 everything. Yet, this doesn't match our expectation that things
5691 closer to the earth core should be hotter than closer to the
5692 surface. The reason is that the energy equation we have used does
5693 not include a term that describes adiabatic cooling and heating:
5694 rock, like gas, heats up as you compress it. Consequently, material
5695 that rises up cools adiabatically, and cold material that sinks down
5696 heats adiabatically. The correct temperature equation would
5697 therefore look somewhat like this:
5698 @f{eqnarray*}{
5699 \frac{D T}{Dt}
5700 -
5701 \nabla \cdot \kappa \nabla T &=& \gamma + \tau\frac{Dp}{Dt},
5702 @f}
5703 or, expanding the advected derivative @f$\frac{D}{Dt} =
5704 \frac{\partial}{\partial t} + \mathbf u \cdot \nabla@f$:
5705 @f{eqnarray*}{
5706 \frac{\partial T}{\partial t}
5707 +
5708 {\mathbf u} \cdot \nabla T
5709 -
5710 \nabla \cdot \kappa \nabla T &=& \gamma +
5711 \tau\left\{\frac{\partial
5712 p}{\partial t} + \mathbf u \cdot \nabla p \right\}.
5713 @f}
5714 In other words, as pressure increases in a rock volume
5715 (@f$\frac{Dp}{Dt}>0@f$) we get an additional heat source, and vice
5716 versa.
5717
5718 The time derivative of the pressure is a bit awkward to
5719 implement. If necessary, one could approximate using the fact
5720 outlined in the introduction that the pressure can be decomposed
5721 into a dynamic component due to temperature differences and the
5722 resulting flow, and a static component that results solely from the
5723 static pressure of the overlying rock. Since the latter is much
5724 bigger, one may approximate @f$p\approx p_{\text{static}}=-\rho_{\text{ref}}
5725 [1+\beta T_{\text{ref}}] \varphi@f$, and consequently
5726 @f$\frac{Dp}{Dt} \approx \left\{- \mathbf u \cdot \nabla \rho_{\text{ref}}
5727 [1+\beta T_{\text{ref}}]\varphi\right\} = \rho_{\text{ref}}
5728 [1+\beta T_{\text{ref}}] \mathbf u \cdot \mathbf g@f$.
5729 In other words, if the fluid is moving in the direction of gravity
5730 (downward) it will be compressed and because in that case @f$\mathbf u
5731 \cdot \mathbf g > 0@f$ we get a positive heat source. Conversely, the
5732 fluid will cool down if it moves against the direction of gravity.
5733
5734<li> <b>Compressibility:</b>
5735 As already hinted at in the temperature model above,
5736 mantle rocks are not incompressible. Rather, given the enormous pressures in
5737 the earth mantle (at the core-mantle boundary, the pressure is approximately
5738 140 GPa, equivalent to 1,400,000 times atmospheric pressure), rock actually
5739 does compress to something around 1.5 times the density it would have
5740 at surface pressure. Modeling this presents any number of
5741 difficulties. Primarily, the mass conservation equation is no longer
5742 @f$\textrm{div}\;\mathbf u=0@f$ but should read
5743 @f$\textrm{div}(\rho\mathbf u)=0@f$ where the density @f$\rho@f$ is now no longer
5744 spatially constant but depends on temperature and pressure. A consequence is
5745 that the model is now no longer linear; a linearized version of the Stokes
5746 equation is also no longer symmetric requiring us to rethink preconditioners
5747 and, possibly, even the discretization. We won't go into detail here as to
5748 how this can be resolved.
5749
5750<li> <b>Nonlinear material models:</b> As already hinted at in various places,
5751 material parameters such as the density, the viscosity, and the various
5752 thermal parameters are not constant throughout the earth mantle. Rather,
5753 they nonlinearly depend on the pressure and temperature, and in the case of
5754 the viscosity on the strain rate @f$\varepsilon(\mathbf u)@f$. For complicated
5755 models, the only way to solve such models accurately may be to actually
5756 iterate this dependence out in each time step, rather than simply freezing
5757 coefficients at values extrapolated from the previous time step(s).
5758
5759<li> <b>Checkpoint/restart:</b> Running this program in 2d on a number of
5760 processors allows solving realistic models in a day or two. However, in 3d,
5761 compute times are so large that one runs into two typical problems: (i) On
5762 most compute clusters, the queuing system limits run times for individual
5763 jobs are to 2 or 3 days; (ii) losing the results of a computation due to
5764 hardware failures, misconfigurations, or power outages is a shame when
5765 running on hundreds of processors for a couple of days. Both of these
5766 problems can be addressed by periodically saving the state of the program
5767 and, if necessary, restarting the program at this point. This technique is
5768 commonly called <i>checkpoint/restart</i> and it requires that the entire
5769 state of the program is written to a permanent storage location (e.g. a hard
5770 drive). Given the complexity of the data structures of this program, this is
5771 not entirely trivial (it may also involve writing gigabytes or more of
5772 data), but it can be made easier by realizing that one can save the state
5773 between two time steps where it essentially only consists of the mesh and
5774 solution vectors; during restart one would then first re-enumerate degrees
5775 of freedom in the same way as done before and then re-assemble
5776 matrices. Nevertheless, given the distributed nature of the data structures
5777 involved here, saving and restoring the state of a program is not
5778 trivial. An additional complexity is introduced by the fact that one may
5779 want to change the number of processors between runs, for example because
5780 one may wish to continue computing on a mesh that is finer than the one used
5781 to precompute a starting temperature field at an intermediate time.
5782
5783<li> <b>Predictive postprocessing:</b> The point of computations like this is
5784 not simply to solve the equations. Rather, it is typically the exploration
5785 of different physical models and their comparison with things that we can
5786 measure at the earth surface, in order to find which models are realistic
5787 and which are contradicted by reality. To this end, we need to compute
5788 quantities from our solution vectors that are related to what we can
5789 observe. Among these are, for example, heatfluxes at the surface of the
5790 earth, as well as seismic velocities throughout the mantle as these affect
5791 earthquake waves that are recorded by seismographs.
5792
5793<li> <b>Better refinement criteria:</b> As can be seen above for the
57943d case, the mesh in 3d is primarily refined along the inner
5795boundary. This is because the boundary layer there is stronger than
5796any other transition in the domain, leading us to refine there almost
5797exclusively and basically not at all following the plumes. One
5798certainly needs better refinement criteria to track the parts of the
5799solution we are really interested in better than the criterion used
5800here, namely the KellyErrorEstimator applied to the temperature, is
5801able to.
5802</ul>
5803
5804
5805There are many other ways to extend the current program. However, rather than
5806discussing them here, let us point to the much larger open
5807source code ASPECT (see https://aspect.geodynamics.org/ ) that constitutes the
5808further development of @ref step_32 "step-32" and that already includes many such possible
5809extensions.
5810 *
5811 *
5812<a name="step_32-PlainProg"></a>
5813<h1> The plain program</h1>
5814@include "step-32.cc"
5815*/
virtual void build_patches(const unsigned int n_subdivisions=0)
Definition data_out.cc:1062
void reinit(const Triangulation< dim, spacedim > &tria)
active_cell_iterator begin_active(const unsigned int level=0) const
Definition fe_q.h:554
std::pair< std::pair< unsigned int, unsigned int >, unsigned int > system_to_base_index(const unsigned int index) const
virtual RangeNumberType value(const Point< dim > &p, const unsigned int component=0) const
virtual void vector_value(const Point< dim > &p, Vector< RangeNumberType > &values) const
static void estimate(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const Quadrature< dim - 1 > &quadrature, const std::map< types::boundary_id, const Function< spacedim, Number > * > &neumann_bc, const ReadVector< Number > &solution, Vector< float > &error, const ComponentMask &component_mask={}, const Function< spacedim > *coefficients=nullptr, const unsigned int n_threads=numbers::invalid_unsigned_int, const types::subdomain_id subdomain_id=numbers::invalid_subdomain_id, const types::material_id material_id=numbers::invalid_material_id, const Strategy strategy=cell_diameter_over_24)
Definition point.h:111
numbers::NumberTraits< Number >::real_type norm() const
Point< 3 > vertices[4]
Point< 2 > second
Definition grid_out.cc:4624
Point< 2 > first
Definition grid_out.cc:4623
unsigned int level
Definition grid_out.cc:4626
#define Assert(cond, exc)
#define AssertThrow(cond, exc)
typename ActiveSelector::active_cell_iterator active_cell_iterator
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
UpdateFlags
@ update_values
Shape function values.
@ update_JxW_values
Transformed quadrature weights.
@ update_gradients
Shape function gradients.
@ update_quadrature_points
Transformed quadrature points.
std::vector< value_type > split(const typename ::Triangulation< dim, spacedim >::cell_iterator &parent, const value_type parent_value)
const Event initial
Definition event.cc:64
const Event remesh
Definition event.cc:65
void approximate(const SynchronousIterators< std::tuple< typename DoFHandler< dim, spacedim >::active_cell_iterator, Vector< float >::iterator > > &cell, const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof_handler, const InputVector &solution, const unsigned int component)
Expression sign(const Expression &x)
std::vector< std::vector< bool > > extract_constant_modes(const DoFHandler< dim, spacedim > &dof_handler, const ComponentMask &component_mask)
void extrapolate(const DoFHandler< dim, spacedim > &dof1, const InVector &z1, const DoFHandler< dim, spacedim > &dof2, OutVector &z2)
void hyper_shell(Triangulation< dim, spacedim > &tria, const Point< spacedim > &center, const double inner_radius, const double outer_radius, const unsigned int n_cells=0, 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)
void scale(const double scaling_factor, Triangulation< dim, spacedim > &triangulation)
double volume(const Triangulation< dim, spacedim > &tria)
double diameter(const Triangulation< dim, spacedim > &tria)
@ valid
Iterator points to a valid object.
@ matrix
Contents is actually a matrix.
@ symmetric
Matrix is symmetric.
double norm(const FEValuesBase< dim > &fe, const ArrayView< const std::vector< Tensor< 1, dim > > > &Du)
Definition divergence.h:471
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
Definition utilities.cc:191
SymmetricTensor< 2, dim, Number > e(const Tensor< 2, dim, Number > &F)
SymmetricTensor< 2, dim, Number > b(const Tensor< 2, dim, Number > &F)
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
VectorType::value_type * end(VectorType &V)
std::vector< unsigned int > serial(const std::vector< unsigned int > &targets, const std::function< RequestType(const unsigned int)> &create_request, const std::function< AnswerType(const unsigned int, const RequestType &)> &answer_request, const std::function< void(const unsigned int, const AnswerType &)> &process_answer, const MPI_Comm comm)
T sum(const T &t, const MPI_Comm mpi_communicator)
T max(const T &t, const MPI_Comm mpi_communicator)
unsigned int this_mpi_process(const MPI_Comm mpi_communicator)
Definition mpi.cc:107
std::string compress(const std::string &input)
Definition utilities.cc:389
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)
void run(const Iterator &begin, const std_cxx20::type_identity_t< Iterator > &end, Worker worker, Copier copier, const ScratchData &sample_scratch_data, const CopyData &sample_copy_data, const unsigned int queue_length, const unsigned int chunk_size)
void run(const std::vector< std::vector< Iterator > > &colored_iterators, Worker worker, Copier copier, const ScratchData &sample_scratch_data, const CopyData &sample_copy_data, const unsigned int queue_length=2 *MultithreadInfo::n_threads(), const unsigned int chunk_size=8)
void abort(const ExceptionBase &exc) noexcept
bool check(const ConstraintKinds kind_in, const unsigned int dim)
long double gamma(const unsigned int n)
int(&) functions(const void *v1, const void *v2)
void reinit(MatrixBlock< MatrixType > &v, const BlockSparsityPattern &p)
static constexpr double PI
Definition numbers.h:254
void refine_and_coarsen_fixed_fraction(::Triangulation< dim, spacedim > &tria, const ::Vector< Number > &criteria, const double top_fraction_of_error, const double bottom_fraction_of_error, const VectorTools::NormType norm_type=VectorTools::L1_norm)
::SolutionTransfer< dim, VectorType, spacedim > SolutionTransfer
STL namespace.
::VectorizedArray< Number, width > min(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > cos(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > sin(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > sqrt(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > abs(const ::VectorizedArray< Number, width > &)
Definition types.h:32
unsigned int subdomain_id
Definition types.h:43
const ::parallel::distributed::Triangulation< dim, spacedim > * triangulation