Time Evolution & Analysis

Method-of-lines time integration and convergence studies.

numgrids.evolve(grid: Grid, rhs, u0, t_span: tuple[float, float], t_eval: Sequence[float] | NDArray | None = None, bcs=None, method: str = 'RK45', source=None, linear=None, dt: float | None = None, **kwargs) → EvolutionResult[source]

Integrate \(\partial_t u = F(t, u)\) in time on a grid.

Parameters:
  • grid (Grid) – The grid.

  • rhs (callable, Operator or nested list of operators) –

    The right-hand side. Either a callable rhs(t, u) returning an array of shape grid.shape, or – for coupled systems with initial state (u0, v0, ...) – rhs(t, u, v, ...) returning a tuple of arrays. For linear problems an Operator L can be passed directly, meaning \(\partial_t u = L u\) (its sparse matrix is used as Jacobian for implicit methods). Linear systems are given as a nested list of blocks, rhs[i][j] acting on field j in the equation of field i; a block is an Operator, a matrix, an array of grid shape (multiplication), a scalar or None (zero). The wave equation \(u_t = v,\ v_t = \nabla^2 u\) is [[None, 1], [L, None]].

    With linear, rhs is only the nonlinear part \(N(t, u)\) of the right-hand side (a callable as above, or None for none).

  • u0 (NDArray or tuple of NDArray) – Initial state (one array, or a tuple of arrays for coupled fields). Complex arrays are supported by explicit methods, by "expm" and by the methods for semilinear problems.

  • t_span ((float, float)) – Start and end time.

  • t_eval (array_like, optional) – Times at which to store the solution. Defaults to the solver’s internal time steps; for "expm" and the fixed-step methods to the start and end time.

  • bcs (optional) –

    Boundary conditions, in any form accepted by resolve_bcs(): Dirichlet, Neumann or Robin conditions. They hold at every instant: the boundary values are not evolved but computed from the interior values so that the conditions are satisfied (for Dirichlet conditions they are simply the prescribed values). The initial state is adjusted accordingly. Values that change in time are wrapped in TimeDependent, e.g. {"x_low": TimeDependent(lambda t: np.sin(t))} or Neumann(TimeDependent(flux)).

    For coupled systems, pass a tuple with one specification per field (None for a field without conditions). A single specification applies to the first field, and the other fields are held fixed on the same boundary points (as suited for second-order equations written as \(u_t = v,\ v_t = \ldots\)).

  • method (str) –

    Integration method of scipy.integrate.solve_ivp(). Use an implicit method ("BDF", "Radau") for stiff problems such as diffusion.

    "expm" is an exponential integrator for linear problems (rhs an Operator or a list of blocks) with constant boundary values and source: the solution \(u(t) = e^{tL} u_0\) (plus the contribution of source and boundary values) is evaluated directly at the output times, without time stepping error, for stiff problems and complex fields alike. It preserves the norm in Schrödinger-type problems.

    "ETDRK4", "ETDRK2", "ETD1" and "IMEX2" integrate stiff semilinear problems \(\partial_t u = L u + N(t, u)\) with a fixed time step dt; they need the linear part as linear. See the notes below.

  • source (array, callable or tuple, optional) – A source term added to the right-hand side, \(\partial_t u = F(t, u) + s\): an array of grid shape, or a callable source(t) returning one (for coupled systems a tuple with one entry per field, None for no source). With an Operator right-hand side this keeps the problem linear, so that implicit methods still use the exact Jacobian.

  • linear (Operator, callable or nested list, optional) –

    The stiff linear part L of a semilinear problem \(\partial_t u = L u + N(t, u)\), for the methods "ETDRK4", "ETDRK2", "ETD1" and "IMEX2": an Operator, or for coupled systems a nested list of blocks as described for rhs. Typically it holds the highest derivatives (diffusion, dispersion), while rhs holds the nonlinear terms.

    On a grid that is periodic along all axes, the linear part (or a block of it) can also be given by its Fourier symbol: a function of the meshed wave numbers (\(2\pi m / L\) along an axis with the period L), e.g. lambda kx, ky: -(kx**2 + ky**2)**2 for \(-\nabla^4\). No matrix is built then, which matters for operators with mixed derivatives in two or three dimensions: their matrices are dense.

  • dt (float, optional) – The time step of the methods for semilinear problems (required there). Every interval between two output times is divided into equal steps that are not longer than dt, so the output times are hit exactly.

  • **kwargs – Passed on to scipy.integrate.solve_ivp() (e.g. rtol, atol, max_step). "expm" and the fixed-step methods take no further options.

Return type:

EvolutionResult

Notes

The methods for semilinear problems \(\partial_t u = L u + N(t, u)\) do not restrict the time step by the stiffness of L, and they never solve a nonlinear system:

  • "ETDRK4" – exponential time differencing Runge-Kutta scheme of order 4 (the scheme of Cox and Matthews in the variant of Krogstad, which is more accurate for stiff problems). The linear part is integrated exactly, the nonlinear part with four evaluations per step. The method of choice in most cases.

  • "ETDRK2", "ETD1" – the schemes of order 2 and 1 (exponential Euler method) with two and one evaluations per step.

  • "IMEX2" – implicit-explicit Runge-Kutta scheme of order 2 (ARS(2,2,2) of Ascher, Ruuth and Spiteri): an L-stable diagonally implicit scheme for the linear part, with two linear solves per step, and an explicit scheme for the nonlinear part. It needs no matrix functions, only solutions of linear systems, and hence also works for large problems.

On a grid that is periodic along all axes, a linear part with constant coefficients (and no boundary conditions) is diagonal in Fourier space. This is detected (or stated, by passing the Fourier symbol as linear), and the time stepping is then done on the Fourier coefficients with fast Fourier transforms: the functions of L are evaluated for each mode separately, by their Taylor series for small arguments and by the recurrence \(\varphi_{k+1}(z) = (\varphi_k(z) - 1/k!)/z\) otherwise (for a linear part that couples the fields, as functions of one small matrix per mode). Problems with many thousands of unknowns are cheap this way.

Otherwise the ETD methods compute the matrix functions \(\varphi_k(hL)\) as dense matrices, once per step size: by an eigendecomposition if the matrix is Hermitian or skew-Hermitian, else by scaling and squaring (a Taylor polynomial of the matrix divided by a power of two, followed by repeated doubling). This is limited to 2500 unknowns; beyond that, use "IMEX2", which solves its linear systems like Operator.solve (single field) or by dense or sparse LU factorization (systems).

Boundary conditions are imposed as for the other methods; their constant values and constant sources are part of the linear problem that is solved exactly by the ETD methods. With boundary values that change in time, expect the order 3 instead of 4 from "ETDRK4". Without a nonlinear part and with constant boundary values and sources, the ETD methods reproduce "expm".

Examples

Heat equation on a rod with fixed ends:

>>> import numpy as np
>>> from numgrids import Grid, chebyshev, evolve
>>> grid = Grid(x=chebyshev(24, 0, 1))
>>> u0 = np.sin(np.pi * grid.coords)
>>> res = evolve(grid, 0.1 * grid.laplacian_operator(), u0, (0, 1),
...              bcs=0, method="BDF", t_eval=[0, 1], rtol=1e-8, atol=1e-10)
>>> exact = np.exp(-0.1 * np.pi ** 2) * u0
>>> bool(np.allclose(res.final, exact, atol=1e-6))
True

An insulated rod (no heat flux through the ends) keeps its total heat:

>>> from numgrids import Neumann
>>> u0 = 1 + np.cos(np.pi * grid.coords)
>>> res = evolve(grid, grid.laplacian_operator(), u0, (0, 1), bcs=Neumann(0),
...              method="BDF", rtol=1e-8, atol=1e-10)
>>> round(grid.integrate(res.final), 6), round(grid.integrate(u0), 6)
(1.0, 1.0)

A soliton of the Korteweg-de Vries equation \(u_t + 6 u u_x + u_{xxx} = 0\) moves with the speed c without changing its shape. The third derivative is the stiff linear part:

>>> from numgrids import periodic
>>> grid = Grid(x=periodic(128, -10, 10))
>>> x = grid.coords
>>> c = 4.0
>>> soliton = lambda x0: c / 2 / np.cosh(np.sqrt(c) / 2 * (x - x0)) ** 2
>>> D = grid.diff_operator()
>>> res = evolve(grid, lambda t, u: -3 * D(u ** 2), soliton(-2.0), (0, 1),
...              linear=-grid.diff_operator(3), method="ETDRK4", dt=0.005)
>>> bool(np.allclose(res.final, soliton(2.0), atol=1e-4))
True
class numgrids.EvolutionResult(t: NDArray, u: Any, success: bool, message: str, sol: Any = None, grid: Any = None)[source]

Result of evolve().

t

Time points, shape (nt,).

Type:

NDArray

u

The solution at the time points, shape (nt, *grid.shape). For coupled systems, a tuple with one such array per field.

Type:

NDArray or tuple of NDArray

success

Whether the integration succeeded.

Type:

bool

message

Status message of the solver.

Type:

str

sol

The raw result of scipy.integrate.solve_ivp() (None for method="expm" and the fixed-step methods for stiff nonlinear problems).

Type:

object

grid

The grid of the solution, used by animate() and to_vtk().

Type:

Grid

property final

The solution at the last time point (array, or tuple for systems).

animate(field: int = 0, **options)[source]

Animate the solution in time (requires matplotlib).

Parameters:
  • field (int) – For coupled systems: the index of the field to animate (default 0, the first one).

  • **options – Options of numgrids.plots.animate_field(), e.g. fps, vmin, vmax, cmap, title, part="abs" for complex fields or save="movie.gif".

Return type:

matplotlib.animation.FuncAnimation

Examples

>>> import numpy as np
>>> from numgrids import Grid, chebyshev, evolve
>>> grid = Grid(x=chebyshev(24, 0, 1))
>>> res = evolve(grid, 0.1 * grid.laplacian_operator(), np.sin(np.pi * grid.coords), (0, 1),
...              bcs=0, method="BDF", t_eval=np.linspace(0, 1, 21))
>>> anim = res.animate()
>>> anim.save("heat.gif")
to_vtk(path, name: str | Sequence[str] = 'u', **options)[source]

Write the solution as a time series of VTK files for ParaView.

One .vts file per time point plus a .pvd collection file with the time values, see numgrids.vtk.write_vtk_series().

Parameters:
  • path (str or Path) – The collection file (suffix .pvd).

  • name (str or sequence of str) – Name of the field in the files (default "u"). For coupled systems, one name per field; a single name is numbered ("u0", "u1", …).

  • **options – binary and close, see numgrids.vtk.write_vtk().

Returns:

The path of the collection file.

Return type:

pathlib.Path

numgrids.convergence_study(make_grid: Callable[[int], Grid], func: Callable[[Grid], NDArray | float], ns: Sequence[int], exact: Callable[[Grid], NDArray | float] | float | None = None, norm: str = 'max', interpolation: str = 'spectral') → ConvergenceResult[source]

Measure the error of a computation for a sequence of resolutions.

Parameters:
  • make_grid (callable) – make_grid(n) -> Grid, creates a grid for resolution n.

  • func (callable) – func(grid) returns the quantity of interest: a scalar (e.g. an integral or eigenvalue) or an array of shape grid.shape.

  • ns (sequence of int) – The resolutions to test.

  • exact (callable or float, optional) – The exact result: a number, or exact(grid) returning a scalar or an array. If omitted, the result on the finest grid serves as reference (it is then not included in the output); array results are interpolated from the finest grid.

  • norm (str) – "max", "l2" or "mean" (for array-valued results).

  • interpolation (str) – Interpolation method used when comparing array results without exact (default "spectral").

Return type:

ConvergenceResult

Examples

>>> import numpy as np
>>> from numgrids import Grid, equidistant, convergence_study
>>> res = convergence_study(
...     lambda n: Grid(equidistant(n, 0, 1)),
...     lambda g: g.diff(np.sin(g.coords), acc=2),
...     ns=[20, 40, 80, 160],
...     exact=lambda g: np.cos(g.coords),
... )
>>> round(res.order)
2
class numgrids.ConvergenceResult(ns: NDArray, errors: NDArray, order: float, rate: float, orders: NDArray)[source]

Result of convergence_study().

ns

Resolutions (as passed to the grid factory).

Type:

NDArray

errors

Error for each resolution.

Type:

NDArray

order

Fitted algebraic convergence order p in error ~ n**(-p) (least-squares fit in log-log space). For spectrally converging methods this keeps growing with n; see rate.

Type:

float

rate

Fitted exponential rate c in error ~ exp(-c n).

Type:

float

orders

Pairwise orders between consecutive resolutions.

Type:

NDArray

plot(ax=None, **kwargs)[source]

Log-log plot of error versus resolution (requires matplotlib).

Plotting

Requires the optional matplotlib dependency (pip install numgrids[plot]).

numgrids.plots.plot_field(grid: Grid, f: NDArray, ax=None, fixed: dict | None = None, cartesian: bool = True, colorbar: bool = True, **kwargs)[source]

Plot a meshed function on a grid.

  • 1D grids: line plot of f over the coordinate.

  • 2D grids: color plot (pcolormesh). Curvilinear grids with a Cartesian mapping (e.g. PolarGrid) are drawn in Cartesian space, with periodic axes closed seamlessly.

  • Higher dimensions: a 2D slice; all but two axes are fixed via fixed (default: the middle index of the trailing axes).

Parameters:
  • grid (Grid) – The grid.

  • f (NDArray) – Meshed function values of shape grid.shape (real part is plotted for complex arrays).

  • ax (matplotlib.axes.Axes, optional) – Axes to draw into; a new figure is created if omitted.

  • fixed (dict, optional) – For grids with more than two dimensions: {axis: index} for the axes to fix (axis given by index or name). Exactly ndims - 2 axes must be fixed.

  • cartesian (bool) – Draw curvilinear 2D grids in Cartesian space (default True).

  • colorbar (bool) – Add a colorbar for 2D plots (default True).

  • **kwargs – Passed on to ax.plot (1D) or ax.pcolormesh (2D).

Return type:

matplotlib.axes.Axes

numgrids.plots.animate_field(grid: Grid, frames: NDArray, t: NDArray | None = None, ax=None, fixed: dict | None = None, cartesian: bool = True, colorbar: bool = True, part: str | Callable[[NDArray], NDArray] = 'real', interval: float | None = None, fps: float | None = None, vmin: float | None = None, vmax: float | None = None, ylim: tuple[float, float] | None = None, title: str | None = None, repeat: bool = True, save: str | Path | None = None, **kwargs) → FuncAnimation[source]

Animate a time-dependent field on a grid.

The frames are drawn like plot_field() draws a single field: a line for 1D grids, a color plot for 2D grids (in Cartesian space for curvilinear grids) and a 2D slice for higher dimensions. The axis limits (1D) and the color scale (2D) are the same in all frames; by default they cover the values of all frames.

Parameters:
  • grid (Grid) – The grid.

  • frames (NDArray) – The field at successive times, shape (nt, *grid.shape), e.g. the attribute u of an EvolutionResult.

  • t (array_like, optional) – The times of the frames, shape (nt,). They are shown in the title as t = ....

  • ax (matplotlib.axes.Axes, optional) – Axes to draw into; a new figure is created if omitted.

  • fixed (dict, optional) – The slice to show for grids with more than two dimensions, see plot_field().

  • cartesian (bool) – Draw curvilinear 2D grids in Cartesian space (default True).

  • colorbar (bool) – Add a colorbar for 2D plots (default True).

  • part (str or callable) – What to show of the values: "real" (default), "imag", "abs" or "abs2" (the squared modulus), or a function that is applied to the frames. Only matters for complex fields.

  • interval (float, optional) – Delay between frames in milliseconds (default 50).

  • fps (float, optional) – Frames per second, as an alternative to interval.

  • vmin (float, optional) – Limits of the color scale (2D) or of the vertical axis (1D). Default: the smallest and largest value of all frames.

  • vmax (float, optional) – Limits of the color scale (2D) or of the vertical axis (1D). Default: the smallest and largest value of all frames.

  • ylim ((float, float), optional) – Limits of the vertical axis for 1D grids, in place of vmin and vmax.

  • title (str, optional) – Title of the plot; the time is appended to it.

  • repeat (bool) – Start again after the last frame (default True).

  • save (str or Path, optional) – Also save the animation to this file, see save_animation().

  • **kwargs – Passed on to ax.plot (1D) or ax.pcolormesh (2D), e.g. cmap.

Returns:

Keep a reference to it: the animation stops when it is garbage collected. In a notebook, show it with HTML(anim.to_jshtml()).

Return type:

matplotlib.animation.FuncAnimation

Examples

>>> import numpy as np
>>> from numgrids import Grid, periodic
>>> grid = Grid(x=periodic(64))
>>> t = np.linspace(0, 2 * np.pi, 40)
>>> frames = np.sin(grid.coords[None, :] - t[:, None])      # a travelling wave
>>> anim = grid.animate(frames, t)
>>> anim.save("wave.gif")
numgrids.plots.save_animation(anim: FuncAnimation, path: str | Path, fps: float | None = None, writer=None, **kwargs) → Path[source]

Save an animation to a file, choosing the writer from the file name.

  • .gif: written with Pillow (installed together with matplotlib).

  • .html: a self-contained page with playback controls (the output of anim.to_jshtml()); needs no additional software.

  • anything else (e.g. .mp4): the default movie writer of matplotlib, usually ffmpeg, which has to be installed separately.

Parameters:
  • anim (matplotlib.animation.Animation) – The animation, e.g. from animate_field().

  • path (str or Path) – Destination file.

  • fps (float, optional) – Frames per second of the file. Defaults to the speed of the animation.

  • writer (str or matplotlib.animation.AbstractMovieWriter, optional) – The writer to use instead of the one chosen from the file name.

  • **kwargs – Passed on to anim.save (e.g. dpi).

Returns:

The path of the file written.

Return type:

Path

Raises:

RuntimeError – If the writer is not available on this system.