Coverage for src/hypra/symbolic.py: 91.15%
243 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"""Lossless harmonic-polylogarithm representation.
3``HPL((a1, ..., an), z)`` uses the expanded Remiddi--Vermaseren alphabet
4``ai in {-1, 0, 1}`` with kernels ``1/(1+t)``, ``1/t`` and ``1/(1-t)``.
5In particular H_1(z) = -log(1-z), not log(1-z). The object deliberately
6retains the symbolic function, including its word, without branch-changing
7simplifications. Its analytic continuation is the principal continuation
8from the real interval 0 < z < 1 unless an external calculation specifies
9otherwise. It does not encode a separate continuation path.
10"""
12from __future__ import annotations
14from typing import Self, cast
16from sympy import (
17 Basic,
18 Dummy,
19 Expr,
20 Function,
21 Integer,
22 Order,
23 Tuple,
24 ceiling,
25 factorial,
26 log,
27 polylog,
28)
29from sympy.core.function import ArgumentIndexError, PoleError
31from ._typing import ExactScalar, IntegerWord
34class HPL(Function):
35 """A harmonic polylogarithm with an explicit, expanded letter word.
37 Use :meth:`from_compressed` for HypExp/HPL's compressed integer indices:
38 ``HPL.from_compressed((2, -1), z) == HPL((0, 1, -1), z)``.
39 A compressed zero is one zero letter. No numerical or branch-dependent
40 reduction is performed automatically.
41 """
43 nargs = 2
45 def _eval_is_commutative(self):
46 # The index tuple labels this scalar function and is not a factor.
47 return self.argument.is_commutative
49 def __new__(cls, word: IntegerWord, argument: ExactScalar, **options: object) -> Self:
50 """Construct the exact SymPy function.
52 Args:
53 word: Expanded exact letters from {-1, 0, 1}, in integration order.
54 argument: SymPy argument of the harmonic polylogarithm.
55 **options: Keyword options forwarded to SymPy's function constructor.
56 """
57 # Validate before Function's cache: Python (1.0,) compares equal to
58 # (1,), and otherwise a cached exact object can bypass eval validation.
59 if not isinstance(word, (tuple, list, Tuple)): 59 ↛ 60line 59 didn't jump to line 60 because the condition on line 59 was never true
60 raise TypeError("HPL word must be a tuple/list of exact letters")
61 if any(
62 isinstance(letter, bool)
63 or not isinstance(letter, (int, Integer))
64 or letter not in (-1, 0, 1)
65 for letter in word
66 ):
67 raise ValueError("HPL requires exact expanded letters -1, 0, or 1")
68 return cast(Self, super().__new__(cls, Tuple(*word), argument, **options))
70 # SymPy supplies a fixed set of positional arguments based on nargs.
71 @classmethod
72 def eval(cls, word, argument): # pyright: ignore[reportIncompatibleMethodOverride]
73 if not isinstance(word, Tuple): 73 ↛ 74line 73 didn't jump to line 74 because the condition on line 73 was never true
74 raise TypeError("HPL word must be a tuple of letters -1, 0, or 1")
75 if any(not isinstance(letter, Integer) or letter not in (-1, 0, 1) for letter in word): 75 ↛ 76line 75 didn't jump to line 76 because the condition on line 75 was never true
76 raise ValueError("HPL requires expanded letters -1, 0, or 1; use from_compressed")
78 @classmethod
79 def from_compressed(cls, word: IntegerWord, argument: ExactScalar) -> Self:
80 """Expand signed integer indices without changing their order.
82 Args:
83 word: Signed compressed indices. A standalone zero is one zero letter.
84 argument: SymPy argument of the harmonic polylogarithm.
86 Returns:
87 An HPL with the corresponding expanded word.
88 """
89 if not isinstance(word, (tuple, list, Tuple)): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 raise TypeError("Compressed HPL indices must be a tuple or list of integers")
91 letters = []
92 for index in word:
93 if isinstance(index, bool) or not isinstance(index, (int, Integer)):
94 raise TypeError("Compressed HPL indices must be exact integers")
95 index = int(index)
96 if abs(index) > 10000:
97 raise ValueError("Compressed HPL index exceeds the supported word length")
98 if index == 0:
99 letters.append(Integer(0))
100 else:
101 letters.extend([Integer(0)] * (abs(index) - 1))
102 letters.append(Integer(1 if index > 0 else -1))
103 if len(letters) > 10000: 103 ↛ 104line 103 didn't jump to line 104 because the condition on line 103 was never true
104 raise ValueError("HPL word exceeds the supported length")
105 return cls(Tuple(*letters), argument)
107 @property
108 def word(self) -> Tuple:
109 """Expanded letters, as a SymPy Tuple."""
110 return cast(Tuple, self.args[0])
112 @property
113 def argument(self) -> Expr:
114 """Argument of the harmonic polylogarithm."""
115 return cast(Expr, self.args[1])
117 def fdiff(self, argindex: int = 2) -> Expr:
118 """Differentiate with respect to the argument, not the discrete word.
120 The kernel is 1/z for a leading 0, 1/(1-z) for 1 and
121 1/(1+z) for -1. The empty word is the constant function one.
122 """
123 if argindex != 2:
124 raise ArgumentIndexError(self, argindex)
125 if not self.word:
126 return Integer(0)
127 z = self.argument
128 letter = cast(Integer, self.word[0])
129 kernel = {Integer(0): 1 / z, Integer(1): 1 / (1 - z), Integer(-1): 1 / (1 + z)}[letter]
130 tail = HPL(self.word[1:], z) if len(self.word) > 1 else Integer(1)
131 return kernel * tail
133 def _eval_derivative(self, s):
134 # Function's generic implementation tries to differentiate Tuple(word),
135 # but the letters are discrete constants. Only the argument varies.
136 return self.fdiff(2) * self.argument.diff(s)
138 def _eval_evalf(self, prec):
139 """Evaluate principal values and side-independent finite values at -1."""
140 import mpmath as mp
141 from sympy import Float, I
142 from sympy.core.evalf import prec_to_dps
144 z = self.argument
145 if z.is_number is not True or z.is_finite is not True or len(self.word) > 24:
146 return self
147 digits = max(2, prec_to_dps(prec) + 8)
148 word = self.word
149 if z == -1:
150 from .errors import UnsupportedExpressionError
151 from .hpl.alternating import hpl_at_minus_one
153 try:
154 value_at_endpoint = hpl_at_minus_one(word)
155 except UnsupportedExpressionError:
156 return self
157 return value_at_endpoint.evalf(digits)
158 if z.is_real is False and digits <= 500:
159 from .hpl.radial_continuation import continue_hpl
161 value = continue_hpl(
162 word, z, domain="principal-cut-plane", path="radial", dps=digits
163 ).value
164 return Float(mp.nstr(value.real, n=digits), precision=prec) + I * Float(
165 mp.nstr(value.imag, n=digits), precision=prec
166 )
167 if z.is_positive is not True or (1 - z).is_positive is not True or digits > 1000:
168 return self
169 from .hpl.numeric import hpl_evalf
171 value = hpl_evalf(word, z, dps=digits)
172 return Float(mp.nstr(value, n=digits), precision=prec)
174 def _zero_germ_argument(self, x, logx=None, cdir=0):
175 """Return a leading argument and its positive rational valuation."""
176 from .errors import UnsupportedExpressionError
178 try:
179 leading = self.argument.as_leading_term(x, logx=logx, cdir=cdir)
180 coefficient, power = leading.as_coeff_exponent(x)
181 except (AttributeError, NotImplementedError, ValueError, TypeError, PoleError) as exc:
182 raise UnsupportedExpressionError(
183 "Could not establish a zero-centered HPL argument germ"
184 ) from exc
185 if (
186 coefficient.has(x)
187 or coefficient.is_nonzero is not True
188 or power.is_Rational is not True
189 or power <= 0
190 ):
191 raise UnsupportedExpressionError(
192 "HPL series requires an argument tending to zero with a known "
193 "nonzero coefficient and positive rational power"
194 )
195 return leading, power
197 def _eval_nseries(self, x, n, logx, cdir=0):
198 """Exact zero-germ composition for analytic words and pure log words.
200 SymPy's generic Function implementation differentiates the discrete
201 Tuple word and cannot be used. The kernel-derived local series is used
202 only where its omitted powers give a valid Order term after composition.
203 """
204 from .errors import UnsupportedExpressionError
205 from .hpl.algebra import hpl_series
207 if not self.word:
208 return Integer(1)
209 if not self.argument.has(x): 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true
210 return self
211 if all(letter == 0 for letter in self.word):
212 exact = log(self.argument) ** len(self.word) / factorial(len(self.word))
213 return exact._eval_nseries(x, n, logx, cdir=cdir)
214 center = self.argument.subs(x, 0)
215 if (
216 isinstance(center, Expr)
217 and center.is_number is True
218 and center.is_real is True
219 and center.is_positive is True
220 and (1 - center).is_positive is True
221 ):
222 from .hpl.taylor import hpl_taylor
224 delta = self.argument - center
225 leading = delta.as_leading_term(x, logx=logx, cdir=cdir)
226 coefficient, power = leading.as_coeff_exponent(x)
227 if ( 227 ↛ 233line 227 didn't jump to line 233 because the condition on line 227 was never true
228 coefficient.has(x)
229 or coefficient.is_nonzero is not True
230 or not power.is_Rational
231 or power <= 0
232 ):
233 raise UnsupportedExpressionError(
234 "Could not establish an interior Taylor argument germ"
235 )
236 degree = int(ceiling(max(n, 0) / power)) + 1
237 local = Dummy("hpl_taylor")
238 polynomial = hpl_taylor(self.word, center, local, through=degree).removeO()
239 return polynomial.subs(local, self.argument)._eval_nseries(
240 x, n, logx, cdir=cdir
241 ) + Order(x**n, x)
242 if self.word[-1] == 0:
243 raise UnsupportedExpressionError(
244 "Mixed trailing-zero HPL words have logarithmic germs; use "
245 "hypra.hpl.algebra.hpl_series for explicit local terms"
246 )
247 _, power = self._zero_germ_argument(x, logx, cdir)
248 # Expand strictly deeper than required: omitted analytic argument powers
249 # have valuation > n, so appending O(x**n) cannot overstate accuracy.
250 local_order = int(ceiling(max(n, 0) / power)) + 1
251 local_variable = Dummy("hpl_germ", positive=True)
252 germ = hpl_series(HPL(self.word, local_variable), local_variable, local_order)
253 composed = germ.subs(local_variable, self.argument)
254 return composed._eval_nseries(x, n, logx, cdir=cdir) + Order(x**n, x)
256 # SymPy infers Self from its default hook, but accepts any leading expression.
257 def _eval_as_leading_term(self, x, logx=None, cdir=0): # pyright: ignore[reportIncompatibleMethodOverride]
258 from .errors import UnsupportedExpressionError
259 from .hpl.algebra import hpl_series
261 if not self.word: 261 ↛ 262line 261 didn't jump to line 262 because the condition on line 261 was never true
262 return Integer(1)
263 if not self.argument.has(x): 263 ↛ 264line 263 didn't jump to line 264 because the condition on line 263 was never true
264 return self
265 if all(letter == 0 for letter in self.word):
266 exact = log(self.argument) ** len(self.word) / factorial(len(self.word))
267 return exact.as_leading_term(x, logx=logx, cdir=cdir)
268 if self.word[-1] == 0: 268 ↛ 269line 268 didn't jump to line 269 because the condition on line 268 was never true
269 raise UnsupportedExpressionError(
270 "Mixed trailing-zero HPL leading terms require explicit hpl_series"
271 )
272 leading, _ = self._zero_germ_argument(x, logx, cdir)
273 # Each nonzero kernel increases the first analytic power by one; zero
274 # kernels preserve it. Its coefficient comes from the exact germ engine.
275 degree = sum(letter != 0 for letter in self.word)
276 local_variable = Dummy("hpl_germ", positive=True)
277 germ = hpl_series(HPL(self.word, local_variable), local_variable, degree + 1)
278 return germ.as_leading_term(local_variable).subs(local_variable, leading)
280 def _latex(self, printer):
281 word = ",".join(printer._print(letter) for letter in self.word)
282 return rf"H_{{{word}}}\!\left({printer._print(self.argument)}\right)"
285def _constant_evalf(atom, prec, evaluator, arguments):
286 """Explicit constant evalf, without importing numerical engines at startup."""
287 import mpmath as mp
288 from sympy import Float
289 from sympy.core.evalf import prec_to_dps
291 from .hpl.mobius import _MAX_MOBIUS_WEIGHT
293 digits = max(2, prec_to_dps(prec) + 8)
294 if sum(atom.indices) > _MAX_MOBIUS_WEIGHT or digits > 900:
295 return atom
296 value = evaluator(*arguments, dps=digits).value
297 return Float(mp.nstr(value, n=digits), precision=prec)
300class MZV(Function):
301 """An exact convergent multiple zeta value in strict descending convention.
303 MZV((s1,...,sd)) = sum_{n1>...>nd>=1} prod(nj**(-sj)), where every
304 index is a positive integer and s1 >= 2. The empty word evaluates to one.
305 No divergent regularization or numerical fitting is implied. Reduction to
306 ordinary zeta values is opt-in through ``hypra.hpl.endpoints.reduce_mzv``.
307 """
309 nargs = 1
311 def __new__(cls, indices: IntegerWord, **options: object) -> Expr:
312 """Construct the exact SymPy function.
314 Args:
315 indices: Positive summation exponents with first index at least two.
316 **options: Keyword options forwarded to SymPy's function constructor.
317 """
318 if not isinstance(indices, (tuple, list, Tuple)):
319 raise TypeError("MZV indices must be a tuple/list of exact integers")
320 if any(
321 isinstance(index, bool) or not isinstance(index, (int, Integer)) or index <= 0
322 for index in indices
323 ):
324 raise ValueError("MZV indices must be exact positive integers")
325 if indices and indices[0] < 2:
326 raise ValueError("A convergent MZV requires first index >= 2")
327 return cast(Expr, super().__new__(cls, Tuple(*indices), **options))
329 # SymPy supplies a fixed set of positional arguments based on nargs.
330 @classmethod
331 def eval(cls, indices): # pyright: ignore[reportIncompatibleMethodOverride]
332 if not isinstance(indices, Tuple): 332 ↛ 333line 332 didn't jump to line 333 because the condition on line 332 was never true
333 raise TypeError("MZV indices must be a tuple of positive integers")
334 if not indices:
335 return Integer(1)
336 if any(not isinstance(index, Integer) or index <= 0 for index in indices): 336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true
337 raise ValueError("MZV indices must be exact positive integers")
338 if indices[0] < 2: 338 ↛ 339line 338 didn't jump to line 339 because the condition on line 338 was never true
339 raise ValueError("A convergent MZV requires first index >= 2")
341 @property
342 def indices(self) -> Tuple:
343 """Strict descending summation exponents."""
344 return cast(Tuple, self.args[0])
346 def _eval_evalf(self, prec):
347 from .hpl.constants import evaluate_mzv
349 return _constant_evalf(self, prec, evaluate_mzv, (self.indices,))
351 def _eval_derivative(self, s):
352 return Integer(0)
354 def _eval_is_real(self):
355 return True
357 def _eval_is_positive(self):
358 return True
360 def _latex(self, printer):
361 indices = ",".join(printer._print(index) for index in self.indices)
362 return rf"\zeta\!\left({indices}\right)"
365class EulerSum(Function):
366 r"""Strict colored sum sum_{n1>...>nd>=1} prod colors[j]**nj / nj**indices[j].
368 Outer-cutoff convergence is used, including conditional convergence when
369 the first index is one and its color is minus one. No regularization.
370 Construction preserves indices and colors rather than reducing constants.
371 """
373 nargs = 2
375 def __new__(cls, indices: IntegerWord, colors: IntegerWord, **options: object) -> Expr:
376 """Construct the exact SymPy function.
378 Args:
379 indices: Positive summation exponents.
380 colors: One sign (-1 or 1) per index.
381 **options: Keyword options forwarded to SymPy's function constructor.
382 """
383 if not isinstance(indices, (tuple, list, Tuple)) or not isinstance( 383 ↛ 386line 383 didn't jump to line 386 because the condition on line 383 was never true
384 colors, (tuple, list, Tuple)
385 ):
386 raise TypeError("EulerSum indices and colors must be exact tuples/lists")
387 if len(indices) != len(colors):
388 raise ValueError("EulerSum requires one color per index")
389 if any(isinstance(n, bool) or not isinstance(n, (int, Integer)) or n <= 0 for n in indices):
390 raise ValueError("EulerSum indices must be positive exact integers")
391 if any(
392 isinstance(c, bool) or not isinstance(c, (int, Integer)) or c not in (-1, 1)
393 for c in colors
394 ):
395 raise ValueError("EulerSum colors must be exact -1 or 1")
396 if indices and indices[0] == 1 and colors[0] == 1:
397 raise ValueError("Divergent EulerSum; no regularized value is assigned")
398 return cast(Expr, super().__new__(cls, Tuple(*indices), Tuple(*colors), **options))
400 # SymPy supplies a fixed set of positional arguments based on nargs.
401 @classmethod
402 def eval(cls, indices, colors): # pyright: ignore[reportIncompatibleMethodOverride]
403 if not indices:
404 return Integer(1)
406 @property
407 def indices(self) -> Tuple:
408 """Strict descending summation exponents."""
409 return cast(Tuple, self.args[0])
411 @property
412 def colors(self) -> Tuple:
413 """Sign raised to the corresponding summation index."""
414 return cast(Tuple, self.args[1])
416 def _eval_evalf(self, prec):
417 from .hpl.constants import evaluate_euler_sum
419 return _constant_evalf(self, prec, evaluate_euler_sum, (self.indices, self.colors))
421 def _eval_derivative(self, s):
422 return Integer(0)
424 def _eval_is_real(self):
425 return True
427 def _latex(self, printer):
428 indices = ",".join(printer._print(n) for n in self.indices)
429 colors = ",".join(printer._print(c) for c in self.colors)
430 return (
431 rf"\operatorname{{ES}}\!\left[\begin{{matrix}}{indices}\\{colors}\end{{matrix}}\right]"
432 )
435def reduce_known_hpl(expression: ExactScalar) -> Expr:
436 """Reduce selected HPL words to exact logarithms and classical polylogs.
438 This is deliberately opt-in: construction/serialization retain HPL objects.
439 Conventions are the principal branches continued from 0 < z < 1, with the
440 same side of cuts in both HPL and output functions. This routine performs
441 no argument transformations, no power/log simplification and no assertion
442 that the expression is regular at a branch point.
444 Supported identities are the empty word (one), all-zero, all-one,
445 all-minus-one words, and zero strings followed by plus or minus one. Mixed words outside
446 these patterns remain symbolic. Formulae hold away from singular endpoints
447 and extend there only when the corresponding limit exists.
448 """
449 if type(expression) is int:
450 expression = Integer(expression)
451 if not isinstance(expression, Basic):
452 raise TypeError("expression must be a SymPy expression")
454 def reduce_one(atom):
455 word, z = atom.word, atom.argument
456 weight = len(word)
457 if not word:
458 return Integer(1)
459 if all(letter == 0 for letter in word):
460 return log(z) ** weight / factorial(weight)
461 if all(letter == 1 for letter in word):
462 return (-log(1 - z)) ** weight / factorial(weight)
463 if all(letter == -1 for letter in word):
464 return log(1 + z) ** weight / factorial(weight)
465 if word[-1] in (-1, 1) and all(letter == 0 for letter in word[:-1]):
466 return word[-1] * polylog(weight, word[-1] * z)
467 return atom
469 return cast(Expr, expression.replace(lambda node: isinstance(node, HPL), reduce_one))