Coverage for src/hypra/hpl/alternating.py: 96.64%
97 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 convergent alternating HPL endpoints, without regularization tables."""
3from functools import lru_cache
4from typing import cast
6import sympy as s
8from .._typing import Boundary, ExactScalar, IntegerWord
9from ..errors import UnsupportedExpressionError
10from ..symbolic import MZV, EulerSum
11from .algebra import shuffle_words
12from .endpoints import reduce_mzv
13from .numeric import _word
16def reduce_euler_sum(expression: ExactScalar) -> s.Expr:
17 """Proved eta, MZV, repeated-letter, Newton and colored double-shuffle identities.
19 All convergent colored sums reduce through weight six, retaining the
20 exact primitive ES((5,1),(-1,-1))=HPLs6-zeta(6). Depth-two sums
21 also reduce at weight seven. Other sums remain exact when the supported
22 identities do not reduce them.
24 Args:
25 expression: Exact symbolic expression containing Euler-sum atoms.
26 """
28 def one(atom):
29 indices, colors = tuple(atom.indices), tuple(atom.colors)
30 if len(indices) > 1 and len(set(indices)) == len(set(colors)) == 1:
31 # At finite cutoff these are elementary symmetric polynomials in
32 # x_n=c**n/n**s. Newton identities hold before any infinite limit.
33 # Every power sum converges for our valid inputs, even s=1,c=-1.
34 index, color = indices[0], colors[0]
35 elementary: list[s.Expr] = [s.S.One]
36 powers = [None] + [
37 one(EulerSum((k * index,), (color**k,))) for k in range(1, len(indices) + 1)
38 ]
39 for depth in range(1, len(indices) + 1):
40 elementary.append(
41 s.expand(
42 sum(
43 (-1) ** (k - 1) * elementary[depth - k] * powers[k]
44 for k in range(1, depth + 1)
45 )
46 / depth
47 )
48 )
49 return elementary[-1]
50 if all(c == 1 for c in colors):
51 return reduce_mzv(MZV(indices))
52 if len(indices) == 1:
53 n = indices[0]
54 return -s.log(2) if n == 1 else -(1 - 2 ** (1 - n)) * s.zeta(n)
55 # H((-1)^d;1) = log(2)^d/d!, while its series carries (-1)^d.
56 if all(n == 1 for n in indices) and colors == (-1,) + (1,) * (len(indices) - 1):
57 return (-1) ** len(indices) * s.log(2) ** len(indices) / s.factorial(len(indices))
58 if (
59 2 <= len(indices) <= 24
60 and all(n == 1 for n in indices)
61 and colors == (-1, -1) + (1,) * (len(indices) - 2)
62 ):
63 # ES=-H_{-1,1,...,1}(1). With u=1-t its defining integral is
64 # -1/(d-1)! integral_0^1 (-log u)^(d-1)/(2-u) du=-Li_d(1/2).
65 if len(indices) == 3:
66 return -7 * s.zeta(3) / 8 + s.pi**2 * s.log(2) / 12 - s.log(2) ** 3 / 6
67 return -s.polylog(len(indices), s.S.Half)
68 if indices == (5, 1) and colors == (-1, -1):
69 return atom
70 if sum(indices) <= 6:
71 from .euler_reduction import euler_weight_reductions
73 return euler_weight_reductions(int(sum(indices)))[
74 tuple(
75 (int(index), int(color)) for index, color in zip(indices, colors, strict=True)
76 )
77 ]
78 if len(indices) == 2 and sum(indices) in (3, 5, 7):
79 from .euler_reduction import euler_depth_two_reductions
81 return euler_depth_two_reductions(int(sum(indices)))[
82 tuple(
83 (int(index), int(color)) for index, color in zip(indices, colors, strict=True)
84 )
85 ]
86 return atom
88 if type(expression) is int: 88 ↛ 89line 88 didn't jump to line 89 because the condition on line 88 was never true
89 expression = s.Integer(expression)
90 if not isinstance(expression, s.Basic):
91 raise TypeError("expression must be a SymPy expression, not source text")
92 return cast(s.Expr, expression.replace(lambda node: isinstance(node, EulerSum), one))
95@lru_cache(maxsize=2048)
96def _endpoint(word):
97 if not word:
98 return s.S.One
99 if all(letter == 0 for letter in word):
100 return s.S.Zero
101 # Kernels have fixed positive sign on (0,1); a nonzero-letter tail
102 # has a nonzero endpoint. Only a pure-zero tail cancels a leading 1 pole.
103 if word[0] == 1 and (len(word) == 1 or any(word[1:])):
104 raise UnsupportedExpressionError("Divergent HPL endpoint; no regularization")
105 if word[-1] == 0:
106 shuffled = shuffle_words(word[:-1], (0,))
107 multiplicity = shuffled.pop(word)
108 return s.expand(
109 -sum((count * _endpoint(w) for w, count in shuffled.items()), s.S.Zero) / multiplicity
110 )
111 indices, colors, zeros, previous, factor = [], [], 0, 1, 1
112 for letter in word:
113 if letter == 0:
114 zeros += 1
115 else:
116 indices.append(zeros + 1)
117 colors.append(previous * letter)
118 previous = letter
119 factor *= letter
120 zeros = 0
121 return factor * EulerSum(indices, colors)
124def hpl_alternating_at_one(word: IntegerWord, *, reduced: bool = True) -> s.Expr:
125 """Limit from real 0<z<1 for expanded 0,+1,-1 words, weight <=24.
127 Conditional sums use the outer-index cutoff, not arbitrary reordered sums.
128 Mixed trailing zeros are removed by shuffle with log(z), which vanishes
129 at one even multiplied by any finite power of log(1-z).
131 Args:
132 word: Expanded ternary word with a convergent endpoint.
133 reduced: Apply supported exact constant reductions.
134 """
135 if type(reduced) is not bool: 135 ↛ 136line 135 didn't jump to line 136 because the condition on line 135 was never true
136 raise TypeError("reduced must be Boolean")
137 result = _endpoint(_word(word))
138 return reduce_euler_sum(result) if reduced else result
141def hpl_at_minus_one(word: IntegerWord, *, boundary: Boundary | None = None) -> s.Expr:
142 """Evaluate the finite endpoint at -1 from the upper or lower half plane.
144 Words use expanded ternary letters, through weight 24. The side may be
145 omitted when both boundary values agree. A singular leading -1 with
146 trailing zeros uses the weight-12 endpoint polynomial to check finiteness.
147 """
148 letters = _word(word)
149 if boundary not in (None, "upper", "lower"):
150 raise ValueError("boundary must be upper, lower, or omitted")
151 reflected = tuple(-letter for letter in letters)
152 sign = (-1) ** sum(letter != 0 for letter in letters)
153 if not letters or letters[-1] != 0:
154 return sign * hpl_alternating_at_one(reflected)
156 # Negation interchanges the nonzero kernels with a minus sign. Moving
157 # the tangential basepoint adds +i*pi to the upper-side origin log.
158 # Path composition deconcatenates only suffixes made entirely of zeros.
159 endpoint_log = s.Symbol("_negative_endpoint_log", real=True)
160 upper = s.S.Zero
161 for count in range(len(letters) + 1): 161 ↛ 173line 161 didn't jump to line 173 because the loop on line 161 didn't complete
162 prefix = reflected[: len(letters) - count]
163 if prefix and prefix[0] == 1:
164 from .regularization import hpl_endpoint_polynomial
166 coefficient = hpl_endpoint_polynomial(prefix, endpoint_log)
167 else:
168 coefficient = hpl_alternating_at_one(prefix)
169 upper += coefficient * (s.I * s.pi) ** count / s.factorial(count)
170 if not prefix or prefix[-1] != 0:
171 break
173 upper = s.expand(sign * upper)
174 if upper.has(endpoint_log):
175 raise UnsupportedExpressionError("No finite HPL endpoint established at -1")
176 lower = cast(s.Expr, upper.xreplace({s.I: -s.I}))
177 if boundary is None and lower != upper:
178 raise UnsupportedExpressionError(
179 "Endpoint at -1 requires an explicit upper or lower boundary"
180 )
181 return lower if boundary == "lower" else upper