Coverage for src/hypra/native/backend.py: 84.39%

153 statements  

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

1"""Native exact SymPy backend for proved hypergeometric families. 

2 

3The principal 2F1 family uses an all-order differential-equation/HPL recursion, 

4not an example lookup table. This is an initial native port, not HypExp parity. 

5""" 

6 

7from __future__ import annotations 

8 

9import hashlib 

10import json 

11import os 

12import tempfile 

13from dataclasses import asdict, dataclass 

14from pathlib import Path 

15from typing import Any, Literal 

16 

17import sympy as s 

18from sympy.logic.boolalg import Boolean 

19 

20from .._json import strict_json_loads 

21from ..errors import IncompleteExpansionError, UnsupportedExpressionError 

22from ..serialization import decode_expr, encode_expr 

23from .atom import expand_atom 

24from .planning import plan_expansion 

25 

26 

27@dataclass(frozen=True) 

28class NativeConfig: 

29 """Settings for the native SymPy expansion engine. 

30 

31 Attributes: 

32 max_internal_order: Maximum internal power after accounting for poles 

33 and reductions. 

34 use_cache: Reuse exact expansions from the local disk cache. 

35 cache_dir: Override the default native cache directory. 

36 timeout_seconds: Optional worker-process timeout in seconds. 

37 expansion_library: Optional SQLite file of registered symbolic families. 

38 argument_domain: Domain contract for interior hypergeometric arguments. 

39 unit_endpoint: Require convergence at z=1 or allow supported 

40 meromorphic parameter continuation. 

41 unit_excess_shift: One-based index of a lower parameter to shift at a 

42 fixed excess pole in meromorphic mode. 

43 unit_shift_singular_lowers: Add epsilon to each fixed nonpositive integer 

44 lower parameter at z=1 before cancellation in meromorphic mode. 

45 """ 

46 

47 max_internal_order: int = 12 

48 use_cache: bool = True 

49 cache_dir: str | None = None 

50 timeout_seconds: float | None = None 

51 argument_domain: Literal["real-interval", "principal-disk", "principal-cut-plane"] = ( 

52 "real-interval" 

53 ) 

54 unit_endpoint: Literal["convergent", "meromorphic"] = "convergent" 

55 unit_excess_shift: int | None = None 

56 unit_shift_singular_lowers: bool = False 

57 expansion_library: str | None = None 

58 

59 def __post_init__(self) -> None: 

60 if self.expansion_library is not None and not isinstance(self.expansion_library, str): 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true

61 raise TypeError("expansion_library must be a path string") 

62 if self.unit_endpoint not in ("convergent", "meromorphic"): 62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true

63 raise ValueError("unit_endpoint must be convergent or meromorphic") 

64 if type(self.unit_shift_singular_lowers) is not bool or ( 64 ↛ 67line 64 didn't jump to line 67 because the condition on line 64 was never true

65 self.unit_shift_singular_lowers and self.unit_endpoint != "meromorphic" 

66 ): 

67 raise ValueError("unit_shift_singular_lowers requires a Boolean and meromorphic mode") 

68 if self.unit_excess_shift is not None and ( 

69 self.unit_endpoint != "meromorphic" 

70 or type(self.unit_excess_shift) is not int 

71 or self.unit_excess_shift < 1 

72 ): 

73 raise ValueError("unit_excess_shift requires meromorphic mode and a positive index") 

74 if self.argument_domain not in ("real-interval", "principal-disk", "principal-cut-plane"): 74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true

75 raise ValueError( 

76 "argument_domain must be real-interval, principal-disk or principal-cut-plane" 

77 ) 

78 if self.timeout_seconds is not None and ( 

79 isinstance(self.timeout_seconds, bool) 

80 or not isinstance(self.timeout_seconds, (int, float)) 

81 or not 0 < self.timeout_seconds < float("inf") 

82 ): 

83 raise ValueError("timeout_seconds must be a finite positive number or None") 

84 if type(self.max_internal_order) is not int or self.max_internal_order < 0: 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 raise ValueError("max_internal_order must be a nonnegative integer") 

86 

87 

88@dataclass(frozen=True) 

89class NativeInfo: 

90 """Availability and version details for the native engine.""" 

91 

92 available: bool = True 

93 backend: str = "native-sympy" 

94 algorithm_version: str = "native-contiguous-nested-sums-v3" 

95 sympy_version: str = s.__version__ 

96 error: str | None = None 

97 

98 def as_dict(self) -> dict[str, Any]: 

99 """Return availability and version details as a JSON-compatible mapping.""" 

100 return asdict(self) 

101 

102 

103class NativeBackend: 

104 """Execute exact AST expansion requests with the native recurrence engine. 

105 

106 Args: 

107 config: Native settings. Omit to use the defaults. 

108 """ 

109 

110 def __init__(self, config: NativeConfig | None = None) -> None: 

111 self.config = config or NativeConfig() 

112 if not isinstance(self.config, NativeConfig): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 raise TypeError("Native backend requires NativeConfig") 

114 

115 def info(self) -> NativeInfo: 

116 """Return availability and version information.""" 

117 return NativeInfo() 

118 

119 def _fingerprint(self) -> str: 

120 digest = hashlib.sha256() 

121 package = Path(__file__).resolve().parents[1] 

122 # New endpoint/reduction helpers can change exact expansion results. 

123 # Discover package modules so they cannot be omitted from cache keys. 

124 for source in sorted(package.rglob("*.py")): 

125 digest.update(source.relative_to(package).as_posix().encode()) 

126 digest.update(source.read_bytes()) 

127 return digest.hexdigest() 

128 

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

130 """Execute a protocol expansion request and return the exact result AST. 

131 

132 Args: 

133 request: Mapping containing encoded input and the requested orders. 

134 

135 Returns: 

136 Protocol response with the result, achieved order, and provenance. 

137 """ 

138 if self.config.timeout_seconds is not None: 

139 from .worker import run_bounded 

140 

141 return run_bounded(request, self.config) 

142 return self._expand(request) 

143 

144 def _expand(self, request: dict[str, Any]) -> dict[str, Any]: 

145 expr, eps = decode_expr(request["expression"]), decode_expr(request["epsilon"]) 

146 assumptions = decode_expr(request["assumptions"]) 

147 if not isinstance(expr, s.Expr) or not isinstance(eps, s.Symbol): 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true

148 raise TypeError("Expected a SymPy expression and regulator Symbol") 

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

150 raise TypeError("Assumptions must be a SymPy Boolean") 

151 plan = plan_expansion(expr, eps, request["through"], assumptions) 

152 order = request["internal_order"] 

153 if type(order) is not int or order < plan.internal_order: 153 ↛ 154line 153 didn't jump to line 154 because the condition on line 153 was never true

154 raise IncompleteExpansionError("Insufficient native internal order") 

155 from .canonical import canonical_bases, use_contiguous 

156 from .contiguous import plan_contiguous 

157 from .integer import expansion_depth 

158 from .matched_half import half_parameters 

159 

160 def atom_depth(h): 

161 parsed = half_parameters(h, eps) 

162 if parsed is not None and use_contiguous(*parsed): 

163 return order + plan_contiguous(*parsed, *canonical_bases(*parsed)).extra_order 

164 return expansion_depth(h, eps, order) 

165 

166 canonical_order = max([order, *(atom_depth(h) for h in expr.atoms(s.hyper))]) 

167 if canonical_order > self.config.max_internal_order: 

168 raise UnsupportedExpressionError( 

169 f"Internal order {canonical_order} exceeds configured native limit {self.config.max_internal_order}" 

170 ) 

171 meta = self.info().as_dict() | { 

172 "source_fingerprint": self._fingerprint(), 

173 "canonical_order_max": canonical_order, 

174 "argument_domain": self.config.argument_domain, 

175 "unit_endpoint": self.config.unit_endpoint, 

176 } 

177 payload = json.dumps( 

178 {"request": request, "backend": meta}, sort_keys=True, separators=(",", ":") 

179 ) 

180 key = hashlib.sha256(payload.encode()).hexdigest() 

181 root = ( 

182 Path(self.config.cache_dir).expanduser() 

183 if self.config.cache_dir 

184 else Path.home() / ".cache" / "hypra" / "native" 

185 ) 

186 cache = root / (key + ".json") 

187 if self.config.use_cache and cache.exists(): 

188 try: 

189 envelope = strict_json_loads(cache.read_text()) 

190 encoded = json.dumps(envelope["response"], sort_keys=True, separators=(",", ":")) 

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

192 envelope["key"] == key 

193 and envelope["checksum"] == hashlib.sha256(encoded.encode()).hexdigest() 

194 ): 

195 response = envelope["response"] 

196 response["cache_hit"] = True 

197 return response 

198 except (OSError, ValueError, KeyError, TypeError): 

199 pass 

200 

201 library = None 

202 if ( 

203 self.config.expansion_library is not None 

204 and self.config.argument_domain == "real-interval" 

205 ): 

206 from ..expansion_library import ExpansionLibrary 

207 

208 library = ExpansionLibrary(self.config.expansion_library) 

209 

210 def checked_atom(h): 

211 from .atom import _inside_interval 

212 

213 result = None 

214 if library is not None and _inside_interval(h.argument, assumptions): 

215 result = library._lookup_atom(h, eps, order) 

216 if result is None: 

217 result = expand_atom(h, eps, order, assumptions, self.config.argument_domain) 

218 slope_symbols = ( 

219 set().union(*(s.diff(parameter, eps).free_symbols for parameter in (*h.ap, *h.bq))) 

220 if h.ap or h.bq 

221 else set() 

222 ) 

223 if slope_symbols: 

224 # Each nonpositive integer lower base contributes at most one 

225 # genuine inverse slope factor. Other parameter denominators 

226 # from contiguous operators must cancel exactly. 

227 source_poles = s.prod( 

228 s.diff(parameter, eps) 

229 for parameter in h.bq 

230 if parameter.subs(eps, 0).is_Integer and parameter.subs(eps, 0) <= 0 

231 ) 

232 from .contiguous import _hpl_pieces, _normalize_coefficient 

233 

234 result = _normalize_coefficient(result) 

235 if any( 235 ↛ 239line 235 didn't jump to line 239 because the condition on line 235 was never true

236 s.cancel(source_poles * coefficient).is_polynomial(*slope_symbols) is not True 

237 for coefficient in _hpl_pieces(result).values() 

238 ): 

239 raise IncompleteExpansionError( 

240 "Symbolic regulator slopes left an unresolved parameter denominator" 

241 ) 

242 result = s.expand(result) 

243 return result 

244 

245 replacements = {h: checked_atom(h) for h in expr.atoms(s.hyper)} 

246 expanded = expr.xreplace(replacements) 

247 try: 

248 if request["through"] < plan.valuation_lower_bound: 

249 polynomial = s.S.Zero 

250 else: 

251 shifted = expanded * eps**plan.pole_bound 

252 series = s.series(shifted, eps, 0, request["through"] + plan.pole_bound + 1) 

253 polynomial = s.expand(series.removeO() / eps**plan.pole_bound) 

254 except (NotImplementedError, ValueError, TypeError, RecursionError) as exc: 

255 raise IncompleteExpansionError( 

256 "SymPy could not complete the final Laurent expansion" 

257 ) from exc 

258 if polynomial.has(s.hyper, s.Derivative, s.Subs, s.nan, s.zoo, s.oo, -s.oo): 258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true

259 raise IncompleteExpansionError( 

260 "Native expansion contains unresolved or singular coefficients" 

261 ) 

262 response = { 

263 "result": encode_expr(polynomial), 

264 "complete": True, 

265 "achieved_through": request["through"], 

266 "remainder_order": request["through"] + 1, 

267 "backend": meta, 

268 "provenance": meta, 

269 "order_basis": "proved-native-recurrence-and-conservative-pole-budget", 

270 "cache_hit": False, 

271 } 

272 if self.config.use_cache: 

273 temporary = None 

274 try: 

275 root.mkdir(parents=True, exist_ok=True) 

276 encoded = json.dumps(response, sort_keys=True, separators=(",", ":")) 

277 with tempfile.NamedTemporaryFile("w", dir=root, delete=False) as stream: 

278 temporary = Path(stream.name) 

279 json.dump( 

280 { 

281 "key": key, 

282 "checksum": hashlib.sha256(encoded.encode()).hexdigest(), 

283 "response": response, 

284 }, 

285 stream, 

286 ) 

287 os.replace(temporary, cache) 

288 except OSError: 

289 if temporary is not None: 

290 temporary.unlink(missing_ok=True) 

291 return response