diff --git a/demos/adaptive_multigrid/adaptive_convergence.png b/demos/adaptive_multigrid/adaptive_convergence.png new file mode 100644 index 0000000000..0091fe0a26 Binary files /dev/null and b/demos/adaptive_multigrid/adaptive_convergence.png differ diff --git a/demos/adaptive_multigrid/adaptive_multigrid.py.rst b/demos/adaptive_multigrid/adaptive_multigrid.py.rst new file mode 100644 index 0000000000..43bb2e0a9a --- /dev/null +++ b/demos/adaptive_multigrid/adaptive_multigrid.py.rst @@ -0,0 +1,216 @@ +Adaptive Multigrid Methods using AdaptiveMeshHierarchy +====================================================== + + +Contributed by Anurag Rao + +The purpose of this demo is to show how to use Firedrake's multigrid solver on a hierarchy of adaptively refined Netgen meshes. +We will first have a look at how to use the :class:`.AdaptiveMeshHierarchy` to construct the mesh hierarchy with Netgen meshes, then we will consider a solution to the Poisson problem on an L-shaped domain. +Finally, we will show how to use the :class:`.AdaptiveMeshHierarchy` and :class:`.AdaptiveTransferManager` to construct a scalable solver. The :class:`.AdaptiveMeshHierarchy` contains information of the mesh hierarchy and the parent child relations between the meshes. +The :class:`.AdaptiveTransferManager` deals with the transfer operator logic across any given levels in the hierarchy. +We begin by importing the necessary libraries :: + + from firedrake import * + from netgen.occ import * + import numpy + +Constructing the Mesh Hierarchy +------------------------------- +We first must construct the domain over which we will solve the problem. For a more comprehensive demo on how to use Open Cascade Technology (OCC) and Constructive Solid Geometry (CSG), +see `Netgen integration in Firedrake `_. +We begin with the L-shaped domain, which we build as the union of two rectangles: :: + + rect1 = WorkPlane(Axes((0,0,0), n=Z, h=X)).Rectangle(1,2).Face() + rect2 = WorkPlane(Axes((0,1,0), n=Z, h=X)).Rectangle(2,1).Face() + L = rect1 + rect2 + + geo = OCCGeometry(L, dim=2) + ngmsh = geo.GenerateMesh(maxh=0.5) + mesh = Mesh(ngmsh) + +It is important to convert the initial Netgen mesh into a Firedrake mesh before constructing the :class:`.AdaptiveMeshHierarchy`. To call the constructor to the hierarchy, we must pass the initial mesh. Our initial mesh looks like this: + +.. figure:: initial_mesh.png + :align: center + :alt: Initial mesh. + +We will also initialize the :class:`.AdaptiveTransferManager` here: :: + + amh = AdaptiveMeshHierarchy(mesh) + atm = AdaptiveTransferManager() + +Poisson Problem +--------------- +Now we can define a simple Poisson problem + +.. math:: + + - \nabla^2 u = f \text{ in } \Omega, \quad u = 0 \text{ on } \partial \Omega + +Our approach strongly follows the similar problem in this `lecture course `_. We define the function ``solve_poisson``. The first lines correspond to finding a solution in the CG1 space. The variational problem is formulated with F, where f is the constant function equal to 1. Since we want Dirichlet boundary conditions, we construct the :class:`.DirichletBC` object and apply it to the entire boundary: :: + + def solve_poisson(mesh, params): + V = FunctionSpace(mesh, "CG", 1) + uh = Function(V, name="solution") + v = TestFunction(V) + bc = DirichletBC(V, 0, "on_boundary") + f = Constant(1) + F = inner(grad(uh), grad(v))*dx - inner(f, v)*dx + + problem = NonlinearVariationalProblem(F, uh, bc) + solver = NonlinearVariationalSolver(problem, solver_parameters=params) + solver.set_transfer_manager(atm) + solver.solve() + return uh + +Note the code after the construction of the :class:`.NonlinearVariationalProblem`. To use the :class:`.AdaptiveMeshHierarchy` with the existing Firedrake solver, we have to set the :class:`.AdaptiveTransferManager` as the transfer manager of the multigrid solver. +Since we are using linear CG elements, we will employ Jacobi as the multigrid relaxation, which we define with :: + + solver_params = { + "mat_type": "matfree", + "ksp_type": "cg", + "pc_type": "mg", + "mg_levels": { + "ksp_type": "chebyshev", + "ksp_max_it": 1, + "pc_type": "jacobi", + }, + "mg_coarse": { + "mat_type": "aij", + "pc_type": "lu", + }, + } + +Alternatively for high-order CG elements, it is recommended to use patch relaxation +to achieve degree-independent multigrid convergence. +For more information +see :doc:`Using patch relaxation for multigrid `. +The initial solution is shown below. + +.. figure:: solution_l1.png + :align: center + :alt: Initial Solution from multigrid with initial mesh. + + +Adaptive Mesh Refinement +------------------------ +In this section we will discuss how to adaptively refine select elements and add the newly refined mesh into the :class:`.AdaptiveMeshHierarchy`. +For this problem, we will be using the Babuška-Rheinbolt a-posteriori estimate for an element: + +.. math:: + \eta_K^2 = h_K^2 \int_K \| f + \nabla^2 u_h \|^2 \mathrm{d}x + \frac{h_K}{2} \int_{\partial K \setminus \partial \Omega} ⟦ \nabla u_h \cdot n ⟧^2 \mathrm{d}s, + +where :math:`K` is the element, :math:`h_K` is the diameter of the element, :math:`n` is the normal, and :math:`⟦ \cdot ⟧` is the jump operator. The a-posteriori estimator is computed using the solution at the current level :math:`h`. Integrating over the domain and using the fact that the components of the estimator are piecewise constant on each cell, we can transform the above estimator into the variational problem + +.. math:: + \int_\Omega \eta_K^2 w \mathrm{d}x = \int_\Omega \sum_K h_K^2 \int_K (f + \text{div} (\text{grad} u_h) )^2 \mathrm{d}x w \mathrm{d}x + \int_\Omega \sum_K \frac{h_K}{2} \int_{\partial K \setminus \partial \Omega} ⟦ \nabla u_h \cdot n ⟧^2 \mathrm{d}s w \mathrm{d}x + +Our approach will be to compute the estimator over all elements and selectively choose to refine only those that contribute most to the error. To compute the error estimator, we use the function below to solve the variational formulation of the error estimator. Since our estimator is a constant per element, we use a DG0 function space. :: + + def estimate_error(mesh, uh): + W = FunctionSpace(mesh, "DG", 0) + eta_sq = Function(W) + w = TestFunction(W) + f = Constant(1) + + # symbols for mesh quantities + h = CellDiameter(mesh) + n = FacetNormal(mesh) + v = CellVolume(mesh) + + # compute cellwise error estimator + G = (inner(eta_sq / v, w)*dx + - inner(h**2 * (f + div(grad(uh)))**2, w) * dx + - inner(h('+')/2 * jump(grad(uh), n)**2, w('+')) * dS + - inner(h('-')/2 * jump(grad(uh), n)**2, w('-')) * dS + ) + + sp = {"mat_type": "matfree", "ksp_type": "richardson", "pc_type": "jacobi"} + solve(G == 0, eta_sq, solver_parameters=sp) + eta = Function(W).interpolate(sqrt(eta_sq)) # compute eta from eta^2 + + with eta.dat.vec_ro as eta_: # compute estimate for error in energy norm + error_est = eta_.norm() + return eta, error_est + +The next step is to choose which elements to refine. For this we use Dörfler marking :cite:`Dorfler1996`: + +.. math:: + \eta_K \geq \theta \text{max}_L \eta_L + +The logic is to select an element :math:`K` to refine if the estimator is greater than some factor :math:`\theta` of the maximum error estimate of the mesh, where :math:`\theta` ranges from 0 to 1. In our code we choose :math:`\theta=0.5`. +With these helper functions complete, we can solve the system iteratively. In the max_iterations is the number of total levels we want to perform multigrid on. We will solve for 15 levels. At every level :math:`l`, we first compute the solution using multigrid with patch relaxation up till level :math:`l`. We then use the current approximation of the solution to estimate the error across the mesh. Finally, we refine the mesh and repeat. :: + + theta = 0.5 + max_iterations = 15 + est_errors = [] + dofs = [] + for i in range(max_iterations): + print(f"level {i}") + + mesh = amh[-1] + uh = solve_poisson(mesh, solver_params) + VTKFile(f"output/adaptive_loop_{i}.pvd").write(uh) + + (eta, error_est) = estimate_error(mesh, uh) + VTKFile(f"output/eta_{i}.pvd").write(eta) + + est_errors.append(error_est) + dofs.append(uh.function_space().dim()) + + print(f" ||u - u_h|| <= C * {error_est}") + if len(dofs) > 1: + rate = -numpy.diff(numpy.log(est_errors)) / numpy.diff(numpy.log(dofs)) + print(f" rate = {rate[-1]}") + + if i != max_iterations - 1: + amh.adapt(eta, theta) + + from matplotlib import pyplot as plt + + opt_errors = est_errors[0] * (numpy.array(dofs)/dofs[0]) ** -0.5 + plt.loglog(dofs, est_errors, '-o', markersize = 3, label="Estimated error") + plt.loglog(dofs, opt_errors, '--', markersize = 3, label="Optimal convergence") + plt.ylabel("Error estimate of the energy norm") + plt.xlabel("Number of degrees of freedom") + plt.legend() + plt.savefig("output/adaptive_convergence.png") + + +To perform Dörfler marking, refine the current mesh, and add the mesh to the :class:`.AdaptiveMeshHierarchy`, we use the ``amh.adapt(eta, theta)`` method. In this method the input is the recently computed error estimator ``eta`` and the Dörfler marking parameter ``theta``. The method always performs this on the current fine mesh in the hierarchy. There is another method for adding a mesh to the hierarchy: ``amh.add_mesh(mesh)``. In this method, refinement on the mesh is performed externally by some custom procedure and the resulting mesh directly gets added to the hierarchy. +The meshes now refine according to the error estimator. The error estimators at levels 3,5, and 15 are shown below. Zooming into the vertex of the L-shape at level 15 shows the error indicator remains strongest there. Further refinements will focus on that area. + ++-------------------------------+-------------------------------+-------------------------------+ +| .. figure:: eta_l3.png | .. figure:: eta_l6.png | .. figure:: eta_l15.png | +| :align: center | :align: center | :align: center | +| :height: 250px | :height: 250px | :height: 250px | +| :alt: Eta at level 3 | :alt: Eta at level 6 | :alt: Eta at level 15 | +| | | | +| *Level 3* | *Level 6* | *Level 15* | ++-------------------------------+-------------------------------+-------------------------------+ + +The solutions at level 4 and 15 are shown below. + ++------------------------------------+------------------------------------+ +| .. figure:: solution_l4.png | .. figure:: solution_l15.png | +| :align: center | :align: center | +| :height: 300px | :height: 300px | +| :alt: Solution, level 4 | :alt: Solution, level 15 | +| | | +| *MG solution at level 4* | *MG solution at level 15* | ++------------------------------------+------------------------------------+ + + +The convergence follows the expected optimal behavior: + +.. figure:: adaptive_convergence.png + :align: center + :alt: Convergence of the error estimator. + + +A runnable python version of this demo can be found :demo:`here`. + +.. rubric:: References + +.. bibliography:: demo_references.bib + :filter: docname in docnames diff --git a/demos/adaptive_multigrid/eta_l15.png b/demos/adaptive_multigrid/eta_l15.png new file mode 100644 index 0000000000..05efad50c3 Binary files /dev/null and b/demos/adaptive_multigrid/eta_l15.png differ diff --git a/demos/adaptive_multigrid/eta_l3.png b/demos/adaptive_multigrid/eta_l3.png new file mode 100644 index 0000000000..ccc80c30f4 Binary files /dev/null and b/demos/adaptive_multigrid/eta_l3.png differ diff --git a/demos/adaptive_multigrid/eta_l6.png b/demos/adaptive_multigrid/eta_l6.png new file mode 100644 index 0000000000..f71d2c5788 Binary files /dev/null and b/demos/adaptive_multigrid/eta_l6.png differ diff --git a/demos/adaptive_multigrid/initial_mesh.png b/demos/adaptive_multigrid/initial_mesh.png new file mode 100644 index 0000000000..7ea4bb85bc Binary files /dev/null and b/demos/adaptive_multigrid/initial_mesh.png differ diff --git a/demos/adaptive_multigrid/solution_l1.png b/demos/adaptive_multigrid/solution_l1.png new file mode 100644 index 0000000000..ff6e6ed997 Binary files /dev/null and b/demos/adaptive_multigrid/solution_l1.png differ diff --git a/demos/adaptive_multigrid/solution_l15.png b/demos/adaptive_multigrid/solution_l15.png new file mode 100644 index 0000000000..e2436d74c0 Binary files /dev/null and b/demos/adaptive_multigrid/solution_l15.png differ diff --git a/demos/adaptive_multigrid/solution_l4.png b/demos/adaptive_multigrid/solution_l4.png new file mode 100644 index 0000000000..d457e29979 Binary files /dev/null and b/demos/adaptive_multigrid/solution_l4.png differ diff --git a/demos/demo_references.bib b/demos/demo_references.bib index 901abaa917..ce29d3c2e8 100644 --- a/demos/demo_references.bib +++ b/demos/demo_references.bib @@ -370,6 +370,17 @@ @article{Brubeck2024 year = {2024} } +@article{Dorfler1996, + title={A convergent adaptive algorithm for Poisson’s equation}, + author={D{\"o}rfler, Willy}, + journal={SIAM Journal on Numerical Analysis}, + volume={33}, + number={3}, + pages={1106--1124}, + year={1996}, + publisher={SIAM} +} + @Article{Farrell2015, author = {Patrick E. Farrell and \'Asgeir Birkisson and Simon W. Funke}, title = {{Deflation techniques for finding distinct solutions of nonlinear partial differential equations}}, diff --git a/docs/source/advanced_tut.rst b/docs/source/advanced_tut.rst index 29d8d093a4..5007d12f4b 100644 --- a/docs/source/advanced_tut.rst +++ b/docs/source/advanced_tut.rst @@ -26,6 +26,7 @@ element systems. Full-waveform inversion: spatial and wave sources parallelism. 1D Vlasov-Poisson equation using vertical independent function spaces. Degree-independent multigrid convergence using patch relaxation. + Multigrid on adaptively-refined mesh hierarchies. Monolithic multigrid with Vanka relaxation for Stokes. Vertex/edge star multigrid relaxation for H(div). Auxiliary space patch relaxation multigrid for H(curl). diff --git a/tests/firedrake/demos/test_demos_run.py b/tests/firedrake/demos/test_demos_run.py index dbb0b938be..dd8ce626bc 100644 --- a/tests/firedrake/demos/test_demos_run.py +++ b/tests/firedrake/demos/test_demos_run.py @@ -18,6 +18,7 @@ DEMO_DIR = join(CWD, "..", "..", "..", "demos") SERIAL_DEMOS = [ + Demo(("adaptive_multigrid", "adaptive_multigrid"), ["netgen", "vtk"]), Demo(("benney_luke", "benney_luke"), ["vtk"]), Demo(("boussinesq", "boussinesq"), []), Demo(("burgers", "burgers"), ["vtk"]),