Axes¶
Axes are the one-dimensional building blocks from which grids are constructed.
Each axis defines a set of collocation points and the associated
differentiation and integration rules along a single coordinate direction.
Use the short-hand factories (chebyshev(),
equidistant(), periodic(),
logarithmic(), radial(),
colatitude(), semi_infinite(),
infinite()), the generic create_axis(),
or instantiate one of the concrete classes directly.
- numgrids.chebyshev(num_points: int, low: float = -1.0, high: float = 1.0, name: str | None = None) ChebyshevAxis[source]¶
Chebyshev axis on
[low, high](spectral accuracy, non-periodic).Examples
>>> from numgrids import chebyshev >>> chebyshev(5, 0, 1).coords.round(3) array([0. , 0.146, 0.5 , 0.854, 1. ])
- numgrids.equidistant(num_points: int, low: float = 0.0, high: float = 1.0, name: str | None = None) EquidistantAxis[source]¶
Equidistant, non-periodic axis on
[low, high](finite differences).Examples
>>> from numgrids import equidistant >>> equidistant(5, 0, 1).coords array([0. , 0.25, 0.5 , 0.75, 1. ])
- numgrids.periodic(num_points: int, low: float = 0.0, high: float = 6.283185307179586, name: str | None = None) EquidistantAxis[source]¶
Equidistant, periodic axis on
[low, high)(FFT spectral accuracy).The endpoint
highis identified withlowand not included.Examples
>>> from numgrids import periodic >>> periodic(4, 0, 1).coords array([0. , 0.25, 0.5 , 0.75])
- numgrids.logarithmic(num_points: int, low: float, high: float, name: str | None = None) LogAxis[source]¶
Logarithmically spaced axis on
[low, high](requireslow > 0).Examples
>>> from numgrids import logarithmic >>> logarithmic(3, 1, 100).coords array([ 1., 10., 100.])
- numgrids.radial(num_points: int, radius: float = 1.0, name: str | None = None) RadialAxis[source]¶
Radial axis on
[0, radius]that passes through the origin.Use it as the radial axis of a
PolarGrid,CylindricalGridorSphericalGridto cover a full disk, cylinder or ball. There is no grid point on the origin itself and no boundary condition is needed there; seeRadialAxis.Examples
>>> import numpy as np >>> from numgrids import PolarGrid, radial, periodic >>> disk = PolarGrid(radial(16, 1.0), periodic(32)) >>> round(disk.integrate(np.ones(disk.shape)), 12) == round(np.pi, 12) True >>> list(disk.faces) # only the rim is a boundary ['0_high']
- numgrids.colatitude(num_points: int, name: str | None = None) ColatitudeAxis[source]¶
Polar angle on
(0, pi)that passes through both poles.Use it as the polar axis of a
SphericalGridorSphericalSurfaceGridto cover the full sphere including the poles. There is no grid point on a pole and no boundary condition is needed there; seeColatitudeAxis.Examples
>>> import numpy as np >>> from numgrids import SphericalGrid, colatitude, periodic, radial >>> ball = SphericalGrid(radial(12, 1.0), colatitude(12), periodic(24)) >>> round(ball.integrate(np.ones(ball.shape)), 12) == round(4 / 3 * np.pi, 12) True >>> list(ball.faces) # only the surface of the ball is a boundary ['0_high']
- numgrids.semi_infinite(num_points: int, scale: float = 1.0, low: float = 0.0, name: str | None = None) SemiInfiniteAxis[source]¶
Axis on the half line
[low, inf)(spectral accuracy).The points are mapped Chebyshev points, \(x = \mathrm{low} + L (1 + \xi) / (1 - \xi)\) with the scale length \(L\) = scale: the first point is
low, half of the points lie in[low, low + scale]and there is no point at infinity. Functions on the axis should be smooth and decay (or tend to a constant) at infinity. Onlylowis a boundary; solutions that grow at infinity are excluded automatically. SeeSemiInfiniteAxis.- Parameters:
Examples
Radial levels of the hydrogen atom, \(-u''/2 - u/r = E u\) with \(u(0) = 0\):
>>> import numpy as np >>> from numgrids import Grid >>> from numgrids import semi_infinite >>> grid = Grid(r=semi_infinite(60, scale=10.0)) >>> r = grid.coords >>> list(grid.faces) # only r = 0 is a boundary ['0_low'] >>> V = np.zeros(grid.shape) >>> V[1:] = -1 / r[1:] >>> H = -0.5 * grid.diff_operator(2) + V >>> E, u = H.eig(k=3, bcs=0, which="SR") >>> np.round(E, 10) array([-0.5 , -0.125 , -0.05555556]) >>> round(grid.integrate(r ** 2 * np.exp(-r)), 10) 2.0
- numgrids.infinite(num_points: int, scale: float = 1.0, center: float = 0.0, name: str | None = None) InfiniteAxis[source]¶
Axis on the whole real line (spectral accuracy).
The points are mapped Chebyshev points, \(x = \mathrm{center} + L \xi / \sqrt{1 - \xi^2}\) with the scale length \(L\) = scale: half of the points lie in
[center - scale, center + scale]and there are no points at infinity. Functions on the axis should be smooth and decay at infinity. The axis has no boundary; solutions that grow at infinity are excluded automatically. SeeInfiniteAxis.- Parameters:
num_points (int) – Number of grid points.
scale (float) – Scale length of the map: about the half-width of the region in which the functions to be represented differ appreciably from their limits (3 to 5 standard deviations of a Gaussian).
center (float) – The point around which the grid points cluster.
name (str, optional) – The axis name.
Examples
Levels of the quantum harmonic oscillator, \(-u''/2 + x^2 u/2 = E u\):
>>> import numpy as np >>> from numgrids import Grid >>> from numgrids import infinite >>> grid = Grid(x=infinite(60, scale=4.0)) >>> x = grid.coords >>> list(grid.faces) # no boundary at all [] >>> H = -0.5 * grid.diff_operator(2) + 0.5 * x ** 2 >>> E, u = H.eig(k=4, which="SR") >>> np.round(E, 10) array([0.5, 1.5, 2.5, 3.5]) >>> bool(abs(grid.integrate(np.exp(-x ** 2)) - np.sqrt(np.pi)) < 1e-12) True
- numgrids.create_axis(axis_type: AxisType | str, num_points: int, low: float, high: float, **kwargs) Axis[source]¶
Create an Axis object of a given type.
- Parameters:
axis_type (AxisType or str) – The type of axis (equidistant, periodic, logarithmic, Chebyshev, etc.). Strings such as
"chebyshev","equidistant","equidistant_periodic"(or"periodic") and"log"are accepted, too.num_points (positive int) – Number of grid points along this axis.
low (float) – The lowest coordinate value on the axis.
high (float) – The highest coordinate value on the axis.
**kwargs – Further keyword arguments for the axis, e.g.
name, orscale(andcenter) for the axes on unbounded domains, whose infinite ends are given asnumpy.inf:create_axis("semi_infinite", 40, 0.0, np.inf, scale=2.0).
- Return type:
Axis object of specified type.
- class numgrids.AxisType(*values)[source]¶
Enumeration of available axis types.
Members¶
- EQUIDISTANT
Uniformly spaced grid points (non-periodic).
- EQUIDISTANT_PERIODIC
Uniformly spaced grid points with periodic boundary conditions.
- CHEBYSHEV
Chebyshev-node spacing for spectral accuracy on non-periodic domains.
- LOGARITHMIC
Logarithmically spaced grid points (requires
low > 0).- RADIAL
Radial coordinate through the origin of polar, cylindrical and spherical grids (requires
low = 0).- COLATITUDE
Polar angle of spherical grids through both poles (requires
low = 0, high = pi).- SEMI_INFINITE
The half line
[low, inf)(requireshigh = inf; keyword argumentscale).- INFINITE
The whole real line (requires
low = -inf, high = inf; keyword argumentsscaleandcenter).
- class numgrids.axes.EquidistantAxis(num_points: int, low: float = 0, high: float = 1, periodic: bool = False, **kwargs)[source]¶
Axis with uniformly spaced grid points.
Supports both non-periodic and periodic boundary conditions. When periodic, the FFT spectral differentiation method is used; otherwise classical finite differences are employed.
For a periodic axis the last point is not included (it would coincide with the first point after wrapping).
Create an equidistant axis.
- Parameters:
num_points (int) – Number of grid points.
low (float, optional) – Lower coordinate bound (default
0).high (float, optional) – Upper coordinate bound (default
1).periodic (bool, optional) – Whether to apply periodic boundary conditions (default
False).**kwargs – Additional keyword arguments forwarded to
Axis(e.g.name).
- class numgrids.axes.ChebyshevAxis(num_points: int, low: float = 0, high: float = 1, **kwargs)[source]¶
Axis with grid points at Chebyshev nodes.
The Chebyshev nodes are defined as
\[x_k = \cos\!\left(\frac{k\pi}{N-1}\right), \quad k = 0, \ldots, N-1\]on the canonical interval
[-1, 1], then linearly mapped to[low, high]. Points cluster near the boundaries, which avoids the Runge phenomenon and enables spectral accuracy for smooth, non-periodic functions.Constructor
- Parameters:
- class numgrids.axes.LogAxis(num_points: int, low: float, high: float, **kwargs)[source]¶
Axis with logarithmically spaced grid points.
Internally the coordinate is transformed to a uniform grid on
[ln(low), ln(high)]. Differentiation uses finite differences on the log-scale and applies the chain rule\[\frac{df}{dx} = \frac{1}{x}\,\frac{df}{d(\ln x)}\]This is useful for problems where fine resolution is needed near the lower boundary (e.g. radial coordinates close to zero).
lowmust be strictly positive.Constructor for LogAxis
- Parameters:
- class numgrids.axes.RadialAxis(num_points: int, low: float = 0.0, high: float = 1.0, **kwargs)[source]¶
Radial axis that passes through the coordinate origin.
Use this axis for the radial coordinate of a
PolarGrid,CylindricalGridorSphericalGridto cover a full disk, cylinder or ball, including the center.The points are the positive half of
2 * num_pointsChebyshev nodes on the diameter \([-R, R]\); no point lies exactly on the origin, so there is no coordinate singularity. A point \((-r, \varphi)\) is the same as \((r, \varphi + \pi)\), so derivatives along the axis are computed on the whole diameter with the values of the antipodal half supplied by the grid (Fornberg’s / Trefethen’s method). This gives spectral accuracy, no spurious eigenvalues, and no boundary condition is needed at the center.Requirements: the grid must provide the antipodal map – the azimuthal axis must be periodic over \(2\pi\) with an even number of points (and, for spherical grids, the polar axis must be symmetric about \(\pi/2\)).
Only the outer end \(r = R\) is a boundary (face
"high").- Parameters:
Base class constructor.
- Parameters:
- property diameter_coords: NDArray¶
All
2 * num_pointsChebyshev nodes on the diameter[-R, R], ascending.
- radial_quadrature_weights(power: int = 1) NDArray[source]¶
Weights \(w_k\) with \(\int_0^R r^m h(r)\,dr \approx \sum_k w_k h(r_k)\).
Exact for even polynomials \(h\) (in \(r\)) up to degree \(2n - 2\); h is assumed even, which holds for angular averages of smooth fields on disks and balls.
- Parameters:
power (int) – The exponent \(m\) of the radial weight: 1 for disks and cylinders, 2 for balls.
- class numgrids.axes.ColatitudeAxis(num_points: int, low: float = 0.0, high: float = 3.141592653589793, **kwargs)[source]¶
Polar angle (colatitude) \(\theta \in (0, \pi)\) that passes through the poles.
Use this axis for the polar angle of a
SphericalGridorSphericalSurfaceGridto cover the full sphere including both poles.The points are \(\theta_j = (j + \tfrac12)\pi/n\), so no point lies on a pole. A meridian continues across a pole on the opposite side: the point \((2\pi - \theta, \varphi)\) is the same as \((\theta, \varphi + \pi)\). Derivatives along the axis are therefore computed with Fourier spectral differentiation on the full great circle \(\theta \in [0, 2\pi)\), with the values of the far side supplied by the grid (“double Fourier sphere”). This gives spectral accuracy and no pole singularity. Integration uses Fejér’s first quadrature rule, which is exact for these nodes.
Requirements: the azimuthal axis must be periodic over \(2\pi\) with an even number of points. The axis has no boundary faces.
- Parameters:
Base class constructor.
- Parameters:
- property great_circle_coords: NDArray¶
All
2 * num_pointspoints on the full great circle[0, 2*pi).
- sine_quadrature_weights() NDArray[source]¶
Weights \(w_j\) with \(\int_0^\pi \sin\theta\, f(\theta)\,d\theta \approx \sum_j w_j f(\theta_j)\).
Fejér’s first rule: exact for \(f = \cos(k\theta)\), \(k < n\), i.e. for polynomials in \(\cos\theta\) of degree \(< n\). Averages of smooth fields over circles of latitude are of this form.
- class numgrids.axes.SemiInfiniteAxis(num_points: int, low: float = 0.0, high: float = inf, scale: float = 1.0, **kwargs)[source]¶
Axis on the half line \([a, \infty)\) with spectral accuracy.
The half line is the image of \(\xi \in [-1, 1)\) under the algebraic map
\[x = a + L\,\frac{1 + \xi}{1 - \xi},\]and the grid points are the images of the Chebyshev–Gauss–Radau points \(\xi_j = -\cos\bigl(2\pi j / (2n - 1)\bigr)\), \(j = 0, \ldots, n - 1\). The first point is \(x_0 = a\), so that boundary conditions can be imposed there; there is no point at infinity. Half of the points lie in \([a, a + L]\), the outermost one at about \(a + 1.6\, n^2 L\).
Functions are represented by polynomials in \(\xi\), i.e. by rational functions of \(x\). This is spectrally accurate for smooth functions that decay or tend to a constant as \(x \to \infty\), but not for functions that grow there, and it converges slowly for functions that oscillate many times while they decay. The scale \(L\) should be several times the decay length of the function (5 to 20 times is a good choice for an exponential decay); too small a value costs more accuracy than too large a one.
Only the finite end is a boundary (face
"low"). No condition is imposed at infinity: the solution of a differential equation that is regular there is selected automatically (seeUnboundedAxis).Integration (
quadrature_weights) is exact for all functions \((1 - \xi)^2\, p(\xi)\) with a polynomial \(p\) of degree \(< n\); integrands must decay faster than \(1/x\).- Parameters:
Examples
>>> import numpy as np >>> from numgrids import SemiInfiniteAxis >>> ax = SemiInfiniteAxis(5, 0.0, scale=1.0) >>> ax.coords.round(4) array([ 0. , 0.1325, 0.7041, 3. , 32.1634]) >>> ax.boundary_sides ('low',) >>> ax = SemiInfiniteAxis(40, 0.0, scale=4.0) >>> x = ax.coords >>> bool(abs(ax.quadrature_weights @ (x ** 2 * np.exp(-x)) - 2) < 1e-10) True
Base class constructor.
- Parameters:
- to_internal(x) NDArray[source]¶
Map physical coordinates to the computational variable \(\xi \in [-1, 1]\).
Infinite values are mapped to \(\pm 1\).
- from_internal(xi) NDArray[source]¶
Map the computational variable \(\xi \in [-1, 1]\) to physical coordinates.
- property barycentric_weights: NDArray¶
Barycentric weights of the nodes in \(\xi\) (up to a common factor).
- property dxi_dx: NDArray¶
The metric factor \(d\xi/dx\) at the grid points.
- class numgrids.axes.InfiniteAxis(num_points: int, low: float = -inf, high: float = inf, scale: float = 1.0, center: float = 0.0, **kwargs)[source]¶
Axis on the whole real line \((-\infty, \infty)\) with spectral accuracy.
The real line is the image of \(\xi \in (-1, 1)\) under the algebraic map
\[x = x_c + \frac{L\,\xi}{\sqrt{1 - \xi^2}},\]and the grid points are the images of the Chebyshev–Gauss points \(\xi_j = -\cos\bigl((2j + 1)\pi / (2n)\bigr)\), i.e. \(x_j = x_c - L \cot\bigl((2j + 1)\pi / (2n)\bigr)\). Half of the points lie in \([x_c - L, x_c + L]\), the outermost ones at about \(x_c \pm 0.64\, n L\). There are no points at infinity.
Functions are represented by polynomials in \(\xi = (x - x_c) / \sqrt{L^2 + (x - x_c)^2}\). This is spectrally accurate for smooth functions that decay exponentially or have an expansion in powers of \(1/x^2\) at infinity, but not for functions that keep oscillating or grow there. The scale \(L\) should be about the half-width of the region in which the function differs appreciably from its limits (3 to 5 standard deviations of a Gaussian); values that are much smaller or much larger cost accuracy.
The axis has no boundary faces. No condition is imposed at infinity: the solution of a differential equation that is regular there is selected automatically (see
UnboundedAxis).Integration (
quadrature_weights) uses the Gauss–Chebyshev rule in \(\xi\), which is exact for all functions \((1 - \xi^2)\, p(\xi)\) with a polynomial \(p\) of degree \(< 2n\); integrands must decay like \(1/x^2\) or faster.- Parameters:
num_points (int) – Number of grid points.
low (float) – Must be
-infandinf(kept for a uniform axis signature).high (float) – Must be
-infandinf(kept for a uniform axis signature).scale (float) – The scale length \(L > 0\) of the map.
center (float) – The point \(x_c\) around which the grid points cluster.
Examples
>>> import numpy as np >>> from numgrids import InfiniteAxis >>> ax = InfiniteAxis(5, scale=2.0) >>> ax.coords.round(4) array([-6.1554, -1.4531, 0. , 1.4531, 6.1554]) >>> ax.boundary_sides () >>> ax = InfiniteAxis(40, scale=3.0) >>> bool(abs(ax.quadrature_weights @ np.exp(-ax.coords ** 2) - np.sqrt(np.pi)) < 1e-12) True
Base class constructor.
- Parameters:
- to_internal(x) NDArray[source]¶
Map physical coordinates to the computational variable \(\xi \in [-1, 1]\).
Infinite values are mapped to \(\pm 1\).
- from_internal(xi) NDArray[source]¶
Map the computational variable \(\xi \in [-1, 1]\) to physical coordinates.
- property barycentric_weights: NDArray¶
Barycentric weights of the nodes in \(\xi\) (up to a common factor).
- property dxi_dx: NDArray¶
The metric factor \(d\xi/dx\) at the grid points.
- class numgrids.axes.UnboundedAxis(num_points: int, low: float, high: float, scale: float, **kwargs)[source]¶
Common base class of
SemiInfiniteAxisandInfiniteAxis.The physical coordinate \(x\) is the image of a computational variable \(\xi \in [-1, 1]\) under an algebraic map with a scale length \(L\); infinity corresponds to \(\xi = \pm 1\). The grid points are Chebyshev-type nodes in \(\xi\) that leave out the points at infinity, and functions are represented by polynomials in \(\xi\) (the “rational Chebyshev functions” of \(x\)). Derivatives follow from the chain rule,
\[\frac{d}{dx} = \frac{d\xi}{dx}\,\frac{d}{d\xi},\]with the polynomial differentiation matrix on the nodes. This is spectrally accurate for smooth functions that decay (or tend to a constant) at infinity.
There is no grid point at infinity and no boundary condition can (or has to) be imposed there. Solutions of a differential equation that grow or keep oscillating at infinity are not polynomials in \(\xi\), so the discretization only finds the solution that is regular there, e.g. the decaying solution of \(u'' - u = f\) or the bound states of a Schrödinger operator. Only if the equation has two solutions that are regular at infinity (such as \(1\) and \(1/r\) for the Laplace equation outside a sphere), it is not uniquely solvable without a condition at infinity; reformulate such problems for a decaying unknown.
Reference: Boyd, Chebyshev and Fourier Spectral Methods, 2nd ed., Dover, 2001, ch. 17.
Base class constructor.