Skip to content

API Reference

api

User-facing functions for creating and manipulating Chebfun objects.

This module provides the main interface for users to create Chebfun objects, which are the core data structure in ChebPy for representing functions.

chebfun(f: Callable[..., Any] | str | float | None = None, domain: np.ndarray | list[float] | None = None, n: int | None = None, *, sing: str | None = None, params: Any = None) -> Chebfun

Create a Chebfun object representing a function.

A Chebfun object represents a function using Chebyshev polynomials. This constructor can create Chebfun objects from various inputs including callable functions, constants, and special strings.

Parameters:

Name Type Description Default
f Callable[..., Any] | str | float | None

The function to represent. Can be: - None: Creates an empty Chebfun - callable: A function handle like lambda x: x**2 - str: A single alphabetic character (e.g., 'x') for the identity function - numeric: A constant value

None
domain ndarray | list[float] | None

The domain on which to define the function. Defaults to the domain specified in preferences.

None
n int | None

Optional number of points to use in the discretization. If None, adaptive construction is used.

None
sing str | None

Optional endpoint-singularity hint, one of "left", "right", or "both". When set, the appropriate boundary pieces are built as :class:~chebpy.singfun.Singfun instances using the Adcock-Richardson exponential clustering map; interior pieces remain :class:~chebpy.bndfun.Bndfun. Only supported with n=None.

None
params Any

Slit-strip map parameters (a :class:~chebpy.maps.MapParams carrying L and alpha). Default None uses :class:~chebpy.maps.MapParams defaults.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the function.

Raises:

Type Description
ValueError

If unable to construct a constant function from the input.

Examples:

>>> # Empty Chebfun
>>> f = chebfun()
>>>
>>> # Function from a lambda
>>> import numpy as np
>>> f = chebfun(lambda x: np.sin(x), domain=[-np.pi, np.pi])
>>>
>>> # Identity function
>>> x = chebfun('x')
>>>
>>> # Constant function
>>> c = chebfun(3.14)
>>>
>>> # Function with an endpoint singularity
>>> g = chebfun(np.sqrt, domain=[0.0, 1.0], sing="left")

pwc(domain: list[float] | None = None, values: list[float] | None = None) -> Chebfun

Initialize a piecewise-constant Chebfun.

Creates a piecewise-constant function represented as a Chebfun object. The function takes constant values on each interval defined by the domain.

Parameters:

Name Type Description Default
domain list

A list of breakpoints defining the intervals. Must have length equal to len(values) + 1. Default is [-1, 0, 1].

None
values list

A list of constant values for each interval. Default is [0, 1].

None

Returns:

Name Type Description
Chebfun Chebfun

A piecewise-constant Chebfun object.

Examples:

>>> # Create a step function with value 0 on [-1,0] and 1 on [0,1]
>>> f = pwc()
>>>
>>> # Create a custom piecewise-constant function
>>> f = pwc(domain=[-2, -1, 0, 1, 2], values=[-1, 0, 1, 2])

chebpts(n: int, domain: list[float] | None = None) -> tuple[np.ndarray, np.ndarray]

Return n Chebyshev points and barycentric weights on domain.

This provides the same functionality as MATLAB's chebpts(n, [a, b]). The points are Chebyshev points of the second kind (i.e. the extrema of the Chebyshev polynomial T_{n-1} plus the endpoints).

Parameters:

Name Type Description Default
n int

Number of Chebyshev points.

required
domain list[float] | None

Two-element list [a, b] specifying the interval. Defaults to [-1, 1].

None

Returns:

Type Description
ndarray

A (points, weights) tuple where points is an array of n

ndarray

Chebyshev points on the given domain and weights is the

tuple[ndarray, ndarray]

corresponding array of barycentric interpolation weights.

Examples:

>>> pts, wts = chebpts(4)
>>> pts, wts = chebpts(4, [0, 3])

trigfun(f: Callable[..., Any] | str | float | None = None, domain: np.ndarray | list[float] | None = None, n: int | None = None) -> Chebfun

Create a Chebfun backed by Fourier (trigonometric) technology.

This is the explicit entry point for constructing periodic functions. Unlike chebfun, which always uses Chebyshev polynomial technology, trigfun always uses :class:~chebpy.trigtech.Trigtech as the underlying approximation technology. The user is responsible for ensuring that f is smooth and periodic on domain.

The API mirrors :func:chebfun exactly:

  • trigfun() → empty Chebfun
  • trigfun(lambda x: np.sin(np.pi*x), [-1, 1]) → from callable
  • trigfun('x') → identity (not truly periodic; provided for interface compatibility)
  • trigfun(3.14) → constant function

Parameters:

Name Type Description Default
f Callable[..., Any] | str | float | None

The function to represent. Same semantics as :func:chebfun.

None
domain ndarray | list[float] | None

Domain [a, b]. Defaults to prefs.domain.

None
n int | None

Fixed number of Fourier modes. If None, adaptive construction is used.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object whose pieces are backed by Trigtech.

Examples:

>>> import numpy as np
>>> from chebpy import trigfun
>>> f = trigfun(lambda x: np.cos(np.pi * x), [-1, 1])
>>> float(f(0.0))
1.0
>>> g = trigfun(lambda x: np.sin(2 * np.pi * x))
>>> bool(abs(g.sum()) < 1e-12)
True

Chebfun

Main class for representing and manipulating functions in ChebPy.

The Chebfun class represents functions using piecewise polynomial approximations on arbitrary intervals. It provides a comprehensive set of operations for working with these function representations, including:

  • Function evaluation at arbitrary points
  • Algebraic operations (addition, multiplication, etc.)
  • Calculus operations (differentiation, integration, etc.)
  • Rootfinding
  • Plotting

Chebfun objects can be created from callable functions, constant values, or directly from function pieces. The class supports both adaptive and fixed-length approximations, allowing for efficient representation of functions with varying complexity across different intervals.

Attributes:

Name Type Description
funs ndarray

Array of function pieces that make up the Chebfun.

breakdata OrderedDict

Mapping of breakpoints to function values.

transposed bool

Flag indicating if the Chebfun is transposed.

breakpoints: np.ndarray property

Get the breakpoints of this Chebfun.

Breakpoints are the points where the Chebfun transitions from one piece to another.

Returns:

Type Description
ndarray

numpy.ndarray: Array of breakpoints.

domain: Domain property writable

Get the domain of this Chebfun.

Returns:

Name Type Description
Domain Domain

A Domain object corresponding to this Chebfun.

support: Any property

Get the support interval of this Chebfun.

The support is the interval between the first and last breakpoints.

Returns:

Type Description
Any

numpy.ndarray: Array containing the first and last breakpoints.

hscale: float property

Get the horizontal scale of this Chebfun.

The horizontal scale is the maximum absolute value of the support interval.

Returns:

Name Type Description
float float

The horizontal scale.

iscomplex: bool property

Check if this Chebfun has complex values.

Returns:

Name Type Description
bool bool

True if any of the functions in this Chebfun have complex values, False otherwise.

isconst: bool property

Check if this Chebfun represents a constant function.

A Chebfun is constant if all of its pieces are constant with the same value.

Returns:

Name Type Description
bool bool

True if this Chebfun represents a constant function, False otherwise.

Note

TODO: find an abstract way of referencing funs[0].coeffs[0]

isempty: bool property

Check if this Chebfun is empty.

An empty Chebfun contains no functions.

Returns:

Name Type Description
bool bool

True if this Chebfun is empty, False otherwise.

vscale: Any property

Get the vertical scale of this Chebfun.

The vertical scale is the maximum of the vertical scales of all pieces.

Returns:

Name Type Description
float Any

The vertical scale.

x: Chebfun property

Get the identity function on the support of this Chebfun.

This property returns a new Chebfun representing the identity function f(x) = x defined on the same support as this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun representing the identity function on the support of this Chebfun.

__init__(funs: Any) -> None

Initialize a Chebfun object.

Parameters:

Name Type Description Default
funs list

List of function objects to be included in the Chebfun. These will be checked and sorted using check_funs.

required

initempty() -> Chebfun classmethod

Initialize an empty Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

An empty Chebfun object with no functions.

Examples:

>>> f = Chebfun.initempty()
>>> f.isempty
True

initidentity(domain: Any = None) -> Chebfun classmethod

Initialize a Chebfun representing the identity function f(x) = x.

Parameters:

Name Type Description Default
domain array - like

Domain on which to define the identity function. If None, uses the default domain from preferences.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the identity function on the specified domain.

Examples:

>>> import numpy as np
>>> x = Chebfun.initidentity([-1, 1])
>>> float(x(0.5))
0.5
>>> np.allclose(x([0, 0.5, 1]), [0, 0.5, 1])
True

initconst(c: Any, domain: Any = None) -> Chebfun classmethod

Initialize a Chebfun representing a constant function f(x) = c.

Parameters:

Name Type Description Default
c float or complex

The constant value.

required
domain array - like

Domain on which to define the constant function. If None, uses the default domain from preferences.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the constant function on the specified domain.

Examples:

>>> import numpy as np
>>> f = Chebfun.initconst(3.14, [-1, 1])
>>> float(f(0))
3.14
>>> float(f(0.5))
3.14
>>> np.allclose(f([0, 0.5, 1]), [3.14, 3.14, 3.14])
True

initfun_adaptive(f: Callable[..., Any], domain: Any = None, *, sing: str | None = None, params: Any = None) -> Chebfun classmethod

Initialize a Chebfun by adaptively sampling a function.

This method determines the appropriate number of points needed to represent the function to the specified tolerance using an adaptive algorithm.

Parameters:

Name Type Description Default
f callable

The function to be approximated.

required
domain array - like

Domain on which to define the function. If None, uses the default domain from preferences.

None
sing str | None

Optional endpoint-singularity hint, one of "left", "right", or "both". When set, the appropriate boundary pieces are built as :class:~chebpy.singfun.Singfun instances using the Adcock-Richardson clustering map; interior pieces remain :class:~chebpy.bndfun.Bndfun.

None
params Any

Slit-strip map parameters (a :class:~chebpy.maps.MapParams). Ignored when sing is None. Default None (uses :class:~chebpy.maps.MapParams defaults).

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the function on the specified domain.

Examples:

>>> import numpy as np
>>> f = Chebfun.initfun_adaptive(lambda x: np.sin(x), [-np.pi, np.pi])
>>> bool(abs(f(0)) < 1e-10)
True
>>> bool(abs(f(np.pi/2) - 1) < 1e-10)
True

initfun_fixedlen(f: Callable[..., Any], n: Any, domain: Any = None) -> Chebfun classmethod

Initialize a Chebfun with a fixed number of points.

This method uses a specified number of points to represent the function, rather than determining the number adaptively.

Parameters:

Name Type Description Default
f callable

The function to be approximated.

required
n int or array - like

Number of points to use. If a single value, uses the same number for each interval. If an array, must have one fewer elements than the size of the domain.

required
domain array - like

Domain on which to define the function. If None, uses the default domain from preferences.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the function on the specified domain.

Raises:

Type Description
BadFunLengthArgument

If n is an array and its size doesn't match domain.size - 1.

initfun(f: Callable[..., Any], domain: Any = None, n: Any = None, *, sing: str | None = None, params: Any = None) -> Chebfun classmethod

Initialize a Chebfun from a function.

This is a general-purpose constructor that delegates to either initfun_adaptive or initfun_fixedlen based on whether n is provided.

Parameters:

Name Type Description Default
f callable

The function to be approximated.

required
domain array - like

Domain on which to define the function. If None, uses the default domain from preferences.

None
n int or array - like

Number of points to use. If None, determines the number adaptively. If provided, uses a fixed number of points.

None
sing str | None

Optional endpoint-singularity hint forwarded to :meth:initfun_adaptive. Only valid when n is None.

None
params Any

Slit-strip map parameters (a :class:~chebpy.maps.MapParams). Forwarded to :meth:initfun_adaptive.

None

Returns:

Name Type Description
Chebfun Chebfun

A Chebfun object representing the function on the specified domain.

__add__(f: Any) -> Any

Add a Chebfun with another Chebfun or a scalar.

Parameters:

Name Type Description Default
f Chebfun or scalar

The object to add to this Chebfun.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing the sum.

__call__(x: Any) -> Any

Evaluate the Chebfun at points x.

This method evaluates the Chebfun at the specified points. It handles interior points, breakpoints, and points outside the domain appropriately.

Parameters:

Name Type Description Default
x float or array - like

Points at which to evaluate the Chebfun.

required

Returns:

Type Description
Any

float or numpy.ndarray: The value(s) of the Chebfun at the specified point(s). Returns a scalar if x is a scalar, otherwise an array of the same size as x.

__iter__() -> Iterator[Any]

Return an iterator over the functions in this Chebfun.

Returns:

Name Type Description
iterator Iterator[Any]

An iterator over the functions (funs) in this Chebfun.

__len__() -> int

Return the total number of coefficients across all funs.

Returns:

Name Type Description
int int

The sum of sizes of all constituent funs.

__eq__(other: object) -> bool

Test for equality between two Chebfun objects.

Two Chebfun objects are considered equal if they have the same domain and their function values are equal (within tolerance) at a set of test points.

Parameters:

Name Type Description Default
other object

The object to compare with this Chebfun.

required

Returns:

Name Type Description
bool bool

True if the objects are equal, False otherwise.

__mul__(f: Any) -> Any

Multiply a Chebfun with another Chebfun or a scalar.

Parameters:

Name Type Description Default
f Chebfun or scalar

The object to multiply with this Chebfun.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing the product.

__neg__() -> Chebfun

Return the negative of this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing -f(x).

__pos__() -> Chebfun

Return the positive of this Chebfun (which is the Chebfun itself).

Returns:

Name Type Description
Chebfun Chebfun

This Chebfun object (unchanged).

__abs__() -> Chebfun

Return the absolute value of this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing |f(x)|.

__pow__(f: Any) -> Any

Raise this Chebfun to a power.

Parameters:

Name Type Description Default
f Chebfun or scalar

The exponent to which this Chebfun is raised.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing self^f.

__rtruediv__(c: Any) -> Chebfun

Divide a scalar by this Chebfun.

This method is called when a scalar is divided by a Chebfun, i.e., c / self.

Parameters:

Name Type Description Default
c scalar

The scalar numerator.

required

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing c / self.

Note

This is executed when truediv(f, self) fails, which is to say whenever c is not a Chebfun. We proceed on the assumption f is a scalar.

__repr__() -> str

Return a string representation of the Chebfun.

This method returns a detailed string representation of the Chebfun, including information about its domain, intervals, and endpoint values.

Returns:

Name Type Description
str str

A string representation of the Chebfun.

__rsub__(f: Any) -> Any

Subtract this Chebfun from another object.

This method is called when another object is subtracted by this Chebfun, i.e., f - self.

Parameters:

Name Type Description Default
f Chebfun or scalar

The object from which to subtract this Chebfun.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing f - self.

__rpow__(f: Any) -> Any

Raise another object to the power of this Chebfun.

This method is called when another object is raised to the power of this Chebfun, i.e., f ** self.

Parameters:

Name Type Description Default
f Chebfun or scalar

The base to be raised to the power of this Chebfun.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing f ** self.

__truediv__(f: Any) -> Any

Divide this Chebfun by another object.

Parameters:

Name Type Description Default
f Chebfun or scalar

The divisor.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing self / f.

__str__() -> str

Return a human-readable string representation of the Chebfun.

This method returns the same detailed representation as __repr__, so that print(f) shows the full summary table. This is consistent with the behaviour of numpy and pandas objects.

Returns:

Name Type Description
str str

A detailed string representation of the Chebfun.

__sub__(f: Any) -> Any

Subtract another object from this Chebfun.

Parameters:

Name Type Description Default
f Chebfun or scalar

The object to subtract from this Chebfun.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun representing self - f.

imag() -> Chebfun

Get the imaginary part of this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing the imaginary part of this Chebfun. If this Chebfun is real-valued, returns a zero Chebfun.

real() -> Chebfun

Get the real part of this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing the real part of this Chebfun. If this Chebfun is already real-valued, returns this Chebfun.

copy() -> Chebfun

Create a deep copy of this Chebfun.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun that is a deep copy of this Chebfun.

restrict(subinterval: Any) -> Any

Restrict a Chebfun to a subinterval.

This method creates a new Chebfun that is restricted to the specified subinterval and simplifies the result.

Parameters:

Name Type Description Default
subinterval array - like

The subinterval to which this Chebfun should be restricted.

required

Returns:

Name Type Description
Chebfun Any

A new Chebfun restricted to the specified subinterval.

restrict_(subinterval: Any) -> Chebfun

Restrict a Chebfun to a subinterval, modifying the object in place.

This method modifies the current Chebfun by restricting it to the specified subinterval and simplifying the result.

Parameters:

Name Type Description Default
subinterval array - like

The subinterval to which this Chebfun should be restricted.

required

Returns:

Name Type Description
Chebfun Chebfun

The modified Chebfun (self).

roots(merge: Any = None) -> np.ndarray

Compute the roots of a Chebfun.

This method finds the values x for which f(x) = 0, by computing the roots of each piece of the Chebfun and combining them.

Parameters:

Name Type Description Default
merge bool

Whether to merge roots at breakpoints. If None, uses the value from preferences. Defaults to None.

None

Returns:

Type Description
ndarray

numpy.ndarray: Array of roots sorted in ascending order.

Examples:

>>> import numpy as np
>>> f = Chebfun.initfun_adaptive(lambda x: x**2 - 1, [-2, 2])
>>> roots = f.roots()
>>> len(roots)
2
>>> np.allclose(sorted(roots), [-1, 1])
True

simplify() -> Chebfun

Simplify each fun in the chebfun.

translate(c: Any) -> Chebfun

Translate a chebfun by c, i.e., return f(x-c).

cumsum() -> Chebfun

Compute the indefinite integral (antiderivative) of the Chebfun.

This method computes the indefinite integral of the Chebfun, with the constant of integration chosen so that the indefinite integral evaluates to 0 at the left endpoint of the domain. For piecewise functions, constants are added to ensure continuity across the pieces.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing the indefinite integral of this Chebfun.

Examples:

>>> import numpy as np
>>> f = Chebfun.initconst(1.0, [-1, 1])
>>> F = f.cumsum()
>>> bool(abs(F(-1)) < 1e-10)
True
>>> bool(abs(F(1) - 2.0) < 1e-10)
True

diff(n: int = 1) -> Chebfun

Compute the derivative of the Chebfun.

This method calculates the nth derivative of the Chebfun with respect to x. It creates a new Chebfun where each piece is the derivative of the corresponding piece in the original Chebfun.

Parameters:

Name Type Description Default
n int

Order of differentiation (default: 1). Must be non-negative integer.

1

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing the nth derivative of this Chebfun.

Examples:

>>> from chebpy import chebfun
>>> f = chebfun(lambda x: x**3)
>>> df1 = f.diff()    # first derivative: 3*x**2
>>> df2 = f.diff(2)   # second derivative: 6*x
>>> df3 = f.diff(3)   # third derivative: 6
>>> bool(abs(df1(0.5) - 0.75) < 1e-10)
True
>>> bool(abs(df2(0.5) - 3.0) < 1e-10)
True
>>> bool(abs(df3(0.5) - 6.0) < 1e-10)
True

conv(g: Chebfun) -> Chebfun

Compute the convolution of this Chebfun with g.

Computes h(x) = (f ★ g)(x) = ∫ f(t) g(x-t) dt, where domain(f) is [a, b] and domain(g) is [c, d]. The result is a piecewise Chebfun on [a + c, b + d] whose breakpoints are the pairwise sums of the breakpoints of f and g.

Both f and g may be piecewise (contain an arbitrary number of funs).

When both inputs are single-piece with equal-width domains, the fast Hale-Townsend Legendre convolution algorithm is used. Otherwise, each output sub-interval is constructed adaptively using Gauss-Legendre quadrature.

The algorithm is based on

N. Hale and A. Townsend, "An algorithm for the convolution of Legendre series", SIAM J. Sci. Comput., 36(3), A1207-A1220, 2014.

Parameters:

Name Type Description Default
g Chebfun

A Chebfun (single-piece or piecewise).

required

Returns:

Name Type Description
Chebfun Chebfun

A piecewise Chebfun on [a + c, b + d] representing (f ★ g).

Examples:

>>> import numpy as np
>>> from chebpy import chebfun
>>> f = chebfun(lambda x: np.ones_like(x), [-1, 1])
>>> h = f.conv(f)
>>> bool(abs(h(0.0) - 2.0) < 1e-10)
True
>>> bool(abs(h(-1.0) - 1.0) < 1e-10)
True
>>> bool(abs(h(1.0) - 1.0) < 1e-10)
True

sum() -> Any

Compute the definite integral of the Chebfun over its domain.

This method calculates the definite integral of the Chebfun over its entire domain of definition by summing the definite integrals of each piece.

Returns:

Type Description
Any

float or complex: The definite integral of the Chebfun over its domain.

Examples:

>>> import numpy as np
>>> f = Chebfun.initfun_adaptive(lambda x: x**2, [-1, 1])
>>> bool(abs(f.sum() - 2.0/3.0) < 1e-10)
True
>>> g = Chebfun.initconst(1.0, [-1, 1])
>>> bool(abs(g.sum() - 2.0) < 1e-10)
True

dot(f: Any) -> Any

Compute the dot product of this Chebfun with another function.

This method calculates the inner product (dot product) of this Chebfun with another function f by multiplying them pointwise and then integrating the result over the domain.

Parameters:

Name Type Description Default
f Chebfun or scalar

The function or scalar to compute the dot product with. If not a Chebfun, it will be converted to one.

required

Returns:

Type Description
Any

float or complex: The dot product of this Chebfun with f.

norm(p: Any = 2) -> Any

Compute the Lp norm of the Chebfun over its domain.

This method calculates the Lp norm of the Chebfun. The L2 norm is the default and is computed as sqrt(integral(|f|^2)). For p=inf, returns the maximum absolute value by checking critical points (extrema).

Parameters:

Name Type Description Default
p int or float

The norm type. Supported values are 1, 2, positive integers/floats, or np.inf. Defaults to 2 (L2 norm).

2

Returns:

Name Type Description
float Any

The Lp norm of the Chebfun.

Examples:

>>> from chebpy import chebfun
>>> import numpy as np
>>> f = chebfun(lambda x: x**2, [-1, 1])
>>> np.allclose(f.norm(), 0.6324555320336759)  # L2 norm
True
>>> np.allclose(f.norm(np.inf), 1.0)  # Maximum absolute value
True

absolute() -> Chebfun

Absolute value of a Chebfun.

sign() -> Chebfun

Sign function of a Chebfun.

Computes the piecewise sign of a Chebfun by finding its roots and splitting the domain at those points, then creating constant pieces with the appropriate sign values.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing sign(f(x)).

ceil() -> Chebfun

Ceiling function of a Chebfun.

Computes the piecewise ceiling of a Chebfun by finding where the function crosses integer values and splitting the domain at those points, then creating constant pieces with the appropriate ceiling values.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing ceil(f(x)).

floor() -> Chebfun

Floor function of a Chebfun.

Computes the piecewise floor of a Chebfun by finding where the function crosses integer values and splitting the domain at those points, then creating constant pieces with the appropriate floor values.

Returns:

Name Type Description
Chebfun Chebfun

A new Chebfun representing floor(f(x)).

maximum(other: Any) -> Any

Pointwise maximum of self and another chebfun.

minimum(other: Any) -> Any

Pointwise mimimum of self and another chebfun.

plot(ax: Axes | None = None, **kwds: Any) -> Any

Plot the Chebfun over its domain.

This method plots the Chebfun over its domain using matplotlib. For complex-valued Chebfuns, it plots the real part against the imaginary part.

For Chebfuns with ±inf endpoints (containing :class:CompactFun pieces), each unbounded endpoint is replaced for plotting purposes with the corresponding plot_support endpoint of the outermost :class:CompactFun piece, so the decay-to-zero region is visible.

Parameters:

Name Type Description Default
ax Axes

The axes on which to plot. If None, a new axes will be created. Defaults to None.

None
**kwds Any

Additional keyword arguments to pass to matplotlib's plot function.

{}

Returns:

Type Description
Any

matplotlib.axes.Axes: The axes on which the plot was created.

plotcoeffs(ax: Axes | None = None, **kwds: Any) -> Axes

Plot the coefficients of the Chebfun on a semilogy scale.

This method plots the absolute values of the coefficients for each piece of the Chebfun on a semilogy scale, which is useful for visualizing the decay of coefficients in the Chebyshev series.

Parameters:

Name Type Description Default
ax Axes

The axes on which to plot. If None, a new axes will be created. Defaults to None.

None
**kwds Any

Additional keyword arguments to pass to matplotlib's semilogy function.

{}

Returns:

Type Description
Axes

matplotlib.axes.Axes: The axes on which the plot was created.

CompactFun

Bases: Classicfun

Functions on (semi-)infinite intervals with finite numerical support.

A :class:CompactFun represents a function whose user-facing logical interval has one or both endpoints at ±inf but whose numerical support — the set where the function differs from its asymptotic limit by more than a configured tolerance — is finite. Internally it inherits from :class:Classicfun and stores a standard :class:Onefun on the discovered finite storage interval; outside that interval the function is reported as the corresponding asymptotic constant tail_left or tail_right (default 0.0).

Two intervals are tracked:

  • self._interval (inherited): the finite storage interval where the underlying Onefun lives.
  • self._logical_interval: the user-facing interval, which may have ±inf endpoints; returned by :attr:support.

Two scalar tail constants are tracked:

  • tail_left: the value reported for x < a_storage when the logical-left endpoint is -inf.
  • tail_right: the value reported for x > b_storage when the logical-right endpoint is +inf.

For finite logical intervals the storage and logical intervals coincide and the tails are ignored, so a :class:CompactFun behaves identically to :class:~chebpy.bndfun.Bndfun.

Attributes:

Name Type Description
onefun

Inherited; the standard :class:Onefun on [-1, 1].

support Any

The logical interval (possibly with ±inf endpoints).

numerical_support Any

The finite storage interval.

tail_left float

Asymptotic value at -inf (0.0 if logical-left is finite).

tail_right float

Asymptotic value at +inf (0.0 if logical-right is finite).

support: Any property

Return the logical (user-facing) interval, possibly with ±inf endpoints.

numerical_support: Any property

Return the finite storage interval [a, b] discovered at construction.

tail_left: float property

Asymptotic value of the function as x → -inf.

Always 0.0 when the logical-left endpoint is finite.

tail_right: float property

Asymptotic value of the function as x → +inf.

Always 0.0 when the logical-right endpoint is finite.

endvalues: Any property

Return values at the logical endpoints; tails at any ±inf endpoint.

plot_support: tuple[float, float] property

Return a finite [a, b] plotting window.

Replaces any ±inf logical endpoint with the corresponding numerical-support endpoint padded by 10% of the storage width (minimum padding of 1.0) so the decay-to-zero region is visible.

__init__(onefun: Any, interval: Any, logical_interval: Any = None, tail_left: float = 0.0, tail_right: float = 0.0) -> None

Create a new :class:CompactFun instance.

Parameters:

Name Type Description Default
onefun Any

The :class:Onefun representing the function on [-1, 1].

required
interval Any

The finite storage :class:Interval (always finite).

required
logical_interval Any

The user-facing interval (possibly with ±inf endpoints). Defaults to interval if omitted.

None
tail_left float

Asymptotic value at -inf. Default 0.0.

0.0
tail_right float

Asymptotic value at +inf. Default 0.0.

0.0

initempty() -> CompactFun classmethod

Initialise an empty CompactFun on (-inf, +inf).

initconst(c: Any, interval: Any) -> CompactFun classmethod

Initialise a constant function.

On an unbounded interval the constant c becomes the asymptotic value on each unbounded side: tail_left = tail_right = c. This makes initconst total — every constant is representable on every interval — but note that integrating a non-zero constant over an unbounded logical interval will (correctly) raise :class:~chebpy.exceptions.DivergentIntegralError.

initidentity(interval: Any) -> CompactFun classmethod

Initialise the identity function f(x) = x.

The identity function is unbounded and so cannot be represented as a :class:CompactFun on an unbounded interval. This method is provided only for completeness and refuses any infinite endpoint.

initfun_adaptive(f: Any, interval: Any) -> CompactFun classmethod

Initialise from a callable using adaptive sampling.

Discovers the numerical support and asymptotic tail constants of f on the (possibly unbounded) logical interval, then builds a standard adaptive :class:Onefun on that finite storage interval.

Raises:

Type Description
CompactFunConstructionError

If the numerical support cannot be discovered within the configured tolerance and width budget, or if f does not converge to a constant at ±inf.

initfun_fixedlen(f: Any, interval: Any, n: int) -> CompactFun classmethod

Initialise from a callable using a fixed number of points.

Discovers numerical support and tails as in :meth:initfun_adaptive, then builds a fixed-length :class:Onefun on the storage interval.

__call__(x: Any, how: str = 'clenshaw') -> Any

Evaluate the function at x.

Outside the storage interval, returns the corresponding tail constant when the matching logical endpoint is ±inf (default 0.0), or 0.0 when the logical endpoint is finite.

__repr__() -> str

Return a string representation showing the logical interval, size, and tails.

sum() -> Any

Compute the definite integral over the logical interval.

Raises:

Type Description
DivergentIntegralError

If the logical interval is unbounded on a side where the corresponding tail is non-zero (the integral of a non-decaying function over a half-line diverges).

cumsum() -> CompactFun

Compute the indefinite integral.

For a :class:CompactFun with zero asymptote on the unbounded left/right side, the antiderivative is well-defined; it is itself a :class:CompactFun whose right-tail equals ∫f and whose left-tail is 0 (anchored so F(-inf) = 0).

Raises:

Type Description
DivergentIntegralError

If the logical interval is unbounded on a side where the corresponding tail is non-zero, in which case the antiderivative diverges.

diff() -> CompactFun

Compute the derivative.

The derivative of a function with constant asymptotic limits has zero asymptotes, so the result has tail_left = tail_right = 0.

roots() -> Any

Find the roots, filtering out spurious roots in numerical-noise regions.

The underlying polynomial approximation can produce many spurious roots in regions where the function has decayed to numerical noise (typically near the boundary of the storage interval). We keep a candidate root r only if both:

  • f(r - δ) and f(r + δ) have opposite signs (the function actually crosses zero), and
  • max(|f(r - δ)|, |f(r + δ)|) exceeds numsupp_tol * vscale (the values are above numerical noise).

Here delta = 1e-3 * storage_width. This heuristic does not preserve double roots; that is a documented limitation since double roots are uncommon in the decay-to-zero functions that :class:CompactFun is designed for.

restrict(subinterval: Any) -> Any

Restrict to a finite subinterval, returning a :class:Bndfun.

translate(c: float) -> CompactFun

Translate by c along the real line, preserving both intervals and tails.

__neg__() -> CompactFun

Return -f; negates both tail constants.

__add__(other: Any) -> Any

Pointwise addition; combines tail constants additively.

__radd__(other: Any) -> Any

Right-hand addition for scalar + CompactFun.

__sub__(other: Any) -> Any

Pointwise subtraction; combines tail constants additively.

__rsub__(other: Any) -> Any

Right-hand subtraction for scalar - CompactFun.

__mul__(other: Any) -> Any

Pointwise multiplication; combines tail constants multiplicatively.

__rmul__(other: Any) -> Any

Right-hand multiplication for scalar * CompactFun.

plot(ax: Any = None, **kwds: Any) -> Any

Plot the function over a finite window derived from its numerical support.

For doubly- or singly-infinite logical intervals, the plotting window defaults to the numerical-support interval padded by 10% on each unbounded side. Pass an explicit support=(a, b) keyword to override.

Trigtech

Bases: Smoothfun, ABC

Trigonometric (Fourier) function approximation on [-1, 1].

Represents a smooth periodic function f: [-1, 1] -> R (or C) as a truncated Fourier series. Coefficients are stored in NumPy FFT order; see module docstring for the precise convention.

This class is ABC so that it cannot be instantiated directly—exactly mirroring Chebtech, which is also abstract (concrete only through the Chebtech name used everywhere). In practice Trigtech is both the abstract base and the concrete class: it is not further subclassed, but the ABC marker prevents accidental bare construction without going through a named constructor.

coeffs: np.ndarray property

Fourier coefficients in NumPy FFT order (always complex128).

interval: Interval property

Interval that the Trigtech is mapped to.

size: int property

Number of stored Fourier coefficients.

isempty: bool property

True if the Trigtech has no coefficients.

iscomplex: bool property

True if the function is complex-valued (values have a non-negligible imaginary part).

This is determined by checking whether the Fourier coefficients violate the conjugate-symmetry condition C_{n-k} ≈ conj(C_k) that holds for every real-valued periodic function.

isconst: bool property

True if the Trigtech represents a constant (single coefficient).

isperiodic: bool property

Always True: Trigtech always represents a periodic function.

vscale: float property

Estimate the vertical scale (max |f|).

initconst(c: Any = None, *, interval: Any = None) -> Trigtech classmethod

Initialise a Trigtech from a constant c.

initempty(*, interval: Any = None) -> Trigtech classmethod

Initialise an empty Trigtech.

initidentity(*, interval: Any = None) -> Trigtech classmethod

Trigtech approximation of the identity f(x) = x on [-1, 1].

Note: f(x) = x is not periodic on [-1, 1], so this will not converge to machine precision. It is provided for interface compatibility with Chebtech; in practice Classicfun.initidentity is used instead.

initfun(fun: Any = None, n: Any = None, *, interval: Any = None) -> Trigtech classmethod

Convenience constructor: adaptive if n is None, fixed-length otherwise.

initfun_fixedlen(fun: Any = None, n: Any = None, *, interval: Any = None) -> Trigtech classmethod

Initialise a Trigtech from callable fun using n equispaced points.

initfun_adaptive(fun: Any = None, *, interval: Any = None) -> Trigtech classmethod

Initialise a Trigtech from callable fun using the adaptive constructor.

initvalues(values: Any = None, *, interval: Any = None) -> Trigtech classmethod

Initialise a Trigtech from function values at equispaced points.

__init__(coeffs: Any, interval: Any = None) -> None

Initialise a Trigtech with FFT-order coeffs on interval.

Coefficients are always stored as complex128. The :attr:iscomplex property returns True only when the function values are complex (i.e., the coefficients do not satisfy the conjugate-symmetry condition C_{n-k} ≈ conj(C_k)).

Parameters:

Name Type Description Default
coeffs Any

1-D array of Fourier coefficients in NumPy FFT order.

required
interval Any

Two-element interval [a, b]. Defaults to prefs.domain.

None

__call__(x: Any, how: str = 'fft') -> Any

Evaluate the Trigtech at points x via the DFT summation formula.

f(x) = Σ_k coeffs[k] * exp(iπω_k*(x+1))

where ω_k = fftfreq(n)*n gives integer frequencies in FFT order. For real-valued functions the imaginary part of the result is discarded.

Parameters:

Name Type Description Default
x Any

Evaluation points in [-1, 1].

required
how str

Ignored; present for interface compatibility with Chebtech.

'fft'

__repr__() -> str

Return a concise string representation.

copy() -> Trigtech

Return a deep copy.

imag() -> Trigtech

Return the imaginary part of the function as a real-valued Trigtech.

For a complex function f(x) = g(x) + i·h(x), the Fourier coefficients of h(x) are H[k] = (D[k] - conj(D[n-k])) / (2i) for k ≥ 1, and H[0] = Im(D[0]).

prolong(n: int) -> Trigtech

Return a Trigtech of length n (truncate or zero-pad in frequency space).

The operation aligns DC components of the source and target DC-centred representations, then either pads with zeros (n > m) or slices (n < m). This correctly handles the asymmetry between even- and odd-length arrays.

real() -> Trigtech

Return the real part of the function as a real-valued Trigtech.

For a complex function f(x) = g(x) + i·h(x), the Fourier coefficients of g(x) are G[k] = (D[k] + conj(D[n-k])) / 2 for k ≥ 1, and G[0] = Re(D[0]).

simplify() -> Trigtech

Truncate high-frequency Fourier coefficients that are below tolerance.

Uses the same one-sided symmetric-maximum criterion as the adaptive constructor: the highest-frequency mode retained is the one where max(|c_k|, |c_{-k}|) / vscale > tol.

values() -> np.ndarray

Function values at the n equispaced points x_j = -1 + 2j/n.

__add__(f: Any) -> Trigtech

Add a scalar or another Trigtech.

__div__(f: Any) -> Trigtech

Divide this Trigtech by a scalar or another Trigtech.

__mul__(g: Any) -> Trigtech

Multiply this Trigtech by a scalar or another Trigtech.

Trig-polynomial multiplication is circular convolution in frequency space. We implement this cleanly by evaluating both on a grid of size n1 + n2 (sufficient to avoid aliasing), multiplying pointwise, and taking the FFT.

__neg__() -> Trigtech

Return the negation.

__pos__() -> Trigtech

Return self (unary plus).

__pow__(f: Any) -> Trigtech

Raise this Trigtech to a power f (scalar or Trigtech).

__rdiv__(f: Any) -> Trigtech

Compute f / self where f is a scalar.

__rsub__(f: Any) -> Trigtech

Compute f - self.

__rpow__(f: Any) -> Trigtech

Compute f ** self.

__sub__(f: Any) -> Trigtech

Subtract f (scalar or Trigtech) from this Trigtech.

roots(sort: bool | None = None) -> np.ndarray

Find the roots of this Trigtech on [-1, 1].

Converts to a Chebyshev representation via re-sampling on Chebyshev points and delegates to the Chebtech colleague-matrix root-finder.

Parameters:

Name Type Description Default
sort bool | None

If True, sort the roots in ascending order. Defaults to prefs.sortroots.

None

sum() -> Any

Definite integral of the Trigtech over [-1, 1].

Only the DC coefficient contributes

{-1}^{1} exp(iπk*(x+1)) dx = 0 for k ≠ 0 ∫{-1}^{1} 1 dx = 2 for k = 0

cumsum() -> Trigtech

Indefinite integral, zero at x = -1, in Fourier coefficient space.

For mode k ≠ 0: antiderivative coefficient = c_k / (iπω_k) For mode k = 0: set to the constant needed so that F(-1) = 0.

Note: if the DC component (self.coeffs[0]) is non-zero the true antiderivative contains a linear trend and is not periodic. We still return a Trigtech representing the periodic part, adjusted so that the result evaluates to 0 at x = -1.

diff() -> Trigtech

Derivative via the Fourier multiplier iπω_k.

d/dx [c_k * exp(iπω_k(x+1))] = iπω_k * c_k * exp(iπω_k(x+1))

plot(ax: Any = None, **kwargs: Any) -> Any

Plot the Trigtech over [-1, 1].

Parameters:

Name Type Description Default
ax Any

Matplotlib axes. If None, uses the current axes.

None
**kwargs Any

Forwarded to matplotlib.

{}

Returns:

Type Description
Any

The axes on which the plot was drawn.

plotcoeffs(ax: Any = None, **kwargs: Any) -> Any

Plot the absolute Fourier coefficient magnitudes in DC-centred order.

Uses _coeffs_to_plotorder() so the horizontal axis runs from the most-negative frequency on the left to the most-positive on the right, with DC in the centre.

Parameters:

Name Type Description Default
ax Any

Matplotlib axes. If None, uses the current axes.

None
**kwargs Any

Forwarded to matplotlib.

{}

Returns:

Type Description
Any

The axes on which the plot was drawn.

Quasimatrix

An inf x n column quasimatrix whose columns are Chebfun objects.

A quasimatrix generalises the idea of a matrix so that one of its dimensions is continuous. Here the rows are indexed by points in an interval and the columns are Chebfun objects.

Attributes:

Name Type Description
columns list[Chebfun]

list of Chebfun objects forming the columns.

shape: tuple[float, int] property

Return (∞, n) where n is the number of columns.

T: _TransposedQuasimatrix property

Return the transpose (an n x inf row quasimatrix).

domain: Any property

Domain of the quasimatrix columns.

support: tuple[float, float] property

Support interval of the quasimatrix.

isempty: bool property

Return True if the quasimatrix has no columns.

__init__(columns: list[Any]) -> None

Initialise from a list of Chebfun objects, callables, or scalars.

__getitem__(key: Any) -> Any

Column indexing: A[:, k] returns column k as a Chebfun.

__len__() -> int

Return the number of columns.

__iter__()

Iterate over the columns.

__call__(x: Any) -> np.ndarray

Evaluate every column at x and return the results as an array.

If x is a scalar the result has shape (n,). If x is an array of length m the result has shape (m, n).

__matmul__(other: Any) -> Any

Matrix-vector product: A @ c returns a Chebfun.

other must be a 1-D array-like of length n.

__mul__(other: Any) -> Quasimatrix

Element-wise scalar multiplication.

__rmul__(other: Any) -> Quasimatrix

Right scalar multiplication.

sum() -> np.ndarray

Definite integral of each column (column sums).

inner(other: Quasimatrix | None = None) -> np.ndarray

Gram matrix self.T @ other (or self.T @ self).

qr() -> tuple[Quasimatrix, np.ndarray]

Compute the reduced QR factorization A = Q R.

Uses modified Gram-Schmidt orthogonalisation in function space.

Returns:

Name Type Description
Q Quasimatrix

Quasimatrix with orthonormal columns.

R ndarray

Upper-triangular n x n NumPy array.

svd() -> tuple[Quasimatrix, np.ndarray, np.ndarray]

Compute the reduced SVD A = U S V^T.

Returns:

Name Type Description
U Quasimatrix

inf x n quasimatrix with orthonormal columns.

S ndarray

1-D array of singular values (length n).

V ndarray

n x n orthogonal NumPy matrix.

solve(f: Chebfun) -> np.ndarray

Least-squares solution c to A c ~ f.

Equivalent to MATLAB A\f. Computed via QR factorisation.

norm(p: Any = 'fro') -> float

Compute the norm of the quasimatrix.

Parameters:

Name Type Description Default
p Any

Norm type. - 2: the 2-norm (largest singular value). - 1: max column 1-norm. - np.inf: max row-sum := max_x sum_j |A_j(x)|. - 'fro': Frobenius norm (default).

'fro'

cond() -> float

2-norm condition number (ratio of largest to smallest singular value).

rank(tol: float | None = None) -> int

Numerical rank (number of significant singular values).

null(tol: float | None = None) -> np.ndarray

Orthonormal basis for the null space of the quasimatrix.

Returns an n x k NumPy array whose columns span null(A).

orth(tol: float | None = None) -> Quasimatrix

Orthonormal basis for the column space (range) of the quasimatrix.

pinv() -> _TransposedQuasimatrix

Moore-Penrose pseudoinverse (returned as an n x inf row quasimatrix).

pinv(A) @ f gives the same result as A.solve(f).

plot(ax: Axes | None = None, **kwds: Any) -> Axes

Plot all columns on the same axes.

spy(ax: Axes | None = None, **kwds: Any) -> Axes

Visualise the shape of the quasimatrix.

Draws a rectangle representing the inf x n structure, with a dot for each column to indicate nonzero content.

__repr__() -> str

Return a string representation.

__str__() -> str

Return a string representation.

polyfit(f: Chebfun, n: int) -> Chebfun

Least-squares polynomial fit of degree n to a Chebfun f.

Returns a Chebfun representing the best degree-n polynomial approximation to f in the L²-norm.

gpr(x: ArrayLike, y: ArrayLike, *, domain: tuple[float, float] | list[float] | np.ndarray | None = None, sigma: float | None = None, length_scale: float | None = None, noise: float = 0.0, trig: bool = False, n_samples: int = 0) -> tuple[Chebfun, Chebfun] | tuple[Chebfun, Chebfun, Quasimatrix]

Gaussian process regression returning Chebfun objects.

Given observations (x, y) of a latent function, compute the posterior mean and variance of a Gaussian process with zero prior mean and a squared exponential kernel::

k(x, x') = sigma**2 * exp(-0.5 / L**2 * (x - x')**2)

When trig=True a periodic variant is used instead::

k(x, x') = sigma**2 * exp(-2 / L**2 * sin(pi * (x - x') / P)**2)

where P is the period (length of the domain).

Parameters:

Name Type Description Default
x ArrayLike

Observation locations (1-D array-like).

required
y ArrayLike

Observation values (same length as x).

required
domain tuple[float, float] | list[float] | ndarray | None

Domain [a, b] for the output Chebfuns. Defaults to [min(x), max(x)] (or slightly extended for trig).

None
sigma float | None

Signal variance of the kernel. Defaults to max(|y|).

None
length_scale float | None

Length-scale L of the kernel. If None, it is chosen to maximise the log marginal likelihood.

None
noise float

Standard deviation of i.i.d. Gaussian observation noise. The kernel diagonal is augmented by noise**2.

0.0
trig bool

If True, use a periodic squared-exponential kernel.

False
n_samples int

Number of independent posterior samples to draw. When positive, a :class:Quasimatrix with n_samples columns is returned as the third element of the output tuple.

0

Returns:

Type Description
tuple[Chebfun, Chebfun] | tuple[Chebfun, Chebfun, Quasimatrix]

(f_mean, f_var) — posterior mean and variance as Chebfun objects.

tuple[Chebfun, Chebfun] | tuple[Chebfun, Chebfun, Quasimatrix]

If n_samples > 0, returns (f_mean, f_var, samples) where

tuple[Chebfun, Chebfun] | tuple[Chebfun, Chebfun, Quasimatrix]

samples is a Quasimatrix whose columns are independent draws from

tuple[Chebfun, Chebfun] | tuple[Chebfun, Chebfun, Quasimatrix]

the posterior.

Raises:

Type Description
ValueError

If x and y have different lengths or are empty.

Examples:

>>> import numpy as np
>>> from chebpy.gpr import gpr
>>> rng = np.random.default_rng(1)
>>> x = -2 + 4 * rng.random(10)
>>> y = np.sin(np.exp(x))
>>> f_mean, f_var = gpr(x, y, domain=[-2, 2])
Reference

C. E. Rasmussen & C. K. I. Williams, "Gaussian Processes for Machine Learning", MIT Press, 2006.

ChebPreferences

Bases: DefaultPreferences

Preferences object used in chebpy.

reset(*names: str) -> None

Reset default preferences.

.reset() resets all preferences to the DefaultPrefs state .reset(*names) resets only the selected ones. This leaves additional user-added prefs untouched.

__new__() -> ChebPreferences

Create or return the singleton instance of ChebPreferences.

This method implements the singleton pattern, ensuring that only one instance of ChebPreferences exists. If an instance already exists, it returns that instance; otherwise, it creates a new one.

Parameters:

Name Type Description Default
cls type

The class being instantiated (ChebPreferences).

required

Returns:

Name Type Description
ChebPreferences ChebPreferences

The singleton instance of ChebPreferences.

__enter__() -> ChebPreferences

Save current preferences when entering a context.

This method is called when entering a context manager block. It saves the current preferences to a stack so they can be restored when exiting the context.

Parameters:

Name Type Description Default
self ChebPreferences

The preferences object.

required

Returns:

Name Type Description
ChebPreferences ChebPreferences

The preferences object (self._instance).

__exit__(exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None

Restore previous preferences when exiting a context.

This method is called when exiting a context manager block. It restores the preferences to their previous values by popping the stashed values from the stack and setting them back on the object.

Parameters:

Name Type Description Default
self ChebPreferences

The preferences object.

required
exc_type type[BaseException] | None

The exception type, if an exception was raised in the context.

required
exc_value BaseException | None

The exception value, if an exception was raised in the context.

required
traceback TracebackType | None

The traceback, if an exception was raised in the context.

required