Coverage for src/hypra/hpl/algebra.py: 90.46%
285 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
1"""Exact shuffle algebra and definite rational-HPL integration.
3The domain is the real interval 0 < z < 1, with the HPL conventions in
4``hypra.symbolic``. Rational poles may occur only at 0, 1, and -1. An origin
5limit is computed for the complete primitive, so cancellations between
6separately divergent summands are retained. No unevaluated Integral or guessed
7integration constant is returned.
8"""
10from __future__ import annotations
12from collections import defaultdict
13from functools import lru_cache
15import sympy as s
17from .._typing import ExactInteger, ExactScalar, IntegerWord, as_integer_tuple
18from ..errors import UnsupportedExpressionError
19from ..symbolic import HPL
21_MAX_WEIGHT = 24
22_MAX_TERMS = 16384
23_MAX_POLE = 32
24_LOG = s.Dummy("log_z", real=True)
27def _h(word: tuple[int, ...], z: s.Expr) -> s.Expr:
28 return HPL(s.Tuple(*word), z) if word else s.S.One
31def _word(word: IntegerWord) -> tuple[int, ...]:
32 if not isinstance(word, (tuple, list, s.Tuple)): 32 ↛ 33line 32 didn't jump to line 33 because the condition on line 32 was never true
33 raise UnsupportedExpressionError("An HPL word must be a sequence of -1, 0, 1")
34 if any( 34 ↛ 38line 34 didn't jump to line 38 because the condition on line 34 was never true
35 isinstance(x, bool) or x not in (-1, 0, 1) or not isinstance(x, (int, s.Integer))
36 for x in word
37 ):
38 raise UnsupportedExpressionError("An HPL word must contain exact letters -1, 0, 1")
39 result = as_integer_tuple(word)
40 if len(result) > _MAX_WEIGHT:
41 raise UnsupportedExpressionError(f"HPL integration supports weight at most {_MAX_WEIGHT}")
42 return result
45@lru_cache(maxsize=1024)
46def _shuffle(left: tuple[int, ...], right: tuple[int, ...]):
47 if len(left) + len(right) > _MAX_WEIGHT: 47 ↛ 48line 47 didn't jump to line 48 because the condition on line 47 was never true
48 raise UnsupportedExpressionError(f"Shuffle weight exceeds {_MAX_WEIGHT}")
49 if not left:
50 return ((right, 1),)
51 if not right:
52 return ((left, 1),)
53 counts = defaultdict(int)
54 for word, count in _shuffle(left[1:], right):
55 counts[(left[0], *word)] += count
56 for word, count in _shuffle(left, right[1:]):
57 counts[(right[0], *word)] += count
58 if len(counts) > _MAX_TERMS: 58 ↛ 59line 58 didn't jump to line 59 because the condition on line 58 was never true
59 raise UnsupportedExpressionError("Shuffle expression exceeds the supported term budget")
60 return tuple(sorted(counts.items()))
63def shuffle_words(left: IntegerWord, right: IntegerWord) -> dict[tuple[int, ...], int]:
64 """Return the shuffle words with their exact integer multiplicities."""
65 return dict(_shuffle(_word(left), _word(right)))
68def shuffle_product(left: HPL, right: HPL) -> s.Expr:
69 """Multiply two same-argument HPLs using the shuffle identity."""
70 if not isinstance(left, HPL) or not isinstance(right, HPL): 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true
71 raise TypeError("shuffle_product requires two HPL objects")
72 if left.argument != right.argument: 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true
73 raise UnsupportedExpressionError("Shuffle products require a common HPL argument")
74 return s.Add(
75 *(
76 count * _h(word, left.argument)
77 for word, count in _shuffle(_word(left.word), _word(right.word))
78 )
79 )
82def _input(expression, z):
83 if not isinstance(z, s.Symbol): 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true
84 raise TypeError("The integration variable must be a SymPy Symbol")
85 if isinstance(expression, bool): 85 ↛ 86line 85 didn't jump to line 86 because the condition on line 85 was never true
86 raise TypeError("A boolean is not an integration expression")
87 if isinstance(expression, int): 87 ↛ 88line 87 didn't jump to line 88 because the condition on line 87 was never true
88 expression = s.Integer(expression)
89 if not isinstance(expression, s.Expr): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 raise TypeError("The integrand must be an exact SymPy expression, not source text")
91 if expression.has(s.Float, s.nan, s.zoo, s.oo, -s.oo):
92 raise UnsupportedExpressionError("The integrand must be exact and finite")
93 return expression
96def _as_hpl(expression, z):
97 """Convert only identities with matching principal real branch conventions."""
98 # HPLPM's multilinear kernel conversion is exact on every branch. Calling
99 # SymPy's rewrite hook avoids a module cycle with the notation layer.
100 expression = expression.rewrite(HPL)
101 replacements = {}
102 for atom in expression.atoms(s.log):
103 if not atom.has(z):
104 continue
105 argument = atom.args[0]
106 if argument == z:
107 replacements[atom] = _h((0,), z)
108 elif argument == 1 - z:
109 replacements[atom] = -_h((1,), z)
110 elif argument == 1 + z:
111 replacements[atom] = _h((-1,), z)
112 else:
113 raise UnsupportedExpressionError("Only log(z), log(1-z), log(1+z) are integrated")
114 for atom in expression.atoms(s.polylog):
115 if not atom.has(z):
116 continue
117 order, argument = atom.args
118 if not isinstance(order, s.Integer) or not 1 <= order <= _MAX_WEIGHT: 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 raise UnsupportedExpressionError(
120 "Only positive-integer classical polylog orders are supported"
121 )
122 if argument == z:
123 replacements[atom] = _h((0,) * (int(order) - 1) + (1,), z)
124 elif argument == -z:
125 replacements[atom] = -_h((0,) * (int(order) - 1) + (-1,), z)
126 else:
127 raise UnsupportedExpressionError("Only Li_n(z) and Li_n(-z) are converted to HPLs")
128 for atom in expression.atoms(HPL):
129 _word(atom.word)
130 if atom.argument != z:
131 raise UnsupportedExpressionError(
132 "HPL integration requires the integration variable as argument"
133 )
134 return expression.xreplace(replacements)
137def _expansion_size(expression):
138 """Conservative pre-expansion budget, avoiding a giant multinomial first."""
139 if isinstance(expression, HPL):
140 return 1
141 if expression.is_Add:
142 size = sum(_expansion_size(arg) for arg in expression.args)
143 elif expression.is_Mul:
144 size = 1
145 for arg in expression.args:
146 size *= _expansion_size(arg)
147 if size > _MAX_TERMS: 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true
148 break
149 elif expression.is_Pow and isinstance(expression.exp, s.Integer) and expression.exp > 0:
150 if expression.exp > 128: 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true
151 raise UnsupportedExpressionError("Polynomial power exceeds the supported budget")
152 base_size = _expansion_size(expression.base)
153 size = base_size ** int(expression.exp)
154 else:
155 size = 1
156 if size > _MAX_TERMS:
157 raise UnsupportedExpressionError("Expression expansion exceeds the supported term budget")
158 return size
161def _linear_terms(expression, z):
162 """Map words to rational coefficients, after exact shuffle expansion."""
163 expression = _as_hpl(_input(expression, z), z)
164 _expansion_size(expression)
165 expression = s.expand(expression, log=False, power_base=False, power_exp=False)
166 if len(s.Add.make_args(expression)) > _MAX_TERMS: 166 ↛ 167line 166 didn't jump to line 167 because the condition on line 166 was never true
167 raise UnsupportedExpressionError("HPL expression exceeds the supported term budget")
168 result: defaultdict[tuple[int, ...], s.Expr] = defaultdict(lambda: s.S.Zero)
169 for term in s.Add.make_args(expression):
170 coefficient = s.S.One
171 words = {(): s.S.One}
172 for factor in s.Mul.make_args(term):
173 base, exponent = factor.as_base_exp()
174 if isinstance(base, HPL) and base.argument == z:
175 if not isinstance(exponent, s.Integer) or exponent < 0:
176 raise UnsupportedExpressionError(
177 "Only nonnegative integer powers of HPLs are supported"
178 )
179 word = _word(base.word)
180 if len(word) * exponent > _MAX_WEIGHT: 180 ↛ 181line 180 didn't jump to line 181 because the condition on line 180 was never true
181 raise UnsupportedExpressionError("HPL product exceeds supported total weight")
182 for _ in range(int(exponent)):
183 next_words: defaultdict[tuple[int, ...], s.Expr] = defaultdict(lambda: s.S.Zero)
184 for existing, multiplier in words.items():
185 for combined, count in _shuffle(existing, word):
186 next_words[combined] += multiplier * count
187 words = next_words
188 if len(words) > _MAX_TERMS: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true
189 raise UnsupportedExpressionError(
190 "HPL product exceeds the supported term budget"
191 )
192 else:
193 if any(atom.argument.has(z) for atom in factor.atoms(HPL)): 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true
194 raise UnsupportedExpressionError(
195 "HPLs must occur polynomially, not inside other functions"
196 )
197 coefficient *= factor
198 coefficient = s.cancel(coefficient)
199 if coefficient.is_rational_function(z) is not True:
200 raise UnsupportedExpressionError(
201 "HPL coefficients must be rational in the integration variable"
202 )
203 for word, multiplier in words.items():
204 result[word] += coefficient * multiplier
205 return {word: s.cancel(coefficient) for word, coefficient in result.items() if coefficient != 0}
208def shuffle_expand(expression: ExactScalar, z: s.Symbol) -> s.Expr:
209 """Linearize HPL products, powers and supported logs/polylogs exactly.
211 The result is a sum of rational coefficients times single HPLs. Matching
212 logarithms use the real principal branch on 0 < z < 1. No argument
213 transformations, numeric fitting or branch-changing log identities occur.
215 Args:
216 expression: Exact rational-HPL expression in z.
217 z: Common HPL argument and rational-function variable.
218 """
219 return s.Add(
220 *(coefficient * _h(word, z) for word, coefficient in _linear_terms(expression, z).items())
221 )
224def _pole_multiplicities(denominator, z):
225 poly = s.Poly(denominator, z, domain="EX")
226 multiplicities = {}
227 for pole in (0, 1, -1):
228 factor = s.Poly(z - pole, z, domain="EX")
229 count = 0
230 while poly.degree() > 0:
231 quotient, remainder = poly.div(factor)
232 if not remainder.is_zero:
233 break
234 poly = quotient
235 count += 1
236 if count > _MAX_POLE:
237 raise UnsupportedExpressionError(f"Rational pole order exceeds {_MAX_POLE}")
238 multiplicities[pole] = count
239 if poly.degree() != 0:
240 raise UnsupportedExpressionError(
241 "Rational HPL integration supports poles only at 0, 1 and -1"
242 )
243 return multiplicities
246@lru_cache(maxsize=512)
247def _split_rational(rational, z):
248 """Return R0 and kernel residues such that R=R0'+sum c_a*f_a."""
249 rational = s.cancel(rational)
250 if rational == 0:
251 return s.S.Zero, ()
252 numerator, denominator = s.fraction(rational)
253 multiplicities = _pole_multiplicities(denominator, z)
254 polynomial, _ = s.Poly(numerator, z, domain="EX").div(s.Poly(denominator, z, domain="EX"))
255 primitive = s.Add(
256 *(
257 coefficient * z ** (power[0] + 1) / (power[0] + 1)
258 for power, coefficient in polynomial.terms()
259 )
260 )
261 residues = {}
262 for pole, multiplicity in multiplicities.items():
263 if not multiplicity:
264 continue
265 regular = s.cancel(rational * (z - pole) ** multiplicity)
266 for order in range(1, multiplicity + 1):
267 derivative_order = multiplicity - order
268 coefficient = s.cancel(s.diff(regular, z, derivative_order)).subs(
269 z, pole
270 ) / s.factorial(derivative_order)
271 if coefficient.has(s.nan, s.zoo, s.oo, -s.oo, z): 271 ↛ 272line 271 didn't jump to line 272 because the condition on line 271 was never true
272 raise UnsupportedExpressionError(
273 "Could not establish an exact rational partial fraction"
274 )
275 if order == 1:
276 residues[pole] = -coefficient if pole == 1 else coefficient
277 else:
278 primitive += coefficient * (z - pole) ** (1 - order) / (1 - order)
279 return s.cancel(primitive), tuple(
280 (pole, coefficient) for pole, coefficient in residues.items() if coefficient != 0
281 )
284@lru_cache(maxsize=1024)
285def _primitive(rational, word, z):
286 rational_primitive, residues = _split_rational(s.cancel(rational), z)
287 result = rational_primitive * _h(word, z)
288 result += s.Add(*(coefficient * _h((pole, *word), z) for pole, coefficient in residues))
289 if word and rational_primitive != 0:
290 kernel = {0: 1 / z, 1: 1 / (1 - z), -1: 1 / (1 + z)}[word[0]]
291 result -= _primitive(s.cancel(rational_primitive * kernel), word[1:], z)
292 return result
295def _log_primitive(polynomial, power):
296 """Polynomial Q with d(z^power Q(log z))/dz=z^(power-1) P(log z)."""
297 if power <= 0: 297 ↛ 298line 297 didn't jump to line 298 because the condition on line 297 was never true
298 raise UnsupportedExpressionError("Internal HPL local-series power is not positive")
299 result = s.S.Zero
300 for (degree,), coefficient in s.Poly(polynomial, _LOG).terms():
301 for derivative in range(degree + 1):
302 result += (
303 coefficient
304 * (-1) ** derivative
305 * s.factorial(degree)
306 / s.factorial(degree - derivative)
307 * _LOG ** (degree - derivative)
308 / power ** (derivative + 1)
309 )
310 return s.expand(result)
313@lru_cache(maxsize=1024)
314def _local_hpl(word, through):
315 """Finite exact expansion in z, with polynomial coefficients in log(z)."""
316 if not word:
317 return ((0, s.S.One),)
318 if all(letter == 0 for letter in word):
319 return ((0, _LOG ** len(word) / s.factorial(len(word))),)
320 if through <= 0:
321 return ()
322 head, tail = word[0], word[1:]
323 result: defaultdict[int, s.Expr] = defaultdict(lambda: s.S.Zero)
324 for power, polynomial in _local_hpl(tail, through if head == 0 else through - 1):
325 if head == 0:
326 if power <= 0: 326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true
327 raise UnsupportedExpressionError("Unresolved logarithmic origin term")
328 result[power] += _log_primitive(polynomial, power)
329 else:
330 for kernel_power in range(through - power):
331 target_power = power + kernel_power + 1
332 sign = (-1) ** kernel_power if head == -1 else 1
333 result[target_power] += sign * _log_primitive(polynomial, target_power)
334 return tuple((power, s.expand(polynomial)) for power, polynomial in sorted(result.items()))
337def _origin_constant(expression, z):
338 """Prove a finite origin limit after combining all Laurent-log terms."""
339 powers = defaultdict(lambda: s.S.Zero)
340 for word, rational in _linear_terms(expression, z).items():
341 if rational == 0:
342 continue
343 numerator, denominator = s.fraction(s.cancel(rational))
344 del numerator
345 pole_order = _pole_multiplicities(denominator, z)[0]
346 regular = s.cancel(rational * z**pole_order)
347 hpl_series = _local_hpl(word, pole_order)
348 for j in range(pole_order + 1):
349 rational_coefficient = s.cancel(s.diff(regular, z, j)).subs(z, 0) / s.factorial(j)
350 rational_power = j - pole_order
351 for hpl_power, polynomial in hpl_series:
352 power = rational_power + hpl_power
353 if power <= 0:
354 powers[power] += rational_coefficient * polynomial
355 origin = s.S.Zero
356 for power, polynomial in powers.items():
357 polynomial = s.Poly(s.expand(polynomial), _LOG)
358 for (log_power,), coefficient in polynomial.terms():
359 coefficient = s.simplify(coefficient)
360 if coefficient == 0:
361 continue
362 if power < 0 or log_power > 0:
363 raise UnsupportedExpressionError(
364 "The origin integral diverges or its convergence cannot be proved"
365 )
366 origin += coefficient
367 return s.simplify(origin)
370def primitive_hpl(expression: ExactScalar, z: s.Symbol) -> s.Expr:
371 """An exact local primitive of rational-HPL products, up to a constant.
373 Rational poles must be at 0,±1. Unlike integrate_from_zero, this does not
374 require a finite origin value and does not assign a divergent endpoint.
375 Principal branches on real 0<z<1 are retained; no definite integral or
376 contour continuation is inferred from this local antiderivative.
378 Args:
379 expression: Exact rational-HPL integrand.
380 z: Integration variable.
381 """
382 linear = _linear_terms(expression, z)
383 primitive = s.Add(*(_primitive(rational, word, z) for word, rational in linear.items()))
384 return shuffle_expand(primitive, z)
387def integrate_from_zero(expression: ExactScalar, z: s.Symbol) -> s.Expr:
388 """Compute integral_0^z R(t) HPL(word,t) dt, including shuffle products.
390 Rational coefficients may have poles only at 0, 1, -1; polynomial parts,
391 repeated poles, exact parameter coefficients and finite cancellations at
392 zero are supported. The result applies for 0 < z < 1 with real principal
393 branches. Unsupported structure, excessive resources or an unproved finite
394 origin limit raises UnsupportedExpressionError; no divergent terms are
395 silently regularized. The algorithm recursively lowers HPL word weight.
397 Args:
398 expression: Exact rational-HPL integrand.
399 z: Integration variable and upper endpoint.
401 Raises:
402 UnsupportedExpressionError: The integrand is unsupported or the finite
403 origin limit could not be established.
404 """
405 primitive = primitive_hpl(expression, z)
406 origin = _origin_constant(primitive, z)
407 return primitive - origin
410def inverse_theta_plus(expression: ExactScalar, z: s.Symbol, n: ExactInteger) -> s.Expr:
411 """Regular inverse of theta+n: z^-n integral_0^z t^(n-1) f(t) dt.
413 Here theta=z*d/dz and n is a positive integer. The vanishing integration
414 constant selects the solution without an added homogeneous z^-n term.
415 """
416 if isinstance(n, bool) or not isinstance(n, (int, s.Integer)) or not 1 <= n <= _MAX_POLE:
417 raise UnsupportedExpressionError(
418 f"inverse_theta_plus requires an integer 1 <= n <= {_MAX_POLE}"
419 )
420 return integrate_from_zero(z ** (n - 1) * _input(expression, z), z) / z**n
423def hpl_series(expression: ExactScalar, z: s.Symbol, order: ExactInteger) -> s.Expr:
424 """Return exact Laurent/log terms of argument degree strictly below order.
426 This is an independent local expansion at z=0 on the positive real side,
427 obtained by integrating the defining HPL kernels coefficientwise. It
428 includes negative rational powers and powers of log(z). The return value
429 is a finite truncation, not an equality to the full function and not a
430 falsely asserted O(z**order) remainder (which may carry logarithms).
432 Args:
433 expression: Exact rational-HPL expression.
434 z: Variable approaching zero from above.
435 order: Exclusive upper power, from one to 32.
436 """
437 if isinstance(order, bool) or not isinstance(order, (int, s.Integer)) or not 1 <= order <= 32: 437 ↛ 438line 437 didn't jump to line 438 because the condition on line 437 was never true
438 raise UnsupportedExpressionError("hpl_series requires an integer 1 <= order <= 32")
439 powers = defaultdict(lambda: s.S.Zero)
440 for word, rational in _linear_terms(expression, z).items():
441 if rational == 0:
442 continue
443 _, denominator = s.fraction(s.cancel(rational))
444 pole_order = _pole_multiplicities(denominator, z)[0]
445 through = int(order) - 1 + pole_order
446 if through > 48: 446 ↛ 447line 446 didn't jump to line 447 because the condition on line 446 was never true
447 raise UnsupportedExpressionError("Local HPL series exceeds the supported power budget")
448 regular = s.cancel(rational * z**pole_order)
449 local = _local_hpl(word, through)
450 for j in range(through + 1):
451 coefficient = s.cancel(s.diff(regular, z, j)).subs(z, 0) / s.factorial(j)
452 rational_power = j - pole_order
453 for hpl_power, polynomial in local:
454 power = rational_power + hpl_power
455 if power < order:
456 powers[power] += coefficient * polynomial
457 return s.Add(
458 *(
459 z**power * s.expand(polynomial).subs(_LOG, s.log(z))
460 for power, polynomial in sorted(powers.items())
461 )
462 )