Multigrid over patches
backend="multigrid" solves NodalPoisson by geometric multigrid over the patches: its levels
are the hierarchy without its finest level, then without the next, down to the base level, and
then the base level coarsened by two along each axis. This page measures what that buys against
the default LU factorization:
- in 3D the LU’s fill grows much faster than the mesh, the multigrid’s work in proportion to it;
- the multigrid takes the same number of iterations however many patches are added;
- a coefficient that changes in every step (the implicit particle step’s ) keeps the multigrid’s levels and interpolations, while the LU factorizes again.
The times are measured when the page is built, on one core of the docs runner.
import time
import matplotlib.pyplot as pltimport numpy as np
from patchwork import AMRHierarchy, NodalPoisson
def timed(function, *arguments, **settings): start = time.perf_counter() result = function(*arguments, **settings) return result, time.perf_counter() - start
def source(nodes): x, y, z = nodes.coordinates.T return np.sin(np.pi * x) * np.sin(np.pi * y) * np.sin(np.pi * z)A growing 3D mesh
Section titled “A growing 3D mesh”A unit cube of cells, grounded faces. The setup is the assembly and the factorization (LU) or the levels and their Galerkin operators (multigrid); the solve is one right-hand side, to a relative residual of for the multigrid.
rows = []for n in (8, 12, 16, 24, 32): mesh = AMRHierarchy(base_shape=(n, n, n)) row = {"cells": n} for backend in ("lu", "multigrid"): solver, setup = timed(NodalPoisson, mesh, backend=backend) potential, solve = timed(solver.solve, source(solver.nodes)) row[backend] = (setup, solve) row["unknowns"] = solver.free.size if backend == "lu": reference = potential else: row["iterations"] = solver.solver.iterations row["difference"] = ( np.abs(potential - reference).max() / np.abs(reference).max() ) rows.append(row)
print( " cells unknowns LU setup + solve [s] multigrid setup + solve [s] iterations difference")for row in rows: (lu_setup, lu_solve), (mg_setup, mg_solve) = row["lu"], row["multigrid"] print( f"{row['cells']:4d}^3 {row['unknowns']:9d} {lu_setup:8.3f} + {lu_solve:.4f}" f" {mg_setup:9.3f} + {mg_solve:.4f} {row['iterations']:5d} " f"{row['difference']:.0e}" ) cells unknowns LU setup + solve [s] multigrid setup + solve [s] iterations difference 8^3 343 0.005 + 0.0001 0.003 + 0.0008 1 2e-15 12^3 1331 0.009 + 0.0001 0.007 + 0.0010 4 3e-15 16^3 3375 0.026 + 0.0004 0.013 + 0.0022 4 6e-15 24^3 12167 0.194 + 0.0028 0.039 + 0.0077 8 7e-13 32^3 29791 1.171 + 0.0120 0.078 + 0.0156 7 6e-13unknowns = [row["unknowns"] for row in rows]fig, ax = plt.subplots(figsize=(5.5, 4))ax.loglog(unknowns, [sum(row["lu"]) for row in rows], "o-", label="LU")ax.loglog(unknowns, [sum(row["multigrid"]) for row in rows], "s-", label="multigrid")ax.loglog( unknowns, sum(rows[-1]["multigrid"]) * np.array(unknowns) / unknowns[-1], "k:", label="linear",)ax.set(xlabel="unknowns", ylabel="setup + one solve [s]", title="3D cube, one core")ax.legend()fig.tight_layout()
The two give the same potential to the multigrid’s tolerance. The LU’s setup grows much faster than the unknowns (its fill in 3D), the multigrid’s about linearly, so the gap widens with every refinement of the mesh. In 2D the LU’s fill is mild, and it stays competitive up to large meshes.
More patches, the same iterations
Section titled “More patches, the same iterations”Patches over the middle of a base, each level a box of half the width of the one below. Every patch is one more level of the V-cycle, so the number of iterations does not grow as levels are added (the uniform mesh needs fewer: its one coarse level is small enough to be solved directly):
print("levels unknowns multigrid levels iterations")for levels in range(4): mesh = AMRHierarchy(base_shape=(16, 16, 16)) low, high = 4, 12 for level in range(1, levels + 1): low, high = 2 * low + (high - low) // 2, 2 * low + 3 * (high - low) // 2 mesh.add_patch(level=level, box=((low, high),) * 3) solver = NodalPoisson(mesh, backend="multigrid") solver.solve(source(solver.nodes)) print( f"{levels:6d} {solver.free.size:8d} {solver.solver.num_levels:16d} " f"{solver.solver.iterations:10d}" )levels unknowns multigrid levels iterations 0 3375 2 4 1 3691 3 9 2 4007 4 9 3 4323 5 8A coefficient that changes every step
Section titled “A coefficient that changes every step”The implicit particle step solves, in every nonlinear iteration, with the coefficient
of that step’s plasma. set_coefficient assembles the new
operator; the LU then factorizes it again, the multigrid only rebuilds its Galerkin operators.
Ten steps on a mesh, each with a new coefficient and one solve:
mesh = AMRHierarchy(base_shape=(32, 32, 32))step_times = {}for backend in ("lu", "multigrid"): solver = NodalPoisson(mesh, backend=backend) centres = solver.nodes.cell_centers right = source(solver.nodes) start = time.perf_counter() for step in range(10): # a plasma blob that drifts across the box blob = np.exp(-np.sum((centres - (0.3 + 0.04 * step)) ** 2, axis=1) / 0.02) solver.set_coefficient(1.0 + 50.0 * blob) solver.solve(right) step_times[backend] = (time.perf_counter() - start) / 10for backend, seconds in step_times.items(): print(f"{backend:9s} {seconds:.3f} s per step (new coefficient and a solve)")print(f"multigrid / LU: {step_times['multigrid'] / step_times['lu']:.2f}")lu 1.136 s per step (new coefficient and a solve)multigrid 0.151 s per step (new coefficient and a solve)multigrid / LU: 0.13Both include the assembly of the new operator, which is the same for both; the rest is the factorization against the multigrid’s coarse operators, smoothers and iterations.