Grids¶
Grids are formed as tensor products of one or more axes. A
Grid combines the collocation points, differentiation
matrices, and integration weights of its constituent axes into a
multi-dimensional structure. MultiGrid holds a
hierarchy of grids of different resolution for the same domain and solves
linear boundary value problems on it with the multigrid method.
- class numgrids.Grid(*axes: Axis, **named_axes: Axis)[source]¶
An N-dimensional numerical grid built from one or more axes.
A
Gridis the tensor product of its constituentAxisobjects. It provides meshed coordinate arrays, boundary masks, and convenience methods for differentiation, integration, interpolation, vector calculus, refinement and plotting.Axes can be passed positionally or as keyword arguments; in the latter case the keyword becomes the axis name, which can then be used instead of the axis index everywhere (
grid.diff(f, axis="x"),grid.faces["x_low"], …).Examples
>>> import numpy as np >>> from numgrids import Grid, chebyshev, periodic >>> grid = Grid(x=chebyshev(20, 0, 1), y=periodic(32, 0, 2 * np.pi)) >>> grid.shape (20, 32) >>> X, Y = grid.meshed_coords >>> f = X ** 2 * np.sin(Y) >>> df_dx = grid.diff(f, axis="x") >>> lap = grid.laplacian(f)
Constructor
- Parameters:
axes (one or more Axis objects) – One or more axes defining the grid. The order of the axes matters! The first axis passed will have index 0.
named_axes (Axis objects as keyword arguments) – Further axes, appended after the positional ones in the given order. The keyword is used as the axis name.
- axis_index(key: int | str) int[source]¶
Return the (non-negative) index of an axis given by index or name.
- property coords: NDArray | tuple[NDArray, ...]¶
Returns a tuple of lists with the coordinate values along each axis. In case of 1D, only a single list is returned.
- property cartesian_coords: tuple[NDArray, ...]¶
Meshed Cartesian coordinates of the grid points.
For a plain (Cartesian) grid this is identical to
meshed_coords. Curvilinear grids map their coordinates to Cartesian space.
- property volume_element: float | NDArray¶
The volume element (Jacobian) of the coordinate system.
1.0for Cartesian grids; an array of shapegrid.shapefor curvilinear grids.
- evaluate(func: Callable[[...], Any]) NDArray[source]¶
Evaluate a function on all grid points.
- Parameters:
func (callable) – Called as
func(*meshed_coords), i.e. with one coordinate array per axis. May also return a scalar, which is broadcast.- Returns:
Array of shape
grid.shape.- Return type:
NDArray
Examples
>>> from numgrids import Grid, equidistant >>> grid = Grid(equidistant(5, 0, 1), equidistant(3, 0, 1)) >>> grid.evaluate(lambda x, y: x + y).shape (5, 3)
- diff(f: NDArray, order: int = 1, axis: int | str = 0, acc: int = 4) NDArray[source]¶
Partial derivative of a meshed function along one axis.
The differentiation operator is cached on the grid.
- diff_operator(order: int = 1, axis: int | str = 0, acc: int = 4) Operator[source]¶
Partial derivative as an
Operator.Operators can be combined algebraically (
+,-,*,@,**) and supportsolve()andeig().
- gradient_operator() tuple[Operator, ...][source]¶
The components of the gradient as operators.
Returns one
Operatorper axis, so that[G(f) for G in grid.gradient_operator()]equalsgrid.gradient(f). Together withdivergence_operator()this builds operators in divergence form, e.g. diffusion with a variable coefficient \(\nabla\cdot(k \nabla u)\):>>> import numpy as np >>> from numgrids import Grid, chebyshev >>> grid = Grid(x=chebyshev(20, 0, 1)) >>> k = 1 + grid.coords >>> (G,), (D,) = grid.gradient_operator(), grid.divergence_operator() >>> L = D @ (k * G) # u -> (k u')' >>> bool(np.allclose(L(grid.coords ** 2), 2 + 4 * grid.coords)) True
- divergence_operator() tuple[Operator, ...][source]¶
The divergence as one operator per vector component.
\(\nabla\cdot\mathbf{v} = \sum_i D_i v_i\) for the returned operators \(D_i\). On curvilinear grids they act on the physical components of the vector field and include the scale factors. See
gradient_operator()for an example.
- diffusion_operator(k=1.0) Operator[source]¶
The operator \(u \mapsto \nabla\cdot(k\,\nabla u)\) in divergence form.
- Parameters:
k (float, NDArray or callable) – The coefficient (e.g. a conductivity or diffusivity): a scalar, an array of grid shape, or a callable evaluated on the grid. With
k = 1this is the Laplacian (butlaplacian_operator()is the more accurate discretization of it on curvilinear grids).
Examples
Steady heat conduction \((k u')' = 0\) with \(k = 1 + x\), \(u(0) = 0\), \(u(1) = 1\):
>>> import numpy as np >>> from numgrids import Grid, chebyshev >>> grid = Grid(x=chebyshev(20, 0, 1)) >>> u = grid.diffusion_operator(lambda x: 1 + x).solve(0, bcs={"x_low": 0, "x_high": 1}) >>> bool(np.allclose(u, np.log(1 + grid.coords) / np.log(2))) True
- gradient(f: NDArray) tuple[NDArray, ...][source]¶
Gradient \(\nabla f\) of a scalar field (one array per axis).
- curl(*v: NDArray) tuple[NDArray, ...] | NDArray[source]¶
Curl \(\nabla\times\mathbf{v}\) of a vector field.
Returns a tuple of three arrays on 3D grids and the scalar out-of-plane component on 2D grids.
- integrate(f: NDArray) float[source]¶
Integrate a meshed function over the whole grid domain.
On curvilinear grids the volume element is included.
- property quadrature_weights: NDArray¶
Quadrature weights of all grid points, as an array of grid shape.
np.sum(grid.quadrature_weights * f)equalsgrid.integrate(f); on curvilinear grids the weights include the volume element.Examples
>>> from numgrids import PolarGrid, radial, periodic >>> disk = PolarGrid(radial(8, 1.0), periodic(16)) >>> round(float(disk.quadrature_weights.sum()), 10) # area of the unit disk 3.1415926536
- inner(f: NDArray, g: NDArray) float | complex[source]¶
The \(L^2\) inner product \(\langle f, g\rangle = \int \bar f\, g\, dV\).
Examples
>>> import numpy as np >>> from numgrids import Grid, periodic >>> grid = Grid(x=periodic(16)) >>> x = grid.coords >>> round(grid.inner(np.sin(x), np.sin(x)), 10), round(abs(grid.inner(np.sin(x), np.cos(x))), 10) (3.1415926536, 0.0)
- norm(f: NDArray, ord: int | float | str = 2) float[source]¶
Norm of a meshed function.
- Parameters:
f (NDArray) – Meshed function of shape
grid.shape.ord (2, 1,
"max"ornumpy.inf) –2(default): the \(L^2\) norm \((\int |f|^2 dV)^{1/2}\);1: the \(L^1\) norm \(\int |f|\, dV\);"max"ornumpy.inf: the largest absolute value.
Examples
>>> import numpy as np >>> from numgrids import Grid, chebyshev >>> grid = Grid(x=chebyshev(20, 0, 2)) >>> round(grid.norm(np.ones(grid.shape)), 10), grid.norm(grid.coords, "max") (1.4142135624, 2.0)
- mean(f: NDArray) float | complex[source]¶
The average \(\int f\, dV / \int dV\) of a meshed function over the domain.
- coefficients(f: NDArray, axis: int | str | tuple | list | None = None) NDArray[source]¶
Spectral expansion coefficients of a meshed function.
Fourier coefficients \(c_k\) along periodic axes, Chebyshev coefficients \(a_k\) along Chebyshev and unbounded axes. See
numgrids.spectral.coefficients()andnumgrids.spectralfor the conventions.- Parameters:
Examples
>>> from numgrids import Grid, chebyshev >>> grid = Grid(x=chebyshev(5, -1, 1)) >>> grid.coefficients(grid.coords ** 2).round(12) + 0 # x^2 = (T_0 + T_2) / 2 array([0.5, 0. , 0.5, 0. , 0. ])
- from_coefficients(c: NDArray, axis: int | str | tuple | list | None = None) NDArray[source]¶
Values on the grid of a function given by its expansion coefficients.
The inverse of
coefficients()(for the same axis argument); seenumgrids.spectral.from_coefficients().
- resample(f: NDArray, target: Grid | int | tuple | list) NDArray[source]¶
Transfer a meshed function to a grid with other numbers of points.
The spectral coefficients are padded with zeros (which is spectral interpolation) or truncated; see
numgrids.spectral.resample().
- resolution(f: NDArray, tol: float = 1e-08)[source]¶
Check whether a meshed function is resolved on this grid.
Looks at the decay of the spectral coefficients along each axis and returns a
Resolutionwith the verdict and the number of points needed per axis; seenumgrids.spectral.resolution().- Parameters:
f (NDArray) – Meshed function of shape
grid.shape.tol (float) – Tolerance for the highest modes, relative to the largest one.
Examples
>>> import numpy as np >>> from numgrids import Grid, chebyshev >>> grid = Grid(x=chebyshev(30, 0, 1)) >>> grid.resolution(np.exp(grid.coords)) Resolution at tol=1e-08: resolved axis x: resolved, 10 of 30 points needed >>> grid.is_resolved(np.tanh(20 * (grid.coords - 0.5))) False
- is_resolved(f: NDArray, tol: float = 1e-08) bool[source]¶
Whether a meshed function is resolved on this grid to the tolerance tol.
Short for
grid.resolution(f, tol).resolved.
- filter(f: NDArray, method: str = 'lowpass', *, keep: float | int = 0.6666666666666666, alpha: float = 36.0, order: float = 8, axis: int | str | tuple | list | None = None) NDArray[source]¶
Damp or remove the high modes of a meshed function.
See
numgrids.spectral.spectral_filter().- Parameters:
f (NDArray) – Meshed function of shape
grid.shape.method (str) –
"lowpass"(default): keep the lowest modes and remove the others;"exponential": multiply mode k byexp(-alpha * (k / k_max) ** order).keep (float or int) – For
"lowpass": the fraction of the modes of each axis that is kept (default 2/3, the rule for dealiasing products), or their number.alpha (float) – Strength and exponent of the exponential filter.
order (float) – Strength and exponent of the exponential filter.
axis (int, str, sequence of those, or None) – The axis or axes to filter (default: all spectral axes).
- interpolate(f: NDArray, locations, method: str = 'cubic')[source]¶
Interpolate a meshed function at arbitrary locations.
See
Interpolatorfor the accepted locations and method values.
- plot(f: NDArray | None = None, ax=None, **kwargs)[source]¶
Visualize the grid points, or a meshed function on the grid.
Without f, the grid points are shown (pairwise projections).
With f, the function is plotted: as a line plot for 1D grids, as a color plot for 2D grids (in Cartesian space for curvilinear grids), and as a 2D slice for higher-dimensional grids. See
numgrids.plots.plot_field()for all options.- Returns:
Only when f is given.
- Return type:
matplotlib.axes.Axes
- animate(frames: NDArray, t: NDArray | None = None, **options)[source]¶
Animate a time-dependent meshed function on the grid (requires matplotlib).
frames has the shape
(nt, *grid.shape), t holds the times of the frames (shown in the title). The frames are drawn likeplot()draws a single function. Seenumgrids.plots.animate_field()for all options.- Return type:
matplotlib.animation.FuncAnimation
- property faces: dict¶
Return a dictionary of all boundary faces.
Keys follow the pattern
'{axis_index}_{side}', e.g.'0_low','0_high'. For named axes,'{name}_{side}'(e.g.'x_low') is accepted as well. Periodic axes are skipped, and radial axes through the origin only have a"high"face.
- property boundary: NDArray¶
Returns a binary mask of the shape of the grid indicating the grid points on the boundary.
- property interior: NDArray¶
Boolean mask of the grid points not on the boundary.
- refine() Grid[source]¶
Returns a new grid with twice the number of grid points in each direction.
The grid type (e.g.
SphericalGrid) is preserved.
- coarsen() Grid[source]¶
Returns a new grid with half the number of grid points in each direction.
The grid type (e.g.
SphericalGrid) is preserved.
- refine_axis(axis_index: int | str, factor: float = 2.0) Grid[source]¶
Return a new grid with one axis resized by the given factor.
- Parameters:
- Returns:
A new grid (of the same type) with the specified axis resized.
- Return type:
- Raises:
ValueError – If axis_index is out of range or factor is not positive.
- property meshed_indices: list[NDArray]¶
Returns a tuple of length grid.ndims, where each item in the tuple is an array of shape grid.shape. Each item stores the indices of each grid point for a given axis.
For example, if you have a 2D grid with 4 points along axis 0 and 3 points along axis 1, the indices along axis 0 are [0, 1, 2, 3], the indices along axis 1 are [0, 1, 2]. meshed_indices returns a tuple (I, J), where I and J both have shape (4, 3). I contains the “slot-0” indices, J contains the “slot-1” indices.
This generalizes for grids in higher dimensions, of course.
- property index_tuples: NDArray¶
Returns an array A of shape
(*grid.shape, grid.ndims).For example, in case of a 2D grid, A[i, j] contains the index tuple (i, j).
- property coord_tuples: NDArray¶
Returns an array A of shape
(*grid.shape, grid.ndims)with all the coordinate tuples.For example, in case of a 2D grid, A[i, j] contains the tuple (x, y), where x and y are the coordinates of the grid point (i, j).
- save(path: str | Path, **data: NDArray) None[source]¶
Save the grid (and optional meshed arrays) to a
.npzfile.See
numgrids.save_grid().
- static load(path: str | Path) tuple[Grid, dict[str, NDArray]][source]¶
Load a grid and its data arrays from a
.npzfile.See
numgrids.load_grid().
- to_xarray(**fields: NDArray)[source]¶
Convert meshed arrays on this grid to an
xarray.Dataset.See
numgrids.to_xarray().
- to_vtk(path: str | Path, **fields) Path[source]¶
Write meshed arrays on this grid to a VTK file (
.vts) for ParaView.Scalar fields are arrays of grid shape, vector fields tuples with one array per axis. See
numgrids.vtk.write_vtk().- Returns:
The path of the file written.
- Return type:
Path
- to_vtk_series(path: str | Path, frames=None, t=None, **fields) Path[source]¶
Write a time series on this grid as VTK files with a
.pvdcollection file.frames has the shape
(nt, *grid.shape)and is stored under the name given byname=(default"u"), t holds the times. Further fields can be passed by name. Seenumgrids.vtk.write_vtk_series().- Returns:
The path of the collection file.
- Return type:
Path
- class numgrids.MultiGrid(*axes, min_size: int = 2, **named_axes)[source]¶
Represents a multigrid, a hierarchical set of grids of different resolutions for the same domain.
Besides holding the grids (
levels) and transferring data between them (transfer()), a multigrid can solve linear boundary value problems on its finest grid with the multigrid method (solve()), whose cost grows only linearly with the number of grid points.Examples
>>> from numgrids import MultiGrid, equidistant >>> mg = MultiGrid(x=equidistant(33, 0, 1), y=equidistant(33, 0, 1), min_size=5) >>> [level.shape for level in mg.levels] [(33, 33), (17, 17), (9, 9), (5, 5)] >>> u = mg.solve(lambda grid: grid.laplacian_operator(), rhs=1.0, bcs=0) # lap u = 1 >>> round(float(u.min()), 4) -0.0737
Constructor.
The grids of the various resolutions are stored in the property levels.
- Parameters:
axes (one or more Axis objects) – The axes for the grid with highest resolution. Starting from the grid with the highest resolution (level 0), the constructor will create different levels of resolution. Each additional level contains a grid with about half the grid points in each direction. All axis types are supported (
EquidistantAxis,ChebyshevAxis,LogAxis, and mixtures thereof). Axis properties such asperiodicandnameare preserved at every level.min_size (positive int) – This parameter sets a lower bound for the coarsest grid in the multigrid. At the lowest resolution, each axis must have at least min_size grid points.
named_axes (Axis objects as keyword arguments) – Further axes, appended after the positional ones. The keyword is used as the axis name, as for
Grid.
- property levels: list[Grid]¶
Returns a list of grids with different resolution levels.
levels[0] => finest grid levels[-1] => coarsest grid
- transfer(f: NDArray, level_from: int, level_to: int, method: str = 'linear') NDArray[source]¶
Coarsen or refine an array on a grid by one level.
- Parameters:
f (numpy.ndarray) – An array given on the grid at level = level_from.
level_from (int) – The level of the grid on which f is given.
level_to (int) – The level to which f shall be refined or coarsened.
method (str) – Coarsening and refinement involves interpolation. This is the interpolation order.
- Return type:
The coarsened or refined array.
- solver(operator: Callable[[Grid], Operator], bcs=None, **options)[source]¶
Set up a reusable multigrid solver for an operator and boundary conditions.
Use this instead of
solve()to solve for several right-hand sides: the setup is done only once.- Parameters:
- Returns:
Call its
solve()method with the right-hand side.- Return type:
- solve(operator: Callable[[Grid], Operator], rhs=0.0, bcs=None, *, u0=None, tol: float = 1e-08, maxiter: int = 100, pre: int = 2, post: int = 2, cycle: str = 'V', method: str = 'gmres', low_order: bool = True, return_info: bool = False)[source]¶
Solve the linear problem
L u = rhson the finest grid with multigrid.In contrast to
Operator.solve(sparse LU), time and memory grow only linearly with the number of grid points, which makes large problems feasible, in particular in 3D. The axes must be equidistant (non-periodic) or logarithmic. SeeMultiGridSolverfor the method and its limitations.- Parameters:
operator (callable) –
operator(grid)returns the operator L on the given grid as anOperator, e.g.lambda grid: grid.laplacian_operator(). It is called for every level, so build coefficients from the grid passed in (grid.evaluate).rhs (float, NDArray or callable) – Right-hand side on the finest grid. Scalars are broadcast; callables are called with the meshed coordinates.
bcs (optional) – Boundary conditions in any form accepted by
resolve_bcs(), e.g.0or{"x_low": 0, "x_high": Neumann(1)}. Every boundary face needs a condition.u0 (float, NDArray or callable, optional) – Initial guess (default zero).
tol (float) – Tolerance for the residual norm relative to the norm of the right-hand side.
maxiter (int) – Maximum number of iterations (multigrid cycles).
pre (int) – Number of smoothing sweeps before and after the coarse-grid correction.
post (int) – Number of smoothing sweeps before and after the coarse-grid correction.
cycle (str) –
"V"(default) or"W".method (str) –
"gmres"(default): the multigrid cycle preconditions GMRES;"plain": the cycle is iterated on its own.low_order (bool) – Build the multigrid cycle from second-order stencils (default); the solution is still that of the operator as given.
return_info (bool) – Also return a
MultiGridInfowith the number of iterations and the residual history.
- Returns:
The solution on the finest grid.
- Return type:
NDArray or tuple of (NDArray, MultiGridInfo)
- Raises:
numgrids.multigrid.MultiGridError – If the iteration does not converge. The exception holds the last iterate and the residual history.
Examples
>>> import numpy as np >>> from numgrids import MultiGrid, equidistant >>> mg = MultiGrid(equidistant(65, 0, 1), equidistant(65, 0, 1)) >>> exact = lambda x, y: np.sin(np.pi * x) * np.exp(y) >>> f = lambda x, y: (1 - np.pi ** 2) * exact(x, y) >>> u, info = mg.solve(lambda grid: grid.laplacian_operator(), f, ... bcs=lambda coords: exact(*coords), return_info=True) >>> bool(np.abs(u - mg.levels[0].evaluate(exact)).max() < 1e-7) True >>> info.converged True
Multigrid solver¶
MultiGrid.solve and
MultiGrid.solver are front ends of the
solver in numgrids.multigrid.
- class numgrids.multigrid.MultiGridSolver(multigrid: MultiGrid, operator: Callable[[Grid], Operator], bcs=None, *, pre: int = 2, post: int = 2, cycle: str = 'V', low_order: bool = True)[source]¶
Geometric multigrid solver for \(L u = f\) with boundary conditions.
The solver is set up once for an operator and a set of boundary conditions and can then solve for any number of right-hand sides with
solve(). For a single solve,MultiGrid.solveis more convenient.One multigrid cycle smooths the error with damped Jacobi sweeps, restricts the residual to the next coarser grid (full weighting), solves there recursively – by sparse LU on the coarsest grid –, interpolates the correction back (linearly) and smooths again. By default the cycle is not iterated on its own but preconditions GMRES.
- Parameters:
multigrid (MultiGrid) – The grid hierarchy. The problem is solved on its finest grid; coarser levels are used as long as every axis has at least 5 points (8 for
low_order=False); a largermin_sizeof theMultiGridstops the coarsening earlier. All axes must be equidistant (non-periodic) or logarithmic, because only finite differences give sparse operators.operator (callable) –
operator(grid)returns the operator \(L\) on the given grid as anOperator, e.g.lambda grid: grid.laplacian_operator(). It is called once per level (forlow_order=Trueonce more, see below), so coefficients must be built from the grid passed in, e.g. withgrid.evaluate.bcs (optional) – Boundary conditions in any form accepted by
resolve_bcs(). Every boundary face needs a condition. Values may be scalars, callables or arrays on the faces of the finest grid (coarser levels only need the type of the conditions).pre (int) – Number of smoothing sweeps before and after the coarse-grid correction (default 2 each).
post (int) – Number of smoothing sweeps before and after the coarse-grid correction (default 2 each).
cycle (str) –
"V"(default) or"W": one or two coarse-grid corrections per level.low_order (bool) – If true (default), the multigrid cycle is built from second-order finite-difference stencils, whatever accuracy order the operator asks for; the cycle then only preconditions the iteration for the operator as given, whose solution is the one returned. The compact second-order stencils are what a point smoother needs; the one-sided stencils that higher orders use next to the boundary (already for the default
acc=4) make it diverge. To this end, operator is also called with grids whose finite differences are limited to second order. Withlow_order=Falsethe cycle uses the operator exactly as given on all levels – sensible only if it is of second order anyway.
- Raises:
TypeError – If an axis is spectral (Chebyshev, periodic, …) or operator is not a function of the grid.
ValueError – If a boundary face has no condition, the operator cannot be built on a level, or the problem is singular (e.g. only Neumann conditions).
Notes
The number of iterations is independent of the grid size for elliptic operators with comparable grid spacing in all directions: Laplacians, variable coefficients and lower-order terms included. Operators of second order (
acc=2) need about 10 iterations; the default fourth-order operators need 20 to 50, because the second-order cycle approximates their one-sided stencils next to the boundary less well.Point smoothers do not cope with strongly anisotropic problems (grid spacings or coefficients that differ by more than a factor of about 4 between directions), with indefinite problems (Helmholtz) or with second derivatives written as products of first derivatives; then many more iterations are needed or the solver fails with a
MultiGridError.Examples
A variable-coefficient problem \(-\nabla^2 u + (1 + x^2) u = 1\) with mixed boundary conditions:
>>> from numgrids import MultiGrid, Neumann, equidistant >>> from numgrids.multigrid import MultiGridSolver >>> mg = MultiGrid(x=equidistant(33, 0, 1), y=equidistant(33, 0, 1)) >>> def operator(grid): ... c = grid.evaluate(lambda x, y: 1 + x ** 2) ... return -grid.laplacian_operator() + c >>> solver = MultiGridSolver(mg, operator, bcs={"all": 0, "x_high": Neumann(0)}) >>> u = solver.solve(1.0) >>> u.shape (33, 33)
- solve(rhs=0.0, *, u0=None, tol: float = 1e-08, maxiter: int = 100, method: str = 'gmres', return_info: bool = False) NDArray | tuple[NDArray, MultiGridInfo][source]¶
Solve \(L u = \text{rhs}\) subject to the boundary conditions.
- Parameters:
rhs (float, NDArray or callable) – Right-hand side on the finest grid. Scalars are broadcast; callables are called with the meshed coordinates.
u0 (float, NDArray or callable, optional) – Initial guess (default zero). Its boundary values are replaced by those that satisfy the boundary conditions.
tol (float) – Stop when the residual norm of the linear system falls below tol times the norm of its right-hand side. Known boundary values count as part of the right-hand side (see
MultiGridInfo), so that the tolerance means the same for problems driven by boundary values as for those driven by rhs.maxiter (int) – Maximum number of iterations (multigrid cycles).
method (str) –
"gmres"(default): GMRES with one multigrid cycle as preconditioner – robust, also for higher-order operators and Neumann or Robin conditions."plain": repeat the multigrid cycle on its own; about as fast for second-order operators with Dirichlet conditions, otherwise much slower or divergent.return_info (bool) – Also return a
MultiGridInfowith the number of iterations and the residual history.
- Returns:
The solution, of shape
grid.shape.- Return type:
NDArray or tuple of (NDArray, MultiGridInfo)
- Raises:
MultiGridError – If the tolerance is not reached within maxiter iterations. The exception holds the last iterate and the residual history.
- as_preconditioner() LinearOperator[source]¶
One multigrid cycle as a preconditioner for SciPy’s iterative solvers.
The returned
LinearOperatormaps a flattened residual to an approximate solution of the systemoperator(grid).with_bcs(rhs, bcs)and can be passed asMto e.g.scipy.sparse.linalg.bicgstab().
- class numgrids.multigrid.MultiGridInfo(iterations: int, residuals: list[float], converged: bool, shapes: tuple[tuple[int, ...], ...])[source]¶
Convergence record of a multigrid solve.
- residuals¶
Relative residual norm \(\|b - A u\|_2 / \|b\|_2\) of the linear system after each iteration;
residuals[0]belongs to the initial guess. Here \(A u = b\) is the system for the interior values: known boundary values count as part of the right-hand side \(b\).