Coverage for src/hypra/hpl/constants.py: 89.74%

89 statements  

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

1"""Fast convergent Euler-sum constants from exact real Mobius identities. 

2 

3No direct, slowly convergent endpoint summation and no implicit branch choice. 

4Each unreduced endpoint is evaluated using HPLs at 1/3 and 1/2, recursively 

5requiring constants of strictly smaller weight. Precision checks are evidence, 

6not interval certification of all errors. 

7""" 

8 

9from dataclasses import dataclass 

10from functools import lru_cache 

11 

12import mpmath as mp 

13import sympy as s 

14 

15from .._typing import IntegerWord 

16from ..errors import UnsupportedExpressionError 

17from ..symbolic import HPL, MZV, EulerSum 

18from .alternating import hpl_alternating_at_one, reduce_euler_sum 

19from .endpoints import reduce_mzv 

20from .mobius import _MAX_MOBIUS_WEIGHT, mobius_hpl 

21from .numeric import HPLNumericalConvergenceError, MPReal, _evaluate 

22 

23 

24@dataclass(frozen=True) 

25class ConstantNumericResult: 

26 """Approximate real constant; stability_gap is not an interval error bound.""" 

27 

28 value: MPReal 

29 stability_gap: MPReal 

30 dps: int 

31 working_dps: int 

32 method: str = "real-Mobius-weight-recursion" 

33 convention: str = "strict outer-index cutoff; no regularization" 

34 

35 

36def _word(indices, colors): 

37 word, cumulative, factor = [], 1, 1 

38 for index, color in zip(indices, colors, strict=True): 

39 cumulative *= int(color) 

40 word.extend([0] * (int(index) - 1)) 

41 word.append(cumulative) 

42 factor *= cumulative 

43 return tuple(word), factor 

44 

45 

46@lru_cache(maxsize=256) 

47def _remainder(word): 

48 z = s.Symbol("constant_z", positive=True) 

49 remainder = s.expand(mobius_hpl(word, z, domain="0<z<1") - hpl_alternating_at_one(word)) 

50 for atom in remainder.atoms(EulerSum, MZV): 

51 if sum(atom.indices) >= len(word): 51 ↛ 52line 51 didn't jump to line 52 because the condition on line 51 was never true

52 raise UnsupportedExpressionError("Endpoint recursion did not strictly lower weight") 

53 return remainder.subs(z, s.Rational(1, 2)) 

54 

55 

56@lru_cache(maxsize=4096) 

57def _hpl_value(word, argument, digits, max_terms): 

58 # The endpoint evaluator already repeats the entire calculation at 

59 # higher precision. Reuse each guarded interior series across sums. 

60 value, _, _, _ = _evaluate(word, argument, digits + 10, digits + 8, max_terms, "real") 

61 return s.Float(mp.nstr(value, n=digits), digits) 

62 

63 

64@lru_cache(maxsize=1024) 

65def _calculate(constant, digits, max_terms): 

66 ctx = mp.mp.clone() 

67 ctx.dps = digits 

68 

69 def as_float(value): 

70 return s.Float(ctx.nstr(value, n=digits), digits) 

71 

72 @lru_cache(maxsize=512) 

73 def evaluate(atom): 

74 if atom == 1: 

75 return s.S.One 

76 weight = sum(atom.indices) 

77 if weight > _MAX_MOBIUS_WEIGHT: 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true

78 raise UnsupportedExpressionError( 

79 f"Numerical endpoint constants support weight at most {_MAX_MOBIUS_WEIGHT}" 

80 ) 

81 if isinstance(atom, MZV): 

82 reduced = reduce_mzv(atom) 

83 if reduced == atom: 

84 return evaluate(EulerSum(atom.indices, (1,) * len(atom.indices))) 

85 else: 

86 reduced = reduce_euler_sum(atom) 

87 # Unreduced same-weight MZVs convert back to this EulerSum; evaluate 

88 # those by the endpoint recursion rather than creating a cycle. 

89 if reduced != atom and not reduced.has(EulerSum, MZV): 

90 return reduced.evalf(digits) 

91 colors = tuple(atom.colors) if isinstance(atom, EulerSum) else (1,) * len(atom.indices) 

92 word, factor = _word(atom.indices, colors) 

93 expression = _remainder(word) 

94 constants = expression.atoms(EulerSum, MZV) 

95 if any(sum(child.indices) >= weight for child in constants): 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true

96 raise UnsupportedExpressionError("Endpoint recursion did not strictly lower weight") 

97 expression = expression.xreplace({child: evaluate(child) for child in constants}) 

98 expression = expression.xreplace( 

99 { 

100 h: _hpl_value(tuple(h.word), h.argument, digits, max_terms) 

101 for h in expression.atoms(HPL) 

102 } 

103 ) 

104 residual = expression.evalf(digits) 

105 if residual.free_symbols or residual.is_real is not True or residual.is_finite is not True: 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true

106 raise UnsupportedExpressionError( 

107 "Endpoint recursion left an unevaluated numeric expression" 

108 ) 

109 value = _hpl_value(word, s.Rational(1, 3), digits, max_terms) 

110 return as_float(factor * (ctx.mpf(str(value)) - ctx.mpf(str(residual)))) 

111 

112 result = evaluate(constant).evalf(digits) 

113 return ctx.mpf(str(result)) 

114 

115 

116def _run(constant, dps, max_terms): 

117 if type(dps) is not int or not 2 <= dps <= 900: 

118 raise ValueError("dps must be an integer between 2 and 900") 

119 if type(max_terms) is not int or not 1 <= max_terms <= 1000000: 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true

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

121 if constant != 1 and sum(constant.indices) > _MAX_MOBIUS_WEIGHT: 

122 raise UnsupportedExpressionError( 

123 f"Numerical endpoint constants support weight at most {_MAX_MOBIUS_WEIGHT}" 

124 ) 

125 first = _calculate(constant, dps + 20, max_terms) 

126 second = _calculate(constant, dps + 40, max_terms) 

127 ctx = mp.mp.clone() 

128 ctx.dps = dps + 40 

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

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

131 raise HPLNumericalConvergenceError("Endpoint constant unstable at increased precision") 

132 return ConstantNumericResult(second, gap, dps, dps + 40) 

133 

134 

135def evaluate_euler_sum( 

136 indices: IntegerWord, 

137 colors: IntegerWord, 

138 *, 

139 dps: int = 50, 

140 max_terms: int = 100000, 

141) -> ConstantNumericResult: 

142 """Numerically evaluate a convergent strict colored sum of weight <=8. 

143 

144 The two-list input uses EulerSum's explicit sigma**n convention. Each 

145 recursive step must lower weight. HPL tail targets and repeated guarded 

146 precision checks are not a certified bound on the final constant's error. 

147 

148 Args: 

149 indices: Strict descending sum exponents. 

150 colors: One sign per index. 

151 dps: Requested decimal precision. 

152 max_terms: Maximum terms per interior HPL series. 

153 """ 

154 return _run(EulerSum(indices, colors), dps, max_terms) 

155 

156 

157def evaluate_mzv( 

158 indices: IntegerWord, 

159 *, 

160 dps: int = 50, 

161 max_terms: int = 100000, 

162) -> ConstantNumericResult: 

163 """Numerically evaluate a convergent strict multiple zeta of weight at most eight. 

164 

165 Args: 

166 indices: Positive integer indices with a leading index of at least two. 

167 The empty word gives one. 

168 dps: Requested decimal precision. 

169 max_terms: Maximum terms per interior HPL series. 

170 """ 

171 return _run(MZV(indices), dps, max_terms)