Coverage for src/hypra/api.py: 81.34%

139 statements  

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

1"""Public expansion API with exact input and checked Laurent output.""" 

2 

3from dataclasses import asdict, dataclass 

4from typing import Any, Literal, Protocol, cast 

5 

6import sympy as s 

7from sympy.logic.boolalg import Boolean 

8 

9from .config import BackendConfig 

10from .errors import IncompleteExpansionError, UnsupportedExpressionError 

11from .native import NativeBackend, NativeConfig 

12from .native.planning import laurent_coefficient, plan_expansion 

13 

14type BackendName = Literal["native", "wolfram"] 

15 

16 

17class ExpansionBackend(Protocol): 

18 """Structural interface for an injected expansion backend.""" 

19 

20 def expand(self, request: dict[str, Any], /) -> dict[str, Any]: 

21 """Return a certified expansion response for the exact AST request.""" 

22 ... 

23 

24 

25@dataclass(frozen=True) 

26class ExpansionResult: 

27 """Exact Laurent polynomial plus its remainder and reproducibility record. 

28 

29 ``sympy.sympify(result)`` includes the order remainder. 

30 

31 Attributes: 

32 polynomial: Exact Laurent polynomial used for coefficient algebra. 

33 epsilon: Regulator expanded about zero. 

34 through: Highest certified Laurent power. 

35 provenance: Input ASTs, plan, backend details, and branch conventions. 

36 """ 

37 

38 polynomial: s.Expr 

39 epsilon: s.Symbol 

40 through: int 

41 provenance: dict[str, Any] 

42 

43 @property 

44 def expression(self) -> s.Expr: 

45 """Exact Laurent expansion including the SymPy order remainder.""" 

46 return self.polynomial + s.Order(self.epsilon ** (self.through + 1), (self.epsilon, 0)) 

47 

48 def coefficient(self, power: int) -> s.Expr: 

49 """Return the coefficient of the requested Laurent power. 

50 

51 Args: 

52 power: Integer exponent of the regulator. 

53 

54 Raises: 

55 TypeError: The exponent is not an integer. 

56 ValueError: The exponent exceeds the certified order. 

57 """ 

58 if not isinstance(power, int) or isinstance(power, bool): 58 ↛ 59line 58 didn't jump to line 59 because the condition on line 58 was never true

59 raise TypeError("power must be an integer") 

60 if power > self.through: 

61 raise ValueError("Coefficient is beyond the certified truncation order") 

62 return laurent_coefficient(self.polynomial, self.epsilon, power) 

63 

64 def latex(self, *, include_order: bool = True) -> str: 

65 """Render exact mathematics, including symbolic HPL words, as LaTeX. 

66 

67 Args: 

68 include_order: Include the SymPy order remainder. 

69 """ 

70 return s.latex(self.expression if include_order else self.polynomial) 

71 

72 def _sympy_(self) -> s.Expr: 

73 return self.expression 

74 

75 def to_dict(self) -> dict[str, Any]: 

76 """Return the exact JSON-compatible ASTs, LaTeX, and provenance.""" 

77 from .serialization import encode_expr 

78 

79 return { 

80 "polynomial": encode_expr(self.polynomial), 

81 "epsilon": encode_expr(self.epsilon), 

82 "through": self.through, 

83 "remainder_order": self.through + 1, 

84 "latex": self.latex(), 

85 "provenance": self.provenance, 

86 } 

87 

88 

89def backend_info( 

90 config: NativeConfig | BackendConfig | None = None, 

91 *, 

92 backend: BackendName = "native", 

93) -> dict[str, Any]: 

94 """Report native backend capabilities or inspect an external Wolfram installation. 

95 

96 Args: 

97 config: Configuration for the selected backend. 

98 backend: Engine to inspect. 

99 

100 Returns: 

101 A JSON-compatible capability record including engine availability. 

102 

103 Raises: 

104 ValueError: The backend name is unknown. 

105 """ 

106 if backend == "native": 106 ↛ 108line 106 didn't jump to line 108 because the condition on line 106 was always true

107 info = NativeBackend(cast(NativeConfig | None, config)).info() 

108 elif backend == "wolfram": 

109 from .backend import WolframBackend 

110 

111 info = WolframBackend(cast(BackendConfig | None, config)).info() 

112 else: 

113 raise ValueError("backend must be 'native' or 'wolfram'") 

114 return info.as_dict() if hasattr(info, "as_dict") else asdict(info) 

115 

116 

117def _checked_polynomial( 

118 expr: s.Expr, 

119 epsilon: s.Symbol, 

120 through: int, 

121 lower_bound: int, 

122) -> s.Expr: 

123 if expr.has( 

124 s.Float, s.nan, s.zoo, s.oo, -s.oo, s.Derivative, s.Subs, s.Integral, s.Sum, s.hyper 

125 ): 

126 raise IncompleteExpansionError( 

127 "Backend returned non-exact, unresolved, or non-finite output" 

128 ) 

129 expanded = s.expand(expr) 

130 for term in s.Add.make_args(expanded): 

131 if term == 0: 

132 continue 

133 coefficient, power = term.as_coeff_exponent(epsilon) 

134 if coefficient.has(epsilon) or not power.is_Integer: 

135 raise IncompleteExpansionError("Backend output is not a Laurent polynomial in epsilon") 

136 if power > through or (term != 0 and power < lower_bound): 

137 raise IncompleteExpansionError( 

138 "Backend output contradicts the requested Laurent bounds" 

139 ) 

140 return expanded 

141 

142 

143def expand_epsilon( 

144 expr: s.Expr, 

145 epsilon: s.Symbol, 

146 through: int = 3, 

147 assumptions: Boolean | None = None, 

148 *, 

149 config: NativeConfig | BackendConfig | None = None, 

150 backend: BackendName | ExpansionBackend | None = None, 

151) -> ExpansionResult: 

152 """Expand the complete expression through the inclusive Laurent order. 

153 

154 The default backend is native Python/SymPy and supports documented integer and half-integer 

155 parameter families. Every prefactor is included; atoms are expanded deeper 

156 when poles require it. Unsupported cases fail closed without fallback. 

157 Set backend="wolfram" explicitly to use the experimental external bridge. 

158 

159 Args: 

160 expr: Exact symbolic input without floating-point atoms. 

161 epsilon: Regulator expanded at zero. 

162 through: Inclusive order. For example, 3 includes all poles and epsilon**3. 

163 assumptions: Explicit relational assumptions, such as `And(w > 0, w < 1)`. 

164 Assumptions attached to input symbols are preserved. 

165 config: Settings for the selected backend. Native settings can opt in 

166 to meromorphic parameter continuation at z=1. 

167 backend: Native, Wolfram, or a custom engine implementing `expand`. 

168 The result records a custom engine as injected. 

169 

170 Returns: 

171 Exact Laurent polynomial, order remainder, and provenance. 

172 

173 Raises: 

174 TypeError: The input, regulator, assumptions, or configuration has the wrong type. 

175 ValueError: The backend name is unknown. 

176 UnsupportedExpressionError: The expression or its domain is unsupported. 

177 IncompleteExpansionError: The backend could not certify a complete exact result. 

178 """ 

179 from .backend import WolframBackend 

180 from .serialization import decode_expr, encode_expr 

181 

182 if not isinstance(expr, s.Expr): 

183 raise TypeError("expr must be an exact SymPy expression, not a string") 

184 if not isinstance(epsilon, s.Symbol): 184 ↛ 185line 184 didn't jump to line 185 because the condition on line 184 was never true

185 raise TypeError("epsilon must be a SymPy Symbol") 

186 if assumptions is None: 

187 assumptions = s.true 

188 if not isinstance(assumptions, Boolean): 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 raise TypeError("assumptions must be a SymPy Boolean expression") 

190 if s.simplify(assumptions) is s.false: 

191 raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain") 

192 try: 

193 if s.satisfiable(assumptions, use_lra_theory=True) is False: 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true

194 raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain") 

195 except (AssertionError, ValueError, NotImplementedError) as exc: 

196 if isinstance(exc, UnsupportedExpressionError): 196 ↛ 197line 196 didn't jump to line 197 because the condition on line 196 was never true

197 raise 

198 # Isolated complex-symbol nonzero guards need no ordering theory. 

199 # Remove only Ne(symbol,0) guards whose symbols occur nowhere else in 

200 # the assumption formula; all remaining domain relations still pass LRA. 

201 clauses = list(assumptions.args) if isinstance(assumptions, s.And) else [assumptions] 

202 independent = [] 

203 for clause in clauses: 

204 if not isinstance(clause, s.Unequality): 

205 continue 

206 symbol = clause.lhs if clause.rhs == 0 else clause.rhs if clause.lhs == 0 else None 

207 if isinstance(symbol, s.Symbol) and all( 207 ↛ 203line 207 didn't jump to line 203 because the condition on line 207 was always true

208 other == clause or not other.has(symbol) for other in clauses 

209 ): 

210 independent.append(clause) 

211 if not independent: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true

212 raise UnsupportedExpressionError( 

213 "Assumption consistency is unsupported; use linear real-domain relations" 

214 ) from exc 

215 remaining = s.And(*(clause for clause in clauses if clause not in independent)) 

216 try: 

217 if s.satisfiable(remaining, use_lra_theory=True) is False: 217 ↛ 218line 217 didn't jump to line 218 because the condition on line 217 was never true

218 raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain") 

219 except (AssertionError, ValueError, NotImplementedError) as remainder_error: 

220 if isinstance(remainder_error, UnsupportedExpressionError): 

221 raise 

222 raise UnsupportedExpressionError( 

223 "Assumption consistency is unsupported beyond isolated nonzero guards" 

224 ) from remainder_error 

225 if expr.has(s.Float, s.nan, s.zoo, s.oo, -s.oo): 

226 raise UnsupportedExpressionError( 

227 "Input must be exact and finite; use Rational instead of Float" 

228 ) 

229 # Encode before invoking anything external: this checks all input heads, 

230 # identifiers, exact constants and assumption syntax against a whitelist. 

231 expression_ast, epsilon_ast = encode_expr(expr), encode_expr(epsilon) 

232 assumption_ast = encode_expr(assumptions) 

233 declared: dict[str, s.Symbol] = {} 

234 input_symbols = cast(set[s.Symbol], expr.free_symbols | assumptions.free_symbols | {epsilon}) 

235 for symbol in input_symbols: 

236 if symbol.name in declared and declared[symbol.name] != symbol: 

237 raise UnsupportedExpressionError( 

238 "Symbols with the same name and different assumptions are ambiguous" 

239 ) 

240 declared[symbol.name] = symbol 

241 original_ast = expression_ast 

242 native: NativeBackend | None = None 

243 if backend is None or backend == "native": 

244 from .native.endpoints import rewrite_endpoints 

245 

246 native = NativeBackend(cast(NativeConfig | None, config)) 

247 expr = rewrite_endpoints( 

248 expr, 

249 epsilon, 

250 assumptions, 

251 meromorphic=native.config.unit_endpoint == "meromorphic", 

252 excess_shift=native.config.unit_excess_shift, 

253 shift_singular_lowers=native.config.unit_shift_singular_lowers, 

254 ) 

255 expression_ast = encode_expr(expr) 

256 plan = plan_expansion(expr, epsilon, through, assumptions) 

257 active: ExpansionBackend 

258 if backend == "wolfram": 258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true

259 active = WolframBackend(cast(BackendConfig | None, config)) 

260 injected = False 

261 elif backend is not None and not isinstance(backend, str): 

262 active = backend 

263 injected = True 

264 elif native is not None: 264 ↛ 268line 264 didn't jump to line 268 because the condition on line 264 was always true

265 active = native 

266 injected = False 

267 else: 

268 raise ValueError("Unknown backend; choose 'native' or 'wolfram'") 

269 request = { 

270 "protocol": 1, 

271 "operation": "expand", 

272 "expression": expression_ast, 

273 "epsilon": epsilon_ast, 

274 "through": through, 

275 "internal_order": plan.internal_order, 

276 "assumptions": assumption_ast, 

277 } 

278 response = active.expand(request) 

279 if not isinstance(response, dict): 279 ↛ 280line 279 didn't jump to line 280 because the condition on line 279 was never true

280 raise IncompleteExpansionError("Backend result must be a structured object") 

281 if response.get("complete") is not True: 

282 raise IncompleteExpansionError("Backend marked the expansion incomplete") 

283 if ( 

284 type(response.get("achieved_through")) is not int 

285 or response["achieved_through"] != through 

286 or type(response.get("remainder_order")) is not int 

287 or response["remainder_order"] != through + 1 

288 ): 

289 raise IncompleteExpansionError("Backend did not certify the requested inclusive order") 

290 try: 

291 polynomial = decode_expr(response["result"]) 

292 except (KeyError, ValueError, TypeError) as exc: 

293 raise IncompleteExpansionError("Backend returned an invalid symbolic result") from exc 

294 if not isinstance(polynomial, s.Expr): 

295 raise IncompleteExpansionError("Backend result must be a scalar SymPy expression") 

296 output_symbols = cast(set[s.Symbol], polynomial.free_symbols) 

297 if any(symbol.name not in declared for symbol in output_symbols): 

298 raise IncompleteExpansionError("Backend introduced undeclared symbols") 

299 polynomial = cast( 

300 s.Expr, 

301 polynomial.xreplace({symbol: declared[symbol.name] for symbol in output_symbols}), 

302 ) 

303 polynomial = _checked_polynomial(polynomial, epsilon, through, plan.valuation_lower_bound) 

304 backend_record = response.get("backend", {}) 

305 if not isinstance(backend_record, dict): 305 ↛ 306line 305 didn't jump to line 306 because the condition on line 305 was never true

306 raise IncompleteExpansionError("Backend provenance must be a structured object") 

307 provenance = { 

308 "hypra_version": "0.3.0", 

309 "sympy_version": s.__version__, 

310 "input": original_ast, 

311 "planned_input": expression_ast, 

312 "epsilon": epsilon_ast, 

313 "assumptions": assumption_ast, 

314 "plan": asdict(plan), 

315 "backend": backend_record, 

316 "backend_fingerprint": response.get("provenance", {}), 

317 "cache_hit": response.get("cache_hit", False), 

318 "order_basis": response.get("order_basis"), 

319 "injected_backend": injected, 

320 "branch_convention": "Principal branches", 

321 "unit_endpoint": native.config.unit_endpoint if native is not None else None, 

322 "unit_excess_shift": native.config.unit_excess_shift if native is not None else None, 

323 "unit_shift_singular_lowers": ( 

324 native.config.unit_shift_singular_lowers if native is not None else None 

325 ), 

326 "certificate_scope": "Conditional on backend correctness and the stated input domain", 

327 } 

328 return ExpansionResult(polynomial, epsilon, through, provenance)