Differential Operators

class findiff.Diff(axis=0, grid=None, periodic=False, acc=2, scheme=None, compact=None, spectral=False, boundary='one-sided')

Represents a partial derivative (along one axis).

For higher derivatives, exponentiate. For mixed partial derivatives, multiply. See examples below.

Parameters

axisint

The 0-based index of the axis along which to differentiate.

gridfloat, array or GridAxis, optional

The grid along axis: a number is the (constant) grid spacing, a 1D array the coordinates of a non-uniform grid. Can also be set later with set_grid().

periodicbool

Whether the grid is periodic along axis.

accint

The (minimum) accuracy order, a positive even number. Default 2.

schemeCompactScheme, optional

Use this compact (implicit) finite difference scheme.

compactint, optional

Use a compact scheme with this (odd) number of left-hand side points, determined from acc (see the guide on compact finite differences).

spectralbool

With compact, use a scheme with spectral-like resolution instead of maximal accuracy order.

boundarystr

How points near a non-periodic boundary are treated on equidistant grids: "one-sided" (default) uses one-sided stencils of order acc; "centered" uses the widest centered stencil that fits. The latter is less accurate near the boundary but keeps time-dependent problems stable for high acc.

Examples

Set up grid (equidistant here):
>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
The array to differentiate
>>> f = np.sin(x) # as an example
Define the first derivative:
>>> from findiff import Diff
>>> d_dx = Diff(0)
>>> d_dx.set_grid({0: x[1] - x[0]})
Now apply it:
>>> df_dx = d_dx(f)
The second derivative is constructed by exponentiation:
>>> d2_dx2 = d_dx ** 2
>>> d2f_dx2 = d2_dx2(f)
In multiple dimensions with meshed grids, the usage is accordingly:
>>> x = y = z = np.linspace(0, 10, 100)
>>> dx = dy = dz = x[1] - x[0]
>>> X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
>>> f = np.sin(X) * np.sin(Y) * np.sin(Z)
>>> d_dx = Diff(0)
>>> d_dy = Diff(1)
>>> d_dz = Diff(2)
>>> d3_dxdydz = d_dx * d_dy * d_dz
>>> d3_dxdydz.set_grid({0: dx, 1: dy, 2: dz})
>>> d3f_dxdydz = d3_dxdydz(f)
DEFAULT_ACC = 2
property axis
property differentiator
eigs(shape, k=6, which='SR', sigma=None, bc=None, M=None, **kwargs)

Compute k eigenvalues and eigenvectors of this operator.

Solves \(L u = \lambda u\) (standard) or \(L u = \lambda M u\) (generalized) using scipy.sparse.linalg.eigs for general (non-symmetric) matrices.

Parameters

shapetuple of ints

Grid shape.

kint

Number of eigenvalues to compute.

whichstr

Which eigenvalues: ‘SR’ (smallest real), ‘LR’, ‘SM’, ‘LM’.

sigmafloat or None

Shift for shift-invert mode.

bcBoundaryConditions or None

Boundary DOFs are eliminated (homogeneous Dirichlet).

MExpression or None

RHS operator for generalized problem.

kwargs

Passed to scipy.sparse.linalg.eigs.

Returns

eigenvaluesndarray of shape (k,)

Sorted by real part ascending.

eigenvectorsndarray

Shape (\\*shape, k). eigenvectors[..., i] is the i-th eigenvector on the grid.

eigsh(shape, k=6, which='SM', sigma=None, bc=None, M=None, **kwargs)

Compute k eigenvalues and eigenvectors of this symmetric operator.

Like eigs(), but uses scipy.sparse.linalg.eigsh which is more efficient for symmetric/Hermitian operators (e.g. Laplacian). Eigenvalues are guaranteed real.

Parameters

shapetuple of ints

Grid shape.

kint

Number of eigenvalues to compute.

whichstr

Which eigenvalues: ‘SM’ (smallest magnitude), ‘LM’, ‘SA’ (smallest algebraic), ‘LA’, ‘BE’.

sigmafloat or None

Shift for shift-invert mode.

bcBoundaryConditions or None

Boundary DOFs are eliminated (homogeneous Dirichlet).

MExpression or None

RHS operator for generalized problem.

kwargs

Passed to scipy.sparse.linalg.eigsh.

Returns

eigenvaluesndarray of shape (k,)

Real eigenvalues sorted ascending.

eigenvectorsndarray

Shape (\\*shape, k). eigenvectors[..., i] is the i-th eigenvector on the grid.

estimate_error(f, acc=None)

Estimate truncation error by comparing results at two accuracy orders.

Computes the derivative at accuracy order p and at p + 2, then uses the pointwise difference as an error estimate for the order-p result. The higher-order result is also returned as an improved (“extrapolated”) derivative.

Parameters

fnumpy.ndarray

The array to differentiate.

accint or None

Base accuracy order. If None, uses the operator’s current accuracy (default 2).

Returns

ErrorEstimate

Named tuple with fields:

  • derivative – result at the base accuracy order p.

  • error – estimated pointwise absolute truncation error.

  • extrapolated – result at accuracy order p + 2.

Raises

NotImplementedError

If compact finite difference schemes are in use.

Examples

>>> import numpy as np
>>> from findiff import Diff
>>> x = np.linspace(0, 2 * np.pi, 200)
>>> d_dx = Diff(0, x[1] - x[0])
>>> result = d_dx.estimate_error(np.sin(x))
>>> result.derivative.shape
(200,)
property grid

Returns the grid used.

matrix(shape)

Returns a matrix representation of the differential operator for a given grid shape.

property order

Returns the order of the derivative.

set_accuracy(acc)

Sets the requested accuracy for the given differential operator expression.

Parameters

acc: int

The accuracy order. Must be a positive, even number.

set_axis(axis: GridAxis)
set_grid(grid)

Sets the grid for the given differential operator expression.

Parameters

grid: dict | Grid

Specifies the grid to use. If a dict is given, an equidistant grid is assumed and the dict specifies the spacings along the required axes.

set_scheme(scheme: CompactScheme = None)

Allows to activate using compact (implicit) finite differences.

stencil(shape)

Returns a stencil representation of the differential operator for a given grid shape.

class findiff.Identity

The identity operator.