Coverage for src/hypra/native/planning.py: 88.06%

174 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 22:12 +0000

1"""Conservative Laurent-order planning; no numerical inference of pole orders.""" 

2 

3from collections.abc import Callable 

4from dataclasses import dataclass 

5from typing import cast 

6 

7import sympy as s 

8from sympy.logic.boolalg import Boolean 

9 

10from ..errors import UnsupportedExpressionError 

11 

12# SymPy's signature infers bool from the default, but accepts Boolean relations. 

13_ask = cast(Callable[[s.Basic, Boolean], bool | None], s.ask) 

14_refine = cast(Callable[[s.Basic, Boolean], s.Basic], s.refine) 

15 

16 

17@dataclass(frozen=True) 

18class ExpansionPlan: 

19 """Conservative orders used to compute and certify the Laurent expansion.""" 

20 

21 through: int 

22 pole_bound: int 

23 internal_order: int 

24 valuation_lower_bound: int 

25 

26 

27def _facts(assumptions): 

28 clauses = assumptions.args if isinstance(assumptions, s.And) else (assumptions,) 

29 facts = [] 

30 for clause in clauses: 

31 if isinstance(clause, s.StrictGreaterThan): 

32 facts.append(s.Q.positive(cast(s.Expr, clause.lhs) - cast(s.Expr, clause.rhs))) 

33 elif isinstance(clause, s.StrictLessThan): 

34 facts.append(s.Q.positive(cast(s.Expr, clause.rhs) - cast(s.Expr, clause.lhs))) 

35 elif isinstance(clause, s.Unequality): 

36 facts.append(s.Q.nonzero(cast(s.Expr, clause.lhs) - cast(s.Expr, clause.rhs))) 

37 else: 

38 facts.append(clause) 

39 return s.And(*facts) 

40 

41 

42def _positive(expr, assumptions): 

43 return _ask(s.Q.positive(expr), _facts(assumptions)) is True 

44 

45 

46def _positive_real_part(expr, assumptions): 

47 # ask(positive(re(a)), positive(a)) alone does not infer re(a)=a. 

48 real_part = _refine(s.re(expr), _facts(assumptions)) 

49 return _positive(real_part, assumptions) 

50 

51 

52def _affine_rational(expr, epsilon): 

53 try: 

54 poly = s.Poly(expr, epsilon) 

55 except s.PolynomialError as exc: 

56 raise UnsupportedExpressionError( 

57 "Hypergeometric parameters must be affine in epsilon with rational bases" 

58 ) from exc 

59 if poly.degree() > 1 or not poly.nth(0).is_Rational: 

60 raise UnsupportedExpressionError( 

61 "Hypergeometric parameters must be affine in epsilon with rational bases" 

62 ) 

63 base = poly.nth(0) 

64 if base.q not in (1, 2): 

65 raise UnsupportedExpressionError("Only integer/half-integer parameter bases are supported") 

66 from .nested_sums import _slope 

67 

68 try: 

69 slope = _slope(poly.nth(1), epsilon) 

70 except (TypeError, ValueError) as exc: 

71 raise UnsupportedExpressionError("Slopes must be exact algebraic polynomials") from exc 

72 return base, slope 

73 

74 

75def _exact_rational_valuation(expr, epsilon, assumptions): 

76 """Order of a rational polynomial quotient when leading coefficients are nonzero.""" 

77 try: 

78 num, den = s.cancel(expr).as_numer_denom() 

79 pn, pd = s.Poly(num, epsilon), s.Poly(den, epsilon) 

80 except s.PolynomialError as exc: 

81 raise UnsupportedExpressionError("Cannot establish denominator order exactly") from exc 

82 if pn.is_zero: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true

83 raise UnsupportedExpressionError( 

84 "A zero denominator or inverse-zero expression is undefined" 

85 ) 

86 orders = [] 

87 for p in (pn, pd): 

88 k = min(m[0] for m, c in p.terms() if c != 0) 

89 c = p.nth(k) 

90 if c.is_nonzero is not True and _ask(s.Q.nonzero(c), _facts(assumptions)) is not True: 

91 raise UnsupportedExpressionError( 

92 f"Nonzero leading coefficient {c} requires an explicit nonzero assumption" 

93 ) 

94 orders.append(k) 

95 return orders[0] - orders[1] 

96 

97 

98def plan_expansion( 

99 expr: s.Expr, 

100 epsilon: s.Symbol, 

101 through: int, 

102 assumptions: Boolean = s.true, 

103) -> ExpansionPlan: 

104 """Bound every omitted hypergeometric term after multiplying all prefactors. 

105 

106 If the total negative valuation bound is p, request each hypergeometric 

107 atom through N+p. This may over-expand but cannot lose coefficients through 

108 N under the supported affine-parameter/meromorphic-input restrictions. 

109 Unknown orders and essential singularities are rejected, not guessed. 

110 """ 

111 if not isinstance(through, int) or isinstance(through, bool): 

112 raise TypeError("through must be an integer inclusive Laurent order") 

113 negative_budget = 0 

114 # Validate even regulator-independent subexpressions, which valuation 

115 # recursion legitimately treats as constants but must not define at poles. 

116 if any( 

117 not b.has(epsilon) and b.is_integer is True and b.is_nonpositive is True 

118 for atom in expr.atoms(s.hyper) 

119 for b in atom.bq 

120 ): 

121 raise UnsupportedExpressionError("Fixed singular lower hypergeometric parameter") 

122 

123 def visit(node): 

124 nonlocal negative_budget 

125 if not node.has(epsilon): 

126 return 0 

127 if node == epsilon: 

128 return 1 

129 if isinstance(node, s.Add): 

130 # Only products compound the depth needed to absorb poles. 

131 before = negative_budget 

132 budgets, valuations = [], [] 

133 for term in node.args: 

134 negative_budget = before 

135 valuations.append(visit(term)) 

136 budgets.append(negative_budget) 

137 negative_budget = max(budgets) 

138 return min(valuations) 

139 if isinstance(node, s.Mul): 

140 return sum(visit(a) for a in node.args) 

141 if isinstance(node, s.Pow): 

142 base, power = node.args 

143 if power.is_Integer: 

144 if power >= 0: 

145 # Each factor in a repeated product may multiply an omitted term. 

146 before = negative_budget 

147 value = visit(base) 

148 negative_budget = before + (negative_budget - before) * int(power) 

149 return int(power) * value 

150 if base.func in (s.gamma, s.exp): 

151 before = negative_budget 

152 val = visit(base) * int(power) 

153 negative_budget = before 

154 else: 

155 val = _exact_rational_valuation(base, epsilon, assumptions) * int(power) 

156 negative_budget += max(0, -val) 

157 return val 

158 if power.has(epsilon): 

159 if base.has(epsilon): 159 ↛ 160line 159 didn't jump to line 160 because the condition on line 159 was never true

160 raise UnsupportedExpressionError( 

161 "Regulator-dependent base and exponent are unsupported" 

162 ) 

163 # exp(power*log(base)) is analytic in epsilon for nonzero fixed base, 

164 # but keeping a real positive base avoids unqualified branch changes. 

165 if not _positive(base, assumptions): 

166 raise UnsupportedExpressionError( 

167 f"Regulator-dependent powers require a positive base assumption: {base}" 

168 ) 

169 if visit(power) < 0: 169 ↛ 170line 169 didn't jump to line 170 because the condition on line 169 was never true

170 raise UnsupportedExpressionError("Essential singularities are unsupported") 

171 return 0 

172 raise UnsupportedExpressionError( 

173 "Fractional epsilon-dependent powers are not Laurent series" 

174 ) 

175 if node.func == s.gamma: 

176 arg = node.args[0] 

177 try: 

178 p = s.Poly(arg, epsilon) 

179 except s.PolynomialError as exc: 

180 raise UnsupportedExpressionError( 

181 "Gamma argument must be polynomial in epsilon" 

182 ) from exc 

183 c = p.nth(0) 

184 if c.is_Rational: 

185 if c.is_integer and c <= 0: 

186 powers = [k[0] for k, value in p.terms() if k[0] > 0 and value != 0] 

187 if not powers: 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was never true

188 raise UnsupportedExpressionError("Gamma has a fixed pole") 

189 m = min(powers) 

190 coeff = p.nth(m) 

191 if ( 191 ↛ 195line 191 didn't jump to line 195 because the condition on line 191 was never true

192 coeff.is_nonzero is not True 

193 and _ask(s.Q.nonzero(coeff), _facts(assumptions)) is not True 

194 ): 

195 raise UnsupportedExpressionError( 

196 "Gamma pole slope must be provably nonzero" 

197 ) 

198 negative_budget += m 

199 return -m 

200 return 0 

201 numeric_nonpole = ( 

202 c.is_number 

203 and c.is_finite is True 

204 and (c.is_integer is False or c.is_real is False) 

205 ) 

206 if not numeric_nonpole and not _positive_real_part(c, assumptions): 

207 raise UnsupportedExpressionError( 

208 "Gamma base requires a positive real-part assumption or an exact nonpole value" 

209 ) 

210 return 0 

211 if node.func == s.hyper: 

212 if len(node.ap) != len(node.bq) + 1: 212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true

213 raise UnsupportedExpressionError("Initial backend scope is pF(p-1)") 

214 if node.argument.has(epsilon): 

215 raise UnsupportedExpressionError( 

216 "Hypergeometric argument must be epsilon-independent" 

217 ) 

218 pairs = [_affine_rational(a, epsilon) for a in (*node.ap, *node.bq)] 

219 slope_symbols = set().union(*(slope.free_symbols for _, slope in pairs)) 

220 if slope_symbols & node.argument.free_symbols: 

221 raise UnsupportedExpressionError( 

222 "Symbolic slopes must be independent of the argument" 

223 ) 

224 poles = 0 

225 for b in node.bq: 

226 c, slope = _affine_rational(b, epsilon) 

227 if c.is_integer and c <= 0: 

228 if slope == 0: 228 ↛ 229line 228 didn't jump to line 229 because the condition on line 228 was never true

229 raise UnsupportedExpressionError( 

230 "Fixed singular lower hypergeometric parameter" 

231 ) 

232 if _ask(s.Q.nonzero(slope), _facts(assumptions)) is not True: 

233 raise UnsupportedExpressionError( 

234 "Moving lower pole slope must be provably nonzero" 

235 ) 

236 poles += 1 

237 negative_budget += poles 

238 return -poles 

239 if node.func == s.exp: 

240 if visit(node.args[0]) < 0: 240 ↛ 242line 240 didn't jump to line 242 because the condition on line 240 was always true

241 raise UnsupportedExpressionError("Essential singularities are unsupported") 

242 return 0 

243 if node.func == s.log: 243 ↛ 254line 243 didn't jump to line 254 because the condition on line 243 was always true

244 arg = node.args[0] 

245 if not _positive(arg.subs(epsilon, 0), assumptions): 245 ↛ 249line 245 didn't jump to line 249 because the condition on line 245 was always true

246 raise UnsupportedExpressionError( 

247 "Log argument at epsilon=0 must be provably positive" 

248 ) 

249 if visit(arg) < 0: 

250 raise UnsupportedExpressionError( 

251 "Logarithmic epsilon singularities are not Laurent series" 

252 ) 

253 return 0 

254 raise UnsupportedExpressionError(f"Cannot establish Laurent order for {node.func}") 

255 

256 lower = visit(expr) 

257 # At least Taylor order zero is needed even for a negative requested order. 

258 internal = max(0, through + negative_budget) 

259 return ExpansionPlan(through, negative_budget, internal, lower) 

260 

261 

262def laurent_coefficient(expr: s.Expr, epsilon: s.Symbol, power: int) -> s.Expr: 

263 """Extract a Laurent coefficient without assuming epsilon is factored visually. 

264 

265 SymPy expand may put epsilon inside a rational denominator; its Expr.coeff 

266 then misses poles. as_coeff_exponent separates those powers exactly. 

267 """ 

268 result: s.Expr = s.S.Zero 

269 for term in s.Add.make_args(s.expand(expr)): 

270 if term == 0: 270 ↛ 271line 270 didn't jump to line 271 because the condition on line 270 was never true

271 continue 

272 coefficient, exponent = term.as_coeff_exponent(epsilon) 

273 if coefficient.has(epsilon) or not exponent.is_Integer: 273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true

274 raise UnsupportedExpressionError("Expression is not an explicit Laurent polynomial") 

275 if exponent == power: 

276 result += coefficient 

277 return result