Coverage for src/hypra/hpl/numeric.py: 97.61%

145 statements  

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

1"""High-precision explicitly branched HPL evaluation without nested numerical quadrature. 

2 

3The default domain is real 0 < z < 1; explicit principal-disk mode permits 

40 < |z| < 1 off the negative real axis, with principal logarithm. General words 

5use the convergent local logarithmic power series and an analytic tail bound. 

6Repeated-letter and classical-polylogarithm words use established mpmath 

7functions. Every result is recomputed at a higher working precision to check 

8stability; neither that check nor the tail bound is an interval-arithmetic 

9certificate of all roundoff errors. 

10""" 

11 

12from __future__ import annotations 

13 

14import math 

15import re 

16from dataclasses import dataclass 

17from typing import Literal 

18 

19import mpmath as mp 

20import sympy as s 

21from mpmath.ctx_mp_python import _mpc as MPComplex 

22from mpmath.ctx_mp_python import _mpf as MPReal 

23 

24from .._typing import IntegerWord, as_integer_tuple 

25from ..errors import UnsupportedExpressionError 

26 

27# mpmath creates new mpf and mpc subclasses for each cloned context. 

28type NumericArgument = s.Expr | int | float | complex | str | MPReal | MPComplex 

29type NumericValue = MPReal | MPComplex 

30type NumericDomain = Literal["real", "principal-disk"] 

31 

32_DECIMAL = re.compile(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\Z") 

33_MAX_WEIGHT = 24 

34 

35 

36class HPLNumericalConvergenceError(ArithmeticError): 

37 """The requested precision was not reached within the numerical budget.""" 

38 

39 

40@dataclass(frozen=True) 

41class HPLNumericResult: 

42 """Numerical value with series and working-precision diagnostics. 

43 

44 Attributes: 

45 value: Real or complex mpmath approximation. 

46 tail_bound: Mathematical series truncation bound, excluding roundoff. 

47 Zero for direct elementary and classical calculations. 

48 stability_gap: Absolute difference between the two precision runs. 

49 terms: Number of terms used in the evaluation. 

50 dps: Requested decimal precision. 

51 working_dps: Working decimal precision of the returned value. 

52 method: Evaluation method used. 

53 domain: Domain and branch description. 

54 """ 

55 

56 value: NumericValue 

57 tail_bound: MPReal 

58 stability_gap: MPReal 

59 terms: int 

60 dps: int 

61 working_dps: int 

62 method: str 

63 domain: str = "real 0 < z < 1; principal real HPL branch" 

64 

65 

66def _word(value: IntegerWord) -> tuple[int, ...]: 

67 if not isinstance(value, (tuple, list, s.Tuple)): 67 ↛ 68line 67 didn't jump to line 68 because the condition on line 67 was never true

68 raise TypeError("Numerical HPL input must be a word of exact -1, 0, 1 letters") 

69 if any( 

70 isinstance(letter, bool) 

71 or not isinstance(letter, (int, s.Integer)) 

72 or letter not in (-1, 0, 1) 

73 for letter in value 

74 ): 

75 raise UnsupportedExpressionError("Numerical HPL words require exact -1, 0, 1 letters") 

76 if len(value) > _MAX_WEIGHT: 

77 raise UnsupportedExpressionError(f"Numerical HPL weight exceeds {_MAX_WEIGHT}") 

78 return as_integer_tuple(value) 

79 

80 

81def _argument(value, ctx, domain): 

82 if isinstance(value, bool) or (domain == "real" and isinstance(value, (complex, mp.mpc))): 

83 raise TypeError("Numerical HPL argument must be real") 

84 if isinstance(value, s.Rational): 

85 result = ctx.mpf(int(value.p)) / int(value.q) 

86 elif isinstance(value, s.Expr): 

87 if ( 

88 value.free_symbols 

89 or value.is_finite is not True 

90 or (domain == "real" and value.is_real is not True) 

91 ): 

92 raise UnsupportedExpressionError( 

93 "Numerical HPL argument must be finite and satisfy the explicit domain" 

94 ) 

95 real, imag = value.as_real_imag() 

96 result = ( 

97 ctx.mpc( 

98 ctx.mpf(str(s.N(real, ctx.dps + 10))), 

99 ctx.mpf(str(s.N(imag, ctx.dps + 10))), 

100 ) 

101 if domain == "principal-disk" 

102 else ctx.mpf(str(s.N(real, ctx.dps + 10))) 

103 ) 

104 elif isinstance(value, str): 

105 if len(value) > 4096 or not _DECIMAL.fullmatch(value): 

106 raise ValueError("Use a decimal string, not executable text, for numerical input") 

107 result = ctx.mpf(value) 

108 elif domain == "principal-disk" and isinstance(value, (complex, mp.mpc)): 

109 result = ctx.mpc(value) 

110 elif isinstance(value, (int, float, mp.mpf)): 

111 result = ctx.mpf(value) 

112 else: 

113 raise TypeError("Use an exact SymPy number, decimal string, integer, float or mpmath real") 

114 valid = ( 

115 (0 < result < 1) 

116 if domain == "real" 

117 else (0 < abs(result) < 1 and not (ctx.im(result) == 0 and ctx.re(result) <= 0)) 

118 ) 

119 if not ctx.isfinite(result) or not valid: 

120 raise UnsupportedExpressionError( 

121 "Numerical HPL requires real 0 < z < 1, or explicit principal-disk " 

122 "mode with 0 < |z| < 1 off the negative real axis" 

123 ) 

124 return result 

125 

126 

127def _integrate_polynomial(coefficients, power, ctx): 

128 """Q with (power + d/dL) Q = P, represented by ascending powers of L.""" 

129 result = [ctx.zero] * len(coefficients) 

130 following = ctx.zero 

131 for degree in range(len(coefficients) - 1, -1, -1): 

132 following = (coefficients[degree] - (degree + 1) * following) / power 

133 result[degree] = following 

134 return result 

135 

136 

137def _polynomial_value(coefficients, logarithm, ctx): 

138 value = ctx.zero 

139 for coefficient in reversed(coefficients): 

140 value = value * logarithm + coefficient 

141 return value 

142 

143 

144def _series(word, z, target_digits, max_terms, ctx): 

145 """O(weight * log-degree * terms) recursion, with constant-in-terms memory.""" 

146 weight = len(word) 

147 trailing = 0 

148 for letter in reversed(word): 148 ↛ 152line 148 didn't jump to line 152 because the loop on line 148 didn't complete

149 if letter != 0: 

150 break 

151 trailing += 1 

152 logarithm = ctx.log(z) 

153 # All coefficient polynomials have degree at most the trailing-zero count. 

154 # Starting from L^d/d!, each integration has coefficient norm <= C_d/n, 

155 # while a nonzero kernel sums n preceding coefficients. Consequently the 

156 # uniform norm bound B below gives tail <= B*|z|^(N+1)/(1-|z|). 

157 c_degree = sum( 

158 math.factorial(trailing) // math.factorial(trailing - j) for j in range(trailing + 1) 

159 ) 

160 coefficient_bound = ( 

161 ctx.mpf(c_degree) ** (weight - trailing) 

162 * max(ctx.one, abs(logarithm)) ** trailing 

163 / math.factorial(trailing) 

164 ) 

165 tolerance = ctx.power(10, -target_digits) 

166 size = trailing + 1 

167 # Each suffix has its previous coefficient polynomial. Pure-zero suffixes 

168 # contribute only n=0 and are initialized exactly, including empty=1. 

169 previous = [] 

170 for start in range(weight + 1): 

171 coefficients = [ctx.zero] * size 

172 suffix = word[start:] 

173 if all(letter == 0 for letter in suffix): 

174 coefficients[len(suffix)] = ctx.one / math.factorial(len(suffix)) 

175 previous.append(coefficients) 

176 cumulative = [[ctx.zero] * size for _ in range(weight)] 

177 total, z_power = ctx.zero, ctx.one 

178 for n in range(1, max_terms + 1): 

179 current = [[ctx.zero] * size for _ in range(weight + 1)] 

180 for start in range(weight - 1, -1, -1): 

181 if start >= weight - trailing: 

182 continue # Pure-zero suffixes have no positive-power coefficients. 

183 head = word[start] 

184 if head == 0: 

185 integrand = current[start + 1] 

186 else: 

187 cumulative[start] = [ 

188 previous[start + 1][degree] + head * cumulative[start][degree] 

189 for degree in range(size) 

190 ] 

191 integrand = cumulative[start] 

192 current[start] = _integrate_polynomial(integrand, n, ctx) 

193 z_power *= z 

194 total += z_power * _polynomial_value(current[0], logarithm, ctx) 

195 previous = current 

196 # A factor two leaves numerical slack when evaluating the exact analytic 

197 # majorant at finite working precision; this is not an interval bound. 

198 tail = 2 * coefficient_bound * abs(z_power) * abs(z) / (1 - abs(z)) 

199 if total != 0 and tail <= tolerance * abs(total): 

200 return total, tail, n, "logarithmic-power-series" 

201 raise HPLNumericalConvergenceError( 

202 f"HPL series did not meet the relative truncation target after {max_terms} terms; " 

203 "increase max_terms or use an argument farther from the unit circle" 

204 ) 

205 

206 

207def _evaluate(word, argument, dps, target_digits, max_terms, domain): 

208 # Clone avoids modifying the caller's global mpmath precision. 

209 ctx = mp.mp.clone() 

210 ctx.dps = dps 

211 z = _argument(argument, ctx, domain) 

212 weight = len(word) 

213 if not word: 

214 return ctx.one, ctx.zero, 0, "empty-word" 

215 if all(letter == 0 for letter in word): 

216 return ctx.log(z) ** weight / math.factorial(weight), ctx.zero, 0, "logarithm" 

217 if all(letter == 1 for letter in word): 

218 return (-ctx.log1p(-z)) ** weight / math.factorial(weight), ctx.zero, 0, "logarithm" 

219 if all(letter == -1 for letter in word): 

220 return ctx.log1p(z) ** weight / math.factorial(weight), ctx.zero, 0, "logarithm" 

221 if all(letter == 0 for letter in word[:-1]): 

222 sign = word[-1] 

223 return sign * ctx.polylog(weight, sign * z), ctx.zero, 0, "classical-polylogarithm" 

224 return _series(word, z, target_digits, max_terms, ctx) 

225 

226 

227def evaluate_hpl( 

228 word: IntegerWord, 

229 argument: NumericArgument, 

230 *, 

231 dps: int = 50, 

232 max_terms: int = 100000, 

233 domain: NumericDomain = "real", 

234) -> HPLNumericResult: 

235 """Evaluate a finite {0,±1} word in an explicitly selected branch domain. 

236 

237 The requested ``dps`` is checked by a stricter analytic truncation target 

238 and agreement of calculations at dps+20 and dps+40. This is high-precision 

239 numerical evidence, not rigorous interval certification. Finite-precision 

240 float/mpmath inputs are evaluated at their stored value; prefer an exact 

241 SymPy Rational or decimal string to specify the intended point precisely. 

242 

243 The default domain="real" requires 0 < z < 1. Explicit 

244 domain="principal-disk" allows 0 < |z| < 1 off the negative real axis, 

245 using principal log(z). No continuation beyond this slit disk is applied. 

246 Endpoints are rejected; use hpl_at_one for supported exact endpoints. 

247 

248 Args: 

249 word: Expanded HPL letters, up to weight 24. 

250 argument: Numeric point in the selected domain. 

251 dps: Requested decimal precision, from 2 to 1000. 

252 max_terms: Maximum number of series terms. 

253 domain: Real interior or principal slit-disk domain. 

254 

255 Returns: 

256 Numerical value, series tail bound, and precision diagnostics. 

257 

258 Raises: 

259 UnsupportedExpressionError: The word or argument is outside the supported domain. 

260 HPLNumericalConvergenceError: The series or precision check failed. 

261 """ 

262 word = _word(word) 

263 if domain not in ("real", "principal-disk"): 

264 raise ValueError("domain must be real or principal-disk") 

265 if type(dps) is not int or not 2 <= dps <= 1000: 

266 raise ValueError("dps must be an integer between 2 and 1000") 

267 if type(max_terms) is not int or not 1 <= max_terms <= 1000000: 

268 raise ValueError("max_terms must be an integer between 1 and 1000000") 

269 first, _, _, _ = _evaluate(word, argument, dps + 20, dps + 8, max_terms, domain) 

270 second, tail, terms, method = _evaluate(word, argument, dps + 40, dps + 8, max_terms, domain) 

271 ctx = mp.mp.clone() 

272 ctx.dps = dps + 40 

273 gap = abs(ctx.convert(first) - second) 

274 if gap > ctx.power(10, -dps - 4) * abs(second): 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true

275 raise HPLNumericalConvergenceError( 

276 "HPL numerical result was not stable under increased working precision" 

277 ) 

278 domain_description = ( 

279 "real 0 < z < 1; principal real HPL branch" 

280 if domain == "real" 

281 else "principal slit disk 0 < |z| < 1, -pi < arg(z) < pi; principal log" 

282 ) 

283 return HPLNumericResult(second, tail, gap, terms, dps, dps + 40, method, domain_description) 

284 

285 

286def hpl_evalf( 

287 word: IntegerWord, 

288 argument: NumericArgument, 

289 *, 

290 dps: int = 50, 

291 max_terms: int = 100000, 

292 domain: NumericDomain = "real", 

293) -> NumericValue: 

294 """Return the mpmath value from `evaluate_hpl`. 

295 

296 Args: 

297 word: Expanded HPL letters, up to weight 24. 

298 argument: Numeric point in the selected domain. 

299 dps: Requested decimal precision. 

300 max_terms: Maximum number of series terms. 

301 domain: Real interior or principal slit-disk domain. 

302 """ 

303 return evaluate_hpl(word, argument, dps=dps, max_terms=max_terms, domain=domain).value