Coverage for src/hypra/hypexp_integrals.py: 95.41%

136 statements  

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

1"""Exact logarithmic moments for the native HypExp interface.""" 

2 

3from functools import cache, lru_cache 

4from typing import Literal 

5 

6import sympy as s 

7 

8from ._typing import ExactInteger, ExactScalar 

9from .errors import UnsupportedExpressionError 

10from .hpl.algebra import integrate_from_zero, shuffle_expand 

11 

12 

13def _integers(*values: ExactInteger) -> tuple[int, ...]: 

14 if any(isinstance(value, bool) or not isinstance(value, (int, s.Integer)) for value in values): 

15 raise TypeError("Moment powers must be explicit integers") 

16 return tuple(map(int, values)) 

17 

18 

19def beta_log_moment(n: ExactInteger, m: ExactInteger, p: ExactInteger) -> s.Expr: 

20 r"""Return the integral of u**p log(u)**n log(1-u)**m from zero to one. 

21 

22 The origin requires p + m >= 0. Coefficients of a beta-function generating 

23 series give exact rational combinations of zeta values. Log weight through 

24 32 and polynomial degrees through 4096 are supported; these are algebra 

25 budgets, not restrictions of the beta-function identity. 

26 

27 Args: 

28 n: Nonnegative power of the origin logarithm. 

29 m: Nonnegative power of the endpoint logarithm. 

30 p: Integer power of the integration variable. 

31 

32 Returns: 

33 Exact value of the definite integral. 

34 

35 Raises: 

36 TypeError: A power is not an explicit integer. 

37 ValueError: A logarithm power is negative. 

38 UnsupportedExpressionError: The integral diverges or exceeds the supported bounds. 

39 """ 

40 n, m, p = _integers(n, m, p) 

41 if n < 0 or m < 0: 41 ↛ 42line 41 didn't jump to line 42 because the condition on line 41 was never true

42 raise ValueError("Logarithm powers must be nonnegative") 

43 if p + m < 0: 

44 raise UnsupportedExpressionError("The beta-log moment diverges at zero") 

45 if n + m > 32 or p > 4096: 

46 raise UnsupportedExpressionError("Beta-log moment exceeds the weight or power budget") 

47 return _beta_log_moment(n, m, p) 

48 

49 

50def _exp_bivariate(logarithm, n, m): 

51 """Exponentiate a rectangular exact Taylor jet with zero constant term. 

52 

53 Euler's homogeneous-degree operator gives 

54 (i+j) F[i,j] = sum (r+t) L[r,t] F[i-r,j-t] for F = exp(L). 

55 This avoids differentiating large symbolic Gamma expressions. 

56 """ 

57 coefficients = {(0, 0): s.S.One} 

58 for i in range(n + 1): 

59 for j in range(m + 1): 

60 if i == j == 0: 

61 continue 

62 value = sum( 

63 ( 

64 (r + t) * coefficient * coefficients[i - r, j - t] 

65 for (r, t), coefficient in logarithm.items() 

66 if r <= i and t <= j 

67 ), 

68 s.S.Zero, 

69 ) 

70 coefficients[i, j] = s.expand(value / (i + j)) 

71 return coefficients 

72 

73 

74@lru_cache(maxsize=256) 

75def _beta_log_moment(n, m, p): 

76 r"""Extract n! m! [a^n b^m] B(p+1+a,1+b), including removable poles. 

77 

78 For p>=0 the logarithm of the beta function follows from the Taylor 

79 expansion of log Gamma at positive integers. For p=-1 write B(a,1+b) 

80 as E(a,b)/a, with E=Gamma(1+a)Gamma(1+b)/Gamma(1+a+b). 

81 

82 For p=-r-1, r>=1, Gamma recurrence gives 

83 

84 B(a-r,1+b) = -(1+b/a) F(a,b)/r, 

85 F = E/(1-a/r) prod_{j=1}^{r-1} (1+b/(a-j)). 

86 

87 The residue in a is a polynomial in b of degree r. The convergence 

88 condition m>=r+1 kills it before coefficient extraction. Therefore these 

89 coefficients equal the convergent log moment, not a regularized divergent 

90 integral. The finite products enter through generalized harmonic numbers; 

91 no HPL tables, endpoint limits, or numerical fitting are used. 

92 """ 

93 if m == 0: 

94 return s.S.NegativeOne**n * s.factorial(n) / s.Integer(p + 1) ** (n + 1) 

95 upper_n = n if p >= 0 else n + 1 

96 harmonic_base = p + 1 if p >= 0 else max(0, -p - 2) 

97 harmonics = {k: s.harmonic(harmonic_base, k) for k in range(1, upper_n + m + 1)} 

98 logarithm = {} 

99 for i in range(upper_n + 1): 

100 for j in range(m + 1): 

101 if i == j == 0: 

102 continue 

103 weight = i + j 

104 if j == 0: 

105 if p >= 0: 

106 value = s.S.NegativeOne**i / (i * s.Integer(p + 1) ** i) 

107 elif p < -1: 

108 value = 1 / (i * s.Integer(-p - 1) ** i) 

109 else: 

110 value = s.S.Zero 

111 elif i == 0: 

112 sign = s.S.NegativeOne**j if p >= 0 else -1 

113 value = sign * harmonics[j] / j 

114 else: 

115 zeta_coefficient = s.S.NegativeOne ** (weight + 1) * s.zeta(weight) 

116 harmonic_sign = s.S.NegativeOne**weight if p >= 0 else -1 

117 value = ( 

118 s.binomial(weight, i) 

119 * (zeta_coefficient + harmonic_sign * harmonics[weight]) 

120 / weight 

121 ) 

122 if value != 0: 

123 logarithm[i, j] = value 

124 coefficients = _exp_bivariate(logarithm, upper_n, m) 

125 factorials = s.factorial(n) * s.factorial(m) 

126 if p >= 0: 

127 return s.expand(factorials * coefficients[n, m] / (p + 1)) 

128 if p == -1: 

129 return s.expand(factorials * coefficients[n + 1, m]) 

130 return s.expand(-factorials * (coefficients[n, m] + coefficients[n + 1, m - 1]) / (-p - 1)) 

131 

132 

133def hypergeometric_log_moment( 

134 p: ExactInteger, 

135 n: ExactInteger, 

136 m: ExactInteger, 

137 k: ExactInteger, 

138 q: ExactInteger, 

139 z: ExactScalar, 

140 *, 

141 argument_domain: Literal["real", "principal-cut-plane"] = "real", 

142) -> s.Expr: 

143 r"""Integrate u**p log(u)**n log(1-u)**m log(1-z*u)**k / (z*u-1)**q. 

144 

145 Integration runs from zero to one. Powers are nonnegative integers. 

146 Endpoints z=0 and z=1 are handled exactly when convergent. Symbolic z 

147 is interpreted on the real interval 0<z<1 unless it is provably negative. 

148 Select argument_domain="principal-cut-plane" for exact finite nonreal 

149 points, using the principal logarithm continued from z=0. 

150 

151 Args: 

152 p: Power of the integration variable. 

153 n: Power of the origin logarithm. 

154 m: Power of the endpoint logarithm. 

155 k: Power of the moving-argument logarithm. 

156 q: Power of the moving denominator. 

157 z: Exact real kernel argument, or a symbol with the stated domain. 

158 argument_domain: Real kernels by default, or principal continuation 

159 to exact numeric points off the cut [1,infinity). 

160 

161 Returns: 

162 Exact value of the definite integral. 

163 

164 Raises: 

165 TypeError: A power is not an explicit integer. 

166 ValueError: A power is negative. 

167 UnsupportedExpressionError: The argument, powers, or convergence are unsupported. 

168 """ 

169 p, n, m, k, q = _integers(p, n, m, k, q) 

170 if argument_domain not in ("real", "principal-cut-plane"): 

171 raise ValueError("argument_domain must be real or principal-cut-plane") 

172 if min(p, n, m, k, q) < 0: 172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true

173 raise ValueError("Integral powers must be nonnegative") 

174 if p > 64 or q > 32 or n + m + k + int(q > 0) > 5: 174 ↛ 175line 174 didn't jump to line 175 because the condition on line 174 was never true

175 raise UnsupportedExpressionError("Logarithmic integral exceeds the weight or power budget") 

176 

177 z = s.sympify(z, strict=True) 

178 if not isinstance(z, s.Expr) or z.has(s.Float, s.nan, s.zoo, s.oo, -s.oo): 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true

179 raise UnsupportedExpressionError("The integral argument must be exact and finite") 

180 if argument_domain == "principal-cut-plane" and (z.free_symbols or z.is_finite is not True): 

181 raise UnsupportedExpressionError( 

182 "Principal-cut-plane moments require an exact finite numeric argument" 

183 ) 

184 if z.is_zero is True: 

185 return s.S.Zero if k else s.S.NegativeOne**q * beta_log_moment(n, m, p) 

186 if z == 1: 

187 if n < q: 

188 raise UnsupportedExpressionError("The logarithmic integral diverges at one") 

189 # Reflect u about 1/2, then expand the polynomial (1-u)**p. 

190 return s.Add( 

191 *( 

192 s.S.NegativeOne ** (q + j) * s.binomial(p, j) * beta_log_moment(m + k, n, j - q) 

193 for j in range(p + 1) 

194 ) 

195 ) 

196 if k == q == 0: 

197 return beta_log_moment(n, m, p) 

198 if z.is_negative is True: 

199 # With v=1-u and y=z/(z-1), 1-z*u=(1-z)*(1-y*v). 

200 # Both factors are positive, so the logarithms add on the real branch. 

201 y = s.cancel(z / (z - 1)) 

202 logarithm = s.log(1 - z) 

203 return ( 

204 s.Add( 

205 *( 

206 (-1) ** degree 

207 * s.binomial(p, degree) 

208 * s.binomial(k, weight) 

209 * logarithm ** (k - weight) 

210 * hypergeometric_log_moment(degree, m, n, weight, q, y) 

211 for degree in range(p + 1) 

212 for weight in range(k + 1) 

213 ) 

214 ) 

215 / (1 - z) ** q 

216 ) 

217 if not (argument_domain == "principal-cut-plane" and z.is_real is False): 

218 if z.is_real is False or z.is_positive is False or (1 - z).is_positive is False: 

219 raise UnsupportedExpressionError("The moving-kernel formula requires 0 < z < 1") 

220 if z.is_number and (z.is_positive is not True or (1 - z).is_positive is not True): 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true

221 raise UnsupportedExpressionError("Could not establish 0 < z < 1") 

222 # For nonreal z, the radial segment t=z*u crosses neither the principal 

223 # log cut nor t=1. The real-interval germs below therefore continue to 

224 # these points by analyticity. log(t)-log(z)=log(u) along this segment; 

225 # log(1-z*u) is the principal branch since its segment avoids (-infinity,0]. 

226 if m: 

227 coordinate = s.Dummy("argument", positive=True) 

228 moment = _mixed_log_moment(p, n, m, k, q, coordinate) 

229 return s.S.NegativeOne**q * moment.xreplace({coordinate: z}) 

230 # Set t=z*u so all t-dependent poles are at 0 and 1. 

231 t = s.Dummy("t", positive=True) 

232 integrand = t**p * (s.log(t) - s.log(z)) ** n * s.log(1 - t) ** k / (t - 1) ** q 

233 return integrate_from_zero(integrand, t).subs(t, z) / z ** (p + 1) 

234 

235 

236def _mixed_log_moment(p, n, m, k, q, z): 

237 """Build the exact origin germ with positive denominator (1-z*u)**q.""" 

238 

239 def theta(expression): 

240 return z * s.diff(expression, z) 

241 

242 @cache 

243 def ordinary(p, n, m, k): 

244 if k == 0: 

245 return beta_log_moment(n, m, p) 

246 if p: 

247 # Integrate the derivative of 

248 # u**(p+a)*(1-u)**(1+b)*(1-z*u)**c and differentiate 

249 # in (a,b,c). The endpoints vanish near (0,0,0). 

250 previous = ordinary(p - 1, n, m, k) 

251 result = p * previous + (z - 1) * s.diff(previous, z) 

252 if n: 

253 result += n * (ordinary(p - 1, n - 1, m, k) - ordinary(p, n - 1, m, k)) 

254 if m: 

255 result -= m * ordinary(p, n, m - 1, k) 

256 result -= k * ordinary(p, n, m, k - 1) 

257 return shuffle_expand(result / (p + 1), z) 

258 # Differentiate the Euler equation for 

259 # B(1+a,1+b) * 2F1(-c,1+a;2+a+b;z). 

260 # Its zeroth-parameter operator is (1-z)*theta*(theta+1). 

261 previous = ordinary(0, n, m, k - 1) 

262 rhs = -k * z * (theta(previous) + previous) 

263 if n: 

264 rhs += n * (z - 1) * theta(ordinary(0, n - 1, m, k)) 

265 rhs -= n * k * z * ordinary(0, n - 1, m, k - 1) 

266 if m: 

267 rhs -= m * theta(ordinary(0, n, m - 1, k)) 

268 first = integrate_from_zero(rhs / (z * (1 - z)), z) 

269 return integrate_from_zero(first, z) / z 

270 

271 @cache 

272 def moment(k, q): 

273 if q == 0: 

274 return ordinary(p, n, m, k) 

275 if q == 1: 

276 # theta(log(1-z*u)**(k+1)) gives the difference of the 

277 # q=1 and q=0 integrands, multiplied by -(k+1). 

278 result = moment(k, 0) - theta(moment(k + 1, 0)) / (k + 1) 

279 else: 

280 # Differentiation raises the denominator power. The log 

281 # derivative contributes only at one lower logarithm power. 

282 previous = moment(k, q - 1) 

283 result = previous + theta(previous) / (q - 1) 

284 if k: 

285 result += k * (moment(k - 1, q) - moment(k - 1, q - 1)) / (q - 1) 

286 return shuffle_expand(result, z) 

287 

288 return moment(k, q)