archimedes.approximation.FunctionSpace¶
- class archimedes.approximation.FunctionSpace(
- basis: Basis,
- domain: Any,
- reference_quad_rule: Quadrature | None = None,
The linear span of a
Basison a fixed target domain.Combines a
Basis(family + size) with a target domain and a “natural” quadrature rule, and provides the operations that act on the space, e.g. evaluation, (Galerkin) projection, and quadrature nodes/weights.See
Functionfor a specific element of the space (a coefficient vector).FunctionSpaceis astruct()so that the domain parameters can be symbolically traced and solved/optimized over jointly with the coefficients of aFunction. Thebasisand default quadrature rule are static (do not carry symbolic information).- Parameters:
basis (Basis) – Basis family and size. Static.
domain (Basis.Parameters) –
- Target-domain parameters. An instance of
basis.Parameters, for example: UnitInterval.Parameters(a=..., b=...)for a basis on an intervalRealLine.Parameters(loc=..., scale=...)for the entire real line
- Target-domain parameters. An instance of
reference_quad_rule (Quadrature | None, optional) –
The space’s natural quadrature rule, defined on the basis’s reference domain. Used unconditionally wherever the required accuracy is fully determined by
basisand as the default forproject(). Defaults to a rule that is exact by for that basis.Should typically be accessed via the
quad_ruleproperty, which maps from the reference domain (e.g. \([0, 1]\)) onto the actualdomainparameters.
Methods
basis_matrix([deriv, quad_rule])This space's basis evaluated at its quadrature nodes.
bspline(degree, knots, *[, quad_rule])A B-spline function space built from a general, explicit knot vector.
chebyshev(n_basis[, a, b, second_kind, ...])Global Chebyshev polynomial space on
[a, b].clamped_bspline(degree, breakpoints, *[, ...])A B-spline space with a clamped knot vector built from element boundaries.
fourier(n_basis[, a, b, kind, density, ...])Global (periodic) Fourier space on
[a, b]function([coefficients])A
Functionon this space with knowncoefficients.hermite(n_basis[, loc, scale, kind, ...])Global Hermite polynomial space on the real line.
jacobi(alpha, beta, n_basis[, a, b, ...])Global Jacobi polynomial space on
[a, b].laguerre(n_basis[, rate, start, density, ...])Global Laguerre polynomial space on
[start, inf).legendre(n_basis[, a, b, density, quad_rule])Global Legendre polynomial space on
[a, b]; seeLegendreMeasurefor the defining weight and recurrence.monomial(n_basis[, a, b, quad_rule])Global monomial (power series) space on
[a, b].piecewise(kind, degree, breakpoints, *[, ...])A piecewise function space created by tiling a local basis.
project(f[, quad_rule, test_space])Galerkin (or Petrov-Galerkin) projection of
fonto this space.quadrature([quad_rule])Quadrature nodes and weights mapped onto this space's domain.
replace(**updates)Returns a new object replacing the specified fields with new values.
tensor(*spaces[, quad_rule])The tensor-product space of independent univariate
spaces.Attributes
Number of basis functions; forwarded from
basis.The space's quadrature rule mapped onto its
domain.reference_quad_rulebasisdomain- classmethod bspline(
- degree: int,
- knots,
- *,
- quad_rule: Quadrature | None = None,
A B-spline function space built from a general, explicit knot vector.
Constructs a
BSplineBasiswithdomainderived automatically fromknots. For the common case of a clamped knot vector built from physical element boundaries useclamped_bspline()instead.- Parameters:
degree (int) – Polynomial degree of each piece.
knots (array_like) – Nondecreasing knot vector, physical units. See
BSplineBasisfor what makes a knot vector valid.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor. Defaults to a rule that is exact for the basis.
- Return type:
- classmethod chebyshev(
- n_basis: int,
- a: float = -1.0,
- b: float = 1.0,
- second_kind: bool = False,
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global Chebyshev polynomial space on
[a, b].Chebyshev polynomials of the first kind satisfy
\[T_n(x) = \cos(n \cos^{-1} x)\]and are orthogonal on \([-1, 1]\) with respect to the weight \((1 - x^2)^{-1/2}\).
Chebyshev polynomials of the second kind satisfy
\[U_n(x) = \sin((n+1) \cos^{-1} x) / \sin(\cos^{-1} x)\]and are orthogonal with respect to \((1 - x^2)^{1/2}\).
Both are special cases of
JacobiMeasure, with \(\alpha = \beta = -1/2\) and \(\alpha = \beta = 1/2\), respectively.- Parameters:
n_basis (int) – Number of basis functions.
a (float, optional) – Bounds of the target interval. Default
-1,1.b (float, optional) – Bounds of the target interval. Default
-1,1.second_kind (bool, optional) – Construct second-kind Chebyshev polynomials. Default
False.density (bool, optional) – Normalize against the probability density rather than the raw weight; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Return type:
- classmethod clamped_bspline(
- degree: int,
- breakpoints,
- *,
- quad_rule: Quadrature | None = None,
A B-spline space with a clamped knot vector built from element boundaries.
The domain of the function space is determined by the range
[breakpoints[0], breakpoints[-1]].Builds a knot vector with multiplicity
degree + 1at both ends, so the first/last coefficients are the endpoint values. Interior knots are simple, preserving smoothest possible continuity (\(C^{degree - 1}\)).Use
bspline()with an explicit knot vector for more fine-grained control.- Parameters:
degree (int) – Polynomial degree of each piece.
breakpoints (array_like) – Element boundaries on the physical (target) domain, shape
(n_elements + 1,), strictly increasing.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor. Defaults to a rule that is exact for the basis.
- Return type:
- classmethod fourier(
- n_basis: int,
- a: float = -1.0,
- b: float = 1.0,
- kind: Literal['full', 'cosine', 'sine'] = 'full',
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global (periodic) Fourier space on
[a, b]Treated as one periodic domain:
aandbare the same point.- Parameters:
n_basis (int) – Number of basis functions; see
FourierBasis.kind="full"requires an odd value.a (float, optional) – Bounds of the target period. Default
-1,1.b (float, optional) – Bounds of the target period. Default
-1,1.kind ({"full", "cosine", "sine"}, optional) – Which trigonometric family. Default
"full".density (bool, optional) – Normalize against the probability density rather than the raw weight; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Raises:
ValueError – If
kindis not"full","cosine", or"sine", or ifn_basisis invalid for the chosenkind.
- classmethod hermite(
- n_basis: int,
- loc: float = 0.0,
- scale: float = 1.0,
- kind: Literal['phys', 'prob'] = 'prob',
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global Hermite polynomial space on the real line.
kindselects which classical Hermite convention:"prob"(default): the probabilists’ convention, reference weight \(e^{-x^2/2}\) (ProbabilistsHermiteMeasure), the un-normalized standard normal density."phys": the physicists’ convention, reference weight \(e^{-x^2}\) (PhysicistsHermiteMeasure).
Neither weight integrates to 1 on its own for either
kind; for normalized (e.g. probability density models, polynomial chaos expansions), setdensity=True.- Parameters:
n_basis (int) – Number of basis functions.
loc (float, optional) – Location/scale of the Hermite weight function; see
RealLine. Default0,1.scale (float, optional) – Location/scale of the Hermite weight function; see
RealLine. Default0,1.kind ({"phys", "prob"}, optional) – Classical Hermite convention, as above. Default
"prob".density (bool, optional) – Normalize against the probability density rather than the raw weight; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Raises:
ValueError – If
kindis not"phys"or"prob".
- classmethod jacobi(
- alpha: float,
- beta: float,
- n_basis: int,
- a: float = -1.0,
- b: float = 1.0,
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global Jacobi polynomial space on
[a, b].Defined on an interval \([a, b]\) with weight function \((1 - x)^\alpha (1 + x)^\beta\). See
JacobiMeasurefor details and restrictions onalpha/beta.- Parameters:
alpha (float) – Jacobi measure parameters; see
JacobiMeasure.beta (float) – Jacobi measure parameters; see
JacobiMeasure.n_basis (int) – Number of basis functions.
a (float, optional) – Bounds of the target interval. Default
-1,1.b (float, optional) – Bounds of the target interval. Default
-1,1.density (bool, optional) – Normalize against the probability density rather than the raw weight; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Return type:
- classmethod laguerre(
- n_basis: int,
- rate: float = 1.0,
- start: float = 0.0,
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global Laguerre polynomial space on
[start, inf).See
LaguerreMeasurefor details.- Parameters:
n_basis (int) – Number of basis functions.
rate (float, optional) – Rate parameter for the exponential weight function; see
HalfLine. Default1.start (float, optional) – Left endpoint of the exponential weight function; see
HalfLine. Default0.density (bool, optional) – Normalize against the probability density rather than the raw weight; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Return type:
- classmethod legendre(
- n_basis: int,
- a: float = -1.0,
- b: float = 1.0,
- density: bool = False,
- quad_rule: Quadrature | None = None,
Global Legendre polynomial space on
[a, b]; seeLegendreMeasurefor the defining weight and recurrence.- Parameters:
n_basis (int) – Number of basis functions.
a (float, optional) – Bounds of the target interval. Default
-1,1.b (float, optional) – Bounds of the target interval. Default
-1,1.density (bool, optional) – Normalize against the probability density; see
Basis.density. DefaultFalse.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- Return type:
- classmethod monomial(
- n_basis: int,
- a: float = -1.0,
- b: float = 1.0,
- quad_rule: Quadrature | None = None,
Global monomial (power series) space on
[a, b].See
MonomialBasisfor details.- Parameters:
n_basis (int) – Number of basis functions (degrees
0throughn_basis - 1).a (float, optional) – Bounds of the target interval. Default
-1,1.b (float, optional) – Bounds of the target interval. Default
-1,1.quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor.
- classmethod piecewise(
- kind: str,
- degree: int | tuple[int, ...],
- breakpoints,
- *,
- nodes: str | ndarray | Callable[[int], ndarray] | None = None,
- continuity: int = 0,
- quad_rule: Quadrature | None = None,
A piecewise function space created by tiling a local basis.
Constructs a
FunctionSpaceby tiling a local basis acrossbreakpoints. The domain of the function space is determined by the range[breakpoints[0], breakpoints[-1]].This method is a convenience constructor for a
PiecewiseBasisfor some common cases. For more fine-grained control, construct aPiecewiseBasisdirectly and pass it to the generalFunctionSpace(basis, domain)constructor.- Parameters:
kind ({"lagrange", "legendre", "hermite"}) –
Local basis family.
"lagrange"is nodal (point-value degrees of freedom); node placement is chosen bynodes."legendre"is modal (OrthogonalPolynomialBasisonLegendreMeasure), which has no boundary degrees of freedom and so only supportscontinuity=-1."hermite"is piecewise cubic, with value and slope degrees of freedom at each end, requiringdegree=3. This is the only option that supportscontinuity=1(\(C^1\)), though also supportscontinuity=0or-1.
degree (int or tuple of int) – Polynomial degree of each element. An
intis shared by every element; a tuple gives one degree per element and must length match the number of elements. Must be3forkind="hermite".breakpoints (array_like) – Element boundaries on the physical (not reference) domain, shape
(n_elements + 1,), strictly increasing.nodes (str, callable, or array_like, optional) –
Node placement for a
kind="lagrange"element, one of:- One of the family names
"lobatto","legendre", "radau_left","radau_right","equispaced"
- One of the family names
An explicit
n -> nodescallableAn explicit array of reference nodes.
Default (
None) is Gauss-Lobatto, which keepscontinuity=0, since Lobatto includes both endpoints. Meaningless for non-Lagrange bases.continuity (int, optional) –
0(the default) for value-continuity (\(C^0\)),-1for a discontinuous basis.kind="hermite"additionally supportscontinuity=1(\(C^1\)).quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor. Defaults to a rule that is exact for the basis.
- Return type:
- classmethod tensor(
- *spaces: FunctionSpace,
- quad_rule: Quadrature | None = None,
The tensor-product space of independent univariate
spaces.Constructs a
TensorBasisfrom the given univariate spaces.- Parameters:
*spaces (FunctionSpace) – One univariate space per dimension, in order.
quad_rule (QuadratureRule, optional) – Forwarded to the underlying
FunctionSpaceconstructor. Default is the tensor product of the factors’ default rules, aTensorQuadratureRule.
- Raises:
ValueError – If fewer than one space is given, or any space is not univariate (
basis.ndim != 1).
- __init__(
- basis: Basis,
- domain: Any,
- reference_quad_rule: Quadrature | None = None,
- basis_matrix(
- deriv: int = 0,
- quad_rule: Quadrature | None = None,
This space’s basis evaluated at its quadrature nodes.
The basis matrix is a generalized Vandermonde matrix with shape
(n_nodes, n_basis). The returnedBasisMatrixobject also carries its quadrature nodes and weights.- Parameters:
deriv (int or tuple of int, optional) – Derivative order; a multi-index for a
TensorBasis, anintotherwise. Default 0.quad_rule (QuadratureRule, optional) – Quadrature rule to use instead of the default for this space.
- Returns:
The basis matrix together with its quadrature nodes and weights.
- Return type:
See also
quadrature()Get the quadrature nodes and weights for this space
quad_ruleThe default quadrature rule for this space.
project()L2 projection of a function onto this space.
- function(coefficients: np.ndarray | None = None) Function¶
A
Functionon this space with knowncoefficients.Convenience method for
Function(coefficients, self). This is the natural constructor when the coefficients are already known, as opposed toproject(), which computes them from a target function.- Parameters:
coefficients (array_like or None, optional) – Expansion coefficients, shape
(n_basis,)for a scalar-valued function or(n_basis, m)for one mapping to anm-vector. IfNone, the expansion is initialized to zero. DefaultNone.
- project(
- f: Callable,
- quad_rule: Quadrature | None = None,
- test_space: FunctionSpace | None = None,
Galerkin (or Petrov-Galerkin) projection of
fonto this space.See the function approximation guide for mathematical details on the projection operation and how it is implemented numerically.
Solves
M @ c = bfor the coefficientsc, using this (trial) space’s basis matrixPhiandtest_space’s basis matrixPsi(seebasis_matrix()).M = Psi.T @ Phiis the Gram matrix andb = Psi.T @ f(x)is the load vector, both approximated viaquad_rule(default this space’s own quadrature).quad_rulemust be accurate enough for the product offand both bases, which is generally a higher-order requirement than exactness for either basis alone. Pass an explicitquad_ruleto use something other than the space’s natural default.test_spacedefaults to this space, performing a standard Galerkin projection. Passing a different space performs Petrov-Galerkin projection. In either case the residualf - Phi @ cis orthogonal totest_space.test_spacemust have the samen_basisas this space and must denote the same physical domain. The resultingFunctionis an element of this (trial) space, not the test space.fmay be vector-valued. Iff(x)has shape(npts, m), then each component is projected and the result has coefficients of shape(n_basis, m). The mass matrix is shared across components, so this vector-valued projection still only requires one basis evaluation.- Parameters:
f (callable) – Target function, called once as
f(x)on the full node array from the quadrature rule. Must return an array of shape(npts,)(scalar-valued) or(npts, m)(vector-valued).quad_rule (QuadratureRule, optional) – Quadrature rule to use instead of this space’s own default.
test_space (FunctionSpace, optional) – Test space for a Petrov-Galerkin projection. Defaults to this (trial) space, giving standard Galerkin projection.
- Returns:
The projected function, in this (trial) space, with coefficients of shape
(n_basis,)or(n_basis, m)to matchf.- Return type:
Examples
>>> import numpy as np >>> from archimedes.approximation import FunctionSpace >>> space = FunctionSpace.legendre(n_basis=8) >>> f = space.project(lambda x: np.exp(x)) >>> np.round(f(np.array([-0.5, 0.0, 0.5])), 4) array([0.6065, 1. , 1.6487])
- quadrature(
- quad_rule: Quadrature | None = None,
Quadrature nodes and weights mapped onto this space’s domain.
Unlike
quad_rule, the returned weights are normalized if the space hasdensity=True, in which case the returned weights sum to 1. Otherwise, weights sum to the integral of the weight function over the domain.- Parameters:
quad_rule (QuadratureRule, optional) – Quadrature rule to use instead of this space’s own default.
- Returns:
nodes, weights – Nodes and weights on this space’s target domain.
- Return type:
ndarray
See also
basis_matrix()Get the basis matrix evaluated at the quadrature nodes.
project()L2 projection of a function onto this space.
quad_ruleThe default quadrature rule for this space.
- replace(**updates) T¶
Returns a new object replacing the specified fields with new values.
- property n_basis: int¶
Number of basis functions; forwarded from
basis.
- property quad_rule: Quadrature¶
The space’s quadrature rule mapped onto its
domain.This property does not apply density-normalization, regardless of whether the space has
density=True. Callquadrature()to get optionally normalized quadrature weights and points, e.g. when working with probability densities.