Coverage for src / chebpy / api.py: 100%
31 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-03-22 21:33 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-03-22 21:33 +0000
1"""User-facing functions for creating and manipulating Chebfun objects.
3This module provides the main interface for users to create Chebfun objects,
4which are the core data structure in ChebPy for representing functions.
5"""
7from collections.abc import Callable
8from typing import Any
10import numpy as np
12from .bndfun import Bndfun
13from .chebfun import Chebfun
14from .settings import _preferences as prefs
15from .utilities import Domain
18def chebfun(
19 f: Callable[..., Any] | str | float | None = None,
20 domain: np.ndarray | list[float] | None = None,
21 n: int | None = None,
22) -> "Chebfun":
23 """Create a Chebfun object representing a function.
25 A Chebfun object represents a function using Chebyshev polynomials. This constructor
26 can create Chebfun objects from various inputs including callable functions,
27 constants, and special strings.
29 Args:
30 f: The function to represent. Can be:
31 - None: Creates an empty Chebfun
32 - callable: A function handle like lambda x: x**2
33 - str: A single alphabetic character (e.g., 'x') for the identity function
34 - numeric: A constant value
35 domain: The domain on which to define the function. Defaults to the domain
36 specified in preferences.
37 n: Optional number of points to use in the discretization. If None, adaptive
38 construction is used.
40 Returns:
41 Chebfun: A Chebfun object representing the function.
43 Raises:
44 ValueError: If unable to construct a constant function from the input.
46 Examples:
47 >>> # Empty Chebfun
48 >>> f = chebfun()
49 >>>
50 >>> # Function from a lambda
51 >>> import numpy as np
52 >>> f = chebfun(lambda x: np.sin(x), domain=[-np.pi, np.pi])
53 >>>
54 >>> # Identity function
55 >>> x = chebfun('x')
56 >>>
57 >>> # Constant function
58 >>> c = chebfun(3.14)
59 """
60 # Empty via chebfun()
61 if f is None:
62 return Chebfun.initempty()
64 domain = domain if domain is not None else prefs.domain
66 # Callable fct in chebfun(lambda x: f(x), ... )
67 if callable(f):
68 return Chebfun.initfun(f, domain, n)
70 # Identity via chebfun('x', ... )
71 if isinstance(f, str) and len(f) == 1 and f.isalpha():
72 if n:
73 return Chebfun.initfun(lambda x: x, domain, n)
74 else:
75 return Chebfun.initidentity(domain)
77 try:
78 # Constant fct via chebfun(3.14, ... ), chebfun('3.14', ... )
79 return Chebfun.initconst(float(f), domain)
80 except (OverflowError, ValueError) as err:
81 raise ValueError(f) from err
84def pwc(domain: list[float] | None = None, values: list[float] | None = None) -> "Chebfun":
85 """Initialize a piecewise-constant Chebfun.
87 Creates a piecewise-constant function represented as a Chebfun object.
88 The function takes constant values on each interval defined by the domain.
90 Args:
91 domain (list): A list of breakpoints defining the intervals. Must have
92 length equal to len(values) + 1. Default is [-1, 0, 1].
93 values (list): A list of constant values for each interval. Default is [0, 1].
95 Returns:
96 Chebfun: A piecewise-constant Chebfun object.
98 Examples:
99 >>> # Create a step function with value 0 on [-1,0] and 1 on [0,1]
100 >>> f = pwc()
101 >>>
102 >>> # Create a custom piecewise-constant function
103 >>> f = pwc(domain=[-2, -1, 0, 1, 2], values=[-1, 0, 1, 2])
104 """
105 if values is None:
106 values = [0, 1]
107 if domain is None:
108 domain = [-1, 0, 1]
109 funs: list[Any] = []
110 intervals = list(Domain(domain).intervals)
111 for interval, value in zip(intervals, values, strict=False):
112 funs.append(Bndfun.initconst(value, interval))
113 return Chebfun(funs)