Coverage for src/chebpy/_pointwise.py: 100%

109 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 13:35 +0000

1"""Pointwise and step-function operations on :class:`~chebpy.chebfun.Chebfun`. 

2 

3Kept separate from :mod:`chebpy.chebfun` so the root-splitting machinery behind 

4``abs``, ``sign``, ``ceil``, ``floor`` and pointwise ``maximum``/``minimum`` 

5does not bloat the main class. Each public Chebfun method is a thin wrapper 

6around the corresponding function here. 

7 

8Every function assumes non-empty operands; the wrapping Chebfun methods handle 

9the empty case (via ``@self_empty()``) before delegating. 

10""" 

11 

12from __future__ import annotations 

13 

14from collections.abc import Callable 

15from itertools import pairwise 

16from typing import TYPE_CHECKING, Any 

17 

18import numpy as np 

19 

20from .bndfun import Bndfun 

21from .exceptions import SupportMismatch 

22from .settings import _preferences as prefs 

23 

24if TYPE_CHECKING: 

25 from .chebfun import Chebfun 

26 

27 

28def absolute(f: Chebfun) -> Chebfun: 

29 """Return ``|f|`` by splitting the domain at the roots of ``f``.""" 

30 newdom = f.domain.merge(f.roots()) 

31 funs = [x.absolute() for x in f._break(newdom)] 

32 return f.__class__(funs) 

33 

34 

35def sign(f: Chebfun) -> Chebfun: 

36 """Return the piecewise sign of ``f``. 

37 

38 Splits the domain at the roots of ``f`` and builds a constant piece with 

39 the appropriate sign on each sub-interval; breakpoints at roots are set to 

40 ``0``. 

41 """ 

42 roots = f.roots() 

43 newdom = f.domain.merge(roots) 

44 funs = [] 

45 for fun in f._break(newdom): 

46 mid = fun.support[0] + 0.5 * (fun.support[-1] - fun.support[0]) 

47 s = float(np.sign(float(f(mid)))) 

48 funs.append(Bndfun.initconst(s, fun.interval)) 

49 result = f.__class__(funs) 

50 # Set breakdata: at roots sign is 0, elsewhere use sign of function. 

51 htol = max(1e2 * f.hscale * prefs.eps, prefs.eps) 

52 for bp in result.breakpoints: 

53 if roots.size > 0 and np.any(np.abs(bp - roots) <= htol): 

54 result.breakdata[bp] = 0.0 

55 else: 

56 result.breakdata[bp] = float(np.sign(float(f(bp)))) 

57 return result 

58 

59 

60def ceil(f: Chebfun) -> Chebfun: 

61 """Return the piecewise ceiling of ``f``.""" 

62 return _step_at_integer_crossings(f, np.ceil) 

63 

64 

65def floor(f: Chebfun) -> Chebfun: 

66 """Return the piecewise floor of ``f``.""" 

67 return _step_at_integer_crossings(f, np.floor) 

68 

69 

70def _step_at_integer_crossings(f: Chebfun, rounder: Callable[[Any], Any]) -> Chebfun: 

71 """Build the piecewise-constant ``rounder(f)`` (used by :func:`ceil`/:func:`floor`). 

72 

73 Splits the domain where ``f`` crosses integer values and assigns each piece 

74 the rounded value at its midpoint. 

75 """ 

76 crossings = _integer_crossings(f) 

77 newdom = f.domain.merge(crossings) 

78 funs = [] 

79 for fun in f._break(newdom): 

80 mid = fun.support[0] + 0.5 * (fun.support[-1] - fun.support[0]) 

81 c = float(rounder(float(f(mid)))) 

82 funs.append(Bndfun.initconst(c, fun.interval)) 

83 result = f.__class__(funs) 

84 for bp in result.breakpoints: 

85 result.breakdata[bp] = float(rounder(float(f(bp)))) 

86 return result 

87 

88 

89def _integer_crossings(f: Chebfun) -> np.ndarray: 

90 """Return the x-values where ``f`` crosses an integer value. 

91 

92 Finds the roots of ``f - n`` for each integer ``n`` in the range of ``f``. 

93 """ 

94 all_values = np.concatenate([fun.values() for fun in f]) 

95 lo = int(np.floor(np.min(all_values))) 

96 hi = int(np.ceil(np.max(all_values))) 

97 crossings = [] 

98 for n in range(lo, hi + 1): 

99 shifted = f - n 

100 crossings.extend(shifted.roots().tolist()) 

101 return np.array(crossings) 

102 

103 

104def maximum_minimum(f: Chebfun, other: Chebfun, comparator: Callable[..., bool]) -> Any: 

105 """Return the pointwise maximum or minimum of ``f`` and ``other``. 

106 

107 ``comparator`` selects which operand wins on each sub-interval: 

108 ``operator.ge`` gives the pointwise maximum and ``operator.lt`` the minimum. 

109 Only roots where ``f - other`` changes sign are switch points; tangential 

110 contacts are equality points but do not switch branches. 

111 """ 

112 if f.isempty or other.isempty: 

113 return f.__class__.initempty() 

114 

115 # Find the intersection of domains. 

116 try: 

117 # Try to use union if supports match. 

118 newdom = f.domain.union(other.domain) 

119 except SupportMismatch: 

120 # If supports don't match, find the intersection. 

121 a_min, a_max = f.support 

122 b_min, b_max = other.support 

123 

124 c_min = max(a_min, b_min) 

125 c_max = min(a_max, b_max) 

126 

127 # If there's no intersection, return empty. 

128 if c_min >= c_max: 

129 return f.__class__.initempty() 

130 

131 # Restrict both functions to the intersection and recurse. 

132 f_restricted = f.restrict([c_min, c_max]) 

133 other_restricted = other.restrict([c_min, c_max]) 

134 return maximum_minimum(f_restricted, other_restricted, comparator) 

135 

136 diff = f - other 

137 roots = branch_switch_roots(diff, diff.roots()) 

138 newdom = newdom.merge(roots) 

139 switch = newdom.support.merge(roots) 

140 

141 # Defensive: empty inputs return early above, so support has two endpoints. 

142 if switch.size == 0: # pragma: no cover - defensive, see above 

143 return f.__class__.initempty() 

144 

145 keys = 0.5 * ((-1) ** np.arange(switch.size - 1) + 1) 

146 if switch.size > 0 and comparator(other(switch[0]), f(switch[0])): 

147 keys = 1 - keys 

148 funs = np.array([]) 

149 for interval, use_self in zip(switch.intervals, keys, strict=False): 

150 subdom = newdom.restrict(interval) 

151 subfun = f.restrict(subdom) if use_self else other.restrict(subdom) 

152 funs = np.append(funs, subfun.funs) 

153 return f.__class__(funs) 

154 

155 

156def branch_switch_roots(diff: Chebfun, roots: np.ndarray) -> np.ndarray: 

157 """Return the subset of ``roots`` where ``diff`` changes sign.""" 

158 if roots.size == 0: 

159 return roots 

160 

161 support = diff.support 

162 breakpoints = np.concatenate(([support[0]], roots, [support[-1]])) 

163 value_tol = max(1e2 * diff.vscale * prefs.eps, prefs.eps) 

164 interval_signs = np.zeros(breakpoints.size - 1) 

165 for idx, (left, right) in enumerate(pairwise(breakpoints)): 

166 if right <= left: 

167 continue 

168 midpoint = left + 0.5 * (right - left) 

169 value = float(diff(midpoint)) 

170 if abs(value) > value_tol: 

171 interval_signs[idx] = np.sign(value) 

172 

173 def nearest_nonzero(start: int, step: int) -> float: 

174 """Return the nearest non-zero interval sign in ``step`` direction.""" 

175 idx = start 

176 while 0 <= idx < interval_signs.size: 

177 sign = interval_signs[idx] 

178 if sign != 0: 

179 return float(sign) 

180 idx += step 

181 return 0.0 

182 

183 switch_roots = [] 

184 for idx, root in enumerate(roots): 

185 left_sign = nearest_nonzero(idx, -1) 

186 right_sign = nearest_nonzero(idx + 1, +1) 

187 if left_sign * right_sign < 0: 

188 switch_roots.append(root) 

189 return np.asarray(switch_roots)