Multigrid Helmholtz Solver
Geometric multigrid solver for variable-coefficient Helmholtz equations on masked Arakawa C-grids.
Solver
finitevolx.MultigridSolver
Bases: Module
Geometric multigrid V-cycle solver for the variable-coefficient Helmholtz equation::
div(c(x,y) grad u) - lambda u = rhs
Supports spatially varying coefficients c(x, y) on staggered faces
and masked (irregular) domains.
V-Cycle Algorithm
The V-cycle is a recursive algorithm that visits coarser grids to correct low-frequency error that the smoother cannot resolve::
Level 0 (fine) *---smooth---*-----------*---smooth---*
| restrict prolong |
Level 1 .....*---smooth---*---smooth---*.....
| restrict prolong |
Level 2 (coarse) ..........*--exact solve--*..........
At each level:
- Pre-smooth (nu_1 weighted Jacobi iterations): damp high-frequency error.
- Compute residual:
r = rhs - A u. - Restrict the residual to the coarse grid (full weighting,
R = Pᵀ / 4). - Recurse: solve for the error on the coarse grid, whose operator
is the Galerkin product
A_c = R A P. - Prolongate the coarse correction back to the fine grid
(bilinear interpolation
P). - Post-smooth (nu_2 weighted Jacobi iterations): damp any high-frequency error introduced by the prolongation.
The coarsest level is solved exactly (an inverse precomputed at build
time). With n_pre == n_post one V-cycle from a zero guess,
r -> v_cycle(0, r), is a symmetric linear operator, so it is a valid
CG preconditioner.
The recursion is statically unrolled at JAX trace time because
each level has a different array shape. All integer parameters
(n_levels, n_pre, etc.) are eqx.field(static=True),
so the unrolled structure is visible to the XLA compiler.
Differentiation Modes
Three solve modes trade off backward-pass cost vs gradient accuracy:
-
__call__— Implicit differentiation viajax.lax.custom_linear_solve(symmetric=True). The backward pass solves the adjoint systemA^T v = dL/duwith one multigrid call. SinceAis symmetric, this costs the same as the forward pass. O(1) memory, exact gradients for the linear system being solved (gradient accuracy is limited by how well the V-cycles approximateA^{-1}, i.e. depends onn_cyclesand smoother settings). -
solve_onestep— One-step differentiation (Bolte, Pauwels & Vaiter, NeurIPS 2023). Runs K V-cycles, appliesstop_gradientafter K-1, then autodiffs through the last cycle only. O(1 V-cycle) memory, approximate gradients with error O(rho). -
solve_unrolled— Unrolled differentiation viajax.lax.fori_loop. Backward replays all K iterations. O(K) memory, exact through-iteration gradients (reproduces the forward computation exactly, so gradient accuracy matches the forward solve accuracy).
Attributes:
| Name | Type | Description |
|---|---|---|
levels |
tuple of MultigridLevel
|
Precomputed level data, finest (index 0) to coarsest (index L-1). |
n_levels |
int
|
Number of multigrid levels. |
bottom_inverse |
Float[Array, 'n_wet n_wet']
|
Inverse of the coarsest operator on its wet points (the
pseudo-inverse, with a relative eigenvalue cut-off, for the singular
Neumann |
bottom_index |
Int[Array, ' n_wet']
|
Flat (row-major) indices of the coarsest level's wet points. |
n_pre, n_post |
int
|
Pre- and post-smoothing iterations (weighted Jacobi). Keep them equal for a symmetric V-cycle. |
omega |
float
|
Jacobi relaxation weight. |
n_cycles |
int
|
Number of V-cycles per solve. |
bc |
{'dirichlet', 'neumann'}
|
Wall condition on the wet–dry faces the hierarchy was built with
(see :func: |
null_labels, null_counts |
Array or None
|
Connected-component labels and wet counts of the finest mask, set
only for |
Source code in finitevolx/_src/solvers/multigrid.py
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 | |
__call__(rhs)
Solve A u = rhs with implicit differentiation.
The forward pass runs K V-cycles (identical to :meth:solve_unrolled).
The backward pass uses jax.lax.custom_linear_solve with
symmetric=True to compute gradients via the implicit function
theorem (IFT) rather than unrolling through V-cycle iterations.
For a scalar loss L(u), the gradient w.r.t. the RHS is::
dL/d(rhs) = A^{-T} dL/du = A^{-1} dL/du (since A = A^T)
This adjoint solve is just another multigrid call — so the backward pass costs the same as the forward pass, with O(1) extra memory (no iteration history stored).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rhs
|
Float[Array, 'Ny Nx']
|
Right-hand side of the linear system. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'Ny Nx']
|
Approximate solution |
Source code in finitevolx/_src/solvers/multigrid.py
solve_onestep(rhs)
Solve with one-step differentiation (Bolte et al., NeurIPS 2023).
Runs K V-cycles to convergence, but autodiff only sees the last
cycle. The first K-1 cycles are wrapped in jax.lax.stop_gradient
so they contribute no backward-pass cost.
The forward result is identical to :meth:solve_unrolled. The
gradient approximation error is O(rho) where rho is the per-cycle
convergence rate (about 0.07 per cycle on the default settings,
measured on 34² to 258² basins; the one-step gradient is then within
5 % of the implicit one).
Gradient structure::
u_0 = 0
u_1 = V(u_0, rhs)
...
u_{K-1} = V(u_{K-2}, rhs) <-- stop_gradient here
u_K = V(u_{K-1}, rhs) <-- autodiff traces only this
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rhs
|
Float[Array, 'Ny Nx']
|
Right-hand side. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'Ny Nx']
|
Approximate solution. |
References
Bolte, Pauwels & Vaiter (NeurIPS 2023). "One-step differentiation of iterative algorithms." https://arxiv.org/abs/2305.13768
Source code in finitevolx/_src/solvers/multigrid.py
solve_unrolled(rhs)
Solve by unrolling all V-cycles through lax.fori_loop.
The backward pass differentiates through every iteration, storing intermediate states for replay. This costs O(n_cycles) memory.
Use this mode when you specifically need gradients through the
iteration dynamics itself. For most applications, prefer
__call__ (implicit differentiation) which gives exact gradients
at O(1) memory cost.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rhs
|
Float[Array, 'Ny Nx']
|
Right-hand side. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'Ny Nx']
|
Approximate solution. |
Source code in finitevolx/_src/solvers/multigrid.py
v_cycle(u, rhs, level_idx=0)
Execute a single multigrid V-cycle starting at level_idx.
Algorithm::
if coarsest level:
return A_c^{-1} rhs # exact bottom solve
u = jacobi(u, rhs, n_pre) # 1. pre-smooth
r = rhs - A(u) # 2. compute residual
r_c = restrict(r) # 3. R = P^T / 4
e_c = v_cycle(0, r_c, level+1) # 4. recurse on A_c = R A P
u = u + prolongate(e_c) # 5. correct with coarse error
u = jacobi(u, rhs, n_post) # 6. post-smooth
The recursion unrolls statically at JAX trace time because
level_idx and n_levels are Python ints (static fields).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
Float[Array, 'Ny Nx']
|
Initial guess (typically zeros for the error equation on coarse grids, or the current iterate on the fine grid). |
required |
rhs
|
Float[Array, 'Ny Nx']
|
Right-hand side (original RHS on the fine grid, or the restricted residual on coarser grids). |
required |
level_idx
|
int
|
Current level (0 = finest, n_levels-1 = coarsest). |
0
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'Ny Nx']
|
Improved solution after one V-cycle. |
Source code in finitevolx/_src/solvers/multigrid.py
Factory
finitevolx.build_multigrid_solver(mask, dx, dy, lambda_=0.0, coeff=None, n_levels=None, n_pre=3, n_post=3, omega=0.8, n_cycles=5, bc='dirichlet')
Build a multigrid solver with precomputed level hierarchies.
This is an offline function (runs once on CPU with NumPy / SciPy) that constructs the entire multigrid hierarchy:
- Finest operator: the 5-point stencil of
div(c grad u) - lambda u, face coefficients the mean of the two cell values, wet–dry faces set bybc(below). - Coarsening: each dimension of
npoints becomes(n + 1) // 2, coarse pointJon fine point2J— odd and even sizes alike, so a standardN + 2grid is as deep asN. A coarse point is wet if its coincident fine point is wet; a point whose interpolation support (fine points2J-1 .. 2J+1in each direction) only touches wet fine points is added when its prolongation column is linearly independent of the others, so narrow channels keep a coarse unknown andPkeeps full column rank (:func:_coarse_mask). - Transfers: bilinear prolongation
Pbetween the nested points (zero at dry coarse points for Dirichlet; renormalised over the wet ones for Neumann) and full-weighting restrictionR = Pᵀ / 4. - Galerkin coarse operators
A_c = R A P(9-point stencils), which follow the fine geometry and coefficient exactly. - Exact bottom solve: the inverse of the coarsest operator on its wet points (at most a few dozen unknowns for square grids).
Grid hierarchy example (34x34, a 32-cell interior plus ghost ring)::
Level 0: 34 x 34 (dx, dy) <- finest (solve here)
Level 1: 17 x 17 (2*dx, 2*dy)
Level 2: 9 x 9 (4*dx, 4*dy)
Level 3: 5 x 5 (8*dx, 8*dy) <- coarsest (exact solve)
The returned MultigridSolver is an immutable equinox.Module
with frozen JAX arrays. All subsequent calls (forward solves,
gradients, JIT compilation) use the precomputed hierarchy.
Boundary condition
~~~~~~~~~~~~~~~~~~
bc sets what happens on every face between a wet cell and a dry
one (land, or outside the array):
"dirichlet"(default):u = 0on the dry neighbour, the face keeps its coefficient. Withcoeff=Nonethe finest-level operator is exactly :func:~finitevolx.masked_laplacianwith dry neighbours zero — the streamfunction problem,psi = 0on the wall / coast X nodes ofMask2D.xy_corner_strict. Non-singular for everylambda_ >= 0."neumann": zero flux through wet–dry faces — the pressure / free-surface problem at T points (passmask.h). Atlambda_ = 0the operator is singular (a constant per connected wet component); the solver then projectsrhsand the solution onto zero mean on each component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
array, shape (Ny, Nx), or Mask2D
|
Domain mask (1 = fluid, 0 = land). |
required |
dx
|
float
|
Fine-grid spacings (metres or non-dimensional). |
required |
dy
|
float
|
Fine-grid spacings (metres or non-dimensional). |
required |
lambda_
|
float
|
Helmholtz parameter (>= 0). Use 0.0 for pure Poisson (Laplacian
only). For QG PV inversion ( |
0.0
|
coeff
|
array, shape (Ny, Nx), or None
|
Spatially varying coefficient |
None
|
n_levels
|
int or None
|
Number of multigrid levels. |
None
|
n_pre
|
int
|
Number of pre- and post-smoothing Jacobi iterations per V-cycle. Keep them equal: the V-cycle is then a symmetric operator (needed when it preconditions CG). Default: 3 each. |
3
|
n_post
|
int
|
Number of pre- and post-smoothing Jacobi iterations per V-cycle. Keep them equal: the V-cycle is then a symmetric operator (needed when it preconditions CG). Default: 3 each. |
3
|
omega
|
float
|
Jacobi relaxation weight (0 < omega < 1). Default 0.8, the weight that damps the high-frequency half of the 5-point spectrum best (by at least 3/5 per sweep). |
0.8
|
n_cycles
|
int
|
Number of V-cycles applied per solve. Each cycle reduces the
residual by 0.06-0.07 on the default settings (measured on 34² to
258² circular basins, independent of the grid size), so 5 cycles
reduce it by about 3e-7. An island is slower: 0.14 / 0.17 per
cycle for |
5
|
bc
|
('dirichlet', 'neumann')
|
Condition on wet–dry faces (see above). Default: |
"dirichlet"
|
Returns:
| Type | Description |
|---|---|
MultigridSolver
|
Ready-to-use solver (JIT-compilable |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in finitevolx/_src/solvers/multigrid.py
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | |
Preconditioner
finitevolx.make_multigrid_preconditioner(mg_solver)
Return a preconditioner closure that applies a single multigrid V-cycle.
The returned callable approximates A^{-1} r by running one V-cycle
from a zero initial guess, which is sufficient as a preconditioner
(it doesn't need to converge — it just needs to be a good approximation).
This is compatible with :func:~finitevolx._src.solvers.iterative.solve_cg:
pass the returned closure as the preconditioner argument. The
V-cycle is a symmetric operator (restriction is the scaled transpose of
prolongation, the coarse operators are Galerkin products and the bottom
solve is exact), as CG requires, provided the solver smooths as much
before as after (n_pre == n_post). CG then converges in a few
iterations independent of the grid size: 6 at 128² and 256² on a
circular basin (rtol = 1e-8), against 33 and 47 with the FFT
preconditioner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mg_solver
|
MultigridSolver
|
A pre-built multigrid solver
(from :func: |
required |
Returns:
| Type | Description |
|---|---|
callable
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> mg = build_multigrid_solver(mask, dx, dy, lambda_=10.0)
>>> precond = make_multigrid_preconditioner(mg)
>>> u, info = solve_cg(A, rhs, preconditioner=precond)
Source code in finitevolx/_src/solvers/preconditioners.py
finitevolx.make_gaussx_multigrid_preconditioner(mg_solver)
The multigrid V-cycle as a symmetric gaussx preconditioner.
Wraps a pre-built :class:~finitevolx.MultigridSolver in
gaussx.OperatorPreconditioner, so the geometric V-cycle plugs into
gaussx's strategies (gaussx.CGSolver(preconditioner=...),
gaussx.PreconditionedCGSolver, gaussx.linear_solve).
gaussx works with positive semidefinite systems, so it solves
(−A) x = −b for finitevolX's negative (semi)definite Helmholtz
operator A = ∇·(c∇) − λ. Let V(v) = −Vcycle(0, v) ≈ (−A)⁻¹ v.
With restriction the scaled transpose of prolongation and equal pre- and
post-smoothing (the defaults), V is already symmetric; this applies
the two-step iteration (V, then its adjoint), with K = −A,
M⁻¹ v = V v + Vᵀ v − Vᵀ K V v,
with Vᵀ the exact transpose of the (linear) V-cycle from
jax.linear_transpose: two V-cycles and one operator application per
use. M⁻¹ is symmetric by construction, and since
I − M⁻¹K = (I − VᵀK)(I − VK) it is positive definite exactly when
one V-cycle reduces the error in the energy norm, ‖I − VK‖_K < 1 —
i.e. when the multigrid itself converges. The default
build_multigrid_solver settings do (about 0.07 residual reduction per
cycle); a divergent configuration (one smoothing sweep with omega
near 1, high coefficient contrast) makes no symmetric form of the
V-cycle positive definite, so check the solver converges on its own
first. It costs two V-cycles per application and takes fewer CG steps
than the raw V-cycle, which :func:make_multigrid_preconditioner uses.
The V-cycle runs in the hierarchy's dtype (float64); each application
returns the dtype of the vector it was given. The structure comes from
the system operator, so pass it when calling the preconditioner directly:
pc(v, operator).
For finitevolX's own :func:~finitevolx.solve_cg, which takes a callable
approximating A⁻¹ on 2-D fields, use
:func:make_multigrid_preconditioner on the same solver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mg_solver
|
MultigridSolver
|
A pre-built solver from :func: |
required |
Returns:
| Type | Description |
|---|---|
OperatorPreconditioner
|
Applies |
Examples:
>>> mg = build_multigrid_solver(mask, dx, dy, lambda_=10.0)
>>> neg_A = gaussx.as_linear_operator(
... lambda v: -A(v.reshape(Ny, Nx)).ravel(),
... shape=(Ny * Nx, Ny * Nx),
... positive_semidefinite=True,
... )
>>> pc = make_gaussx_multigrid_preconditioner(mg)
>>> x = gaussx.CGSolver(preconditioner=pc).solve(neg_A, -rhs.ravel())
Source code in finitevolx/_src/solvers/preconditioners.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |