Coverage for src/hypra/native/nested_sums.py: 92.65%
157 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"""Native canonical hypergeometric expansion by strict finite harmonic sums.
3No external tables are used. For a positive-index word ``a`` we use
5 H_N(a1,...,ad) = sum_{N >= n1 > ... > nd >= 1} prod_j n_j**(-aj).
7The empty word has value one. Products use the positive-merge quasi-shuffle
8(stuffle) algebra. For example H_N(1)**2 = 2 H_N(1,1) + H_N(2).
9These finite sums are intermediate algebra, not numerical approximations.
10"""
12from __future__ import annotations
14from collections.abc import Mapping, Sequence
15from functools import lru_cache
17import sympy as s
19from .._typing import as_integer_tuple
20from ..symbolic import HPL
22Word = tuple[int, ...]
23HarmonicPolynomial = dict[Word, s.Expr]
26def _word(value) -> Word:
27 if not isinstance(value, (tuple, list, s.Tuple)): 27 ↛ 28line 27 didn't jump to line 28 because the condition on line 27 was never true
28 raise TypeError("A harmonic word must be a tuple/list of positive integer indices")
29 if any(
30 isinstance(index, bool) or not isinstance(index, (int, s.Integer)) or index <= 0
31 for index in value
32 ):
33 raise ValueError("Strict harmonic words require positive integer indices")
34 return as_integer_tuple(value)
37def _coefficient(value) -> s.Expr:
38 if type(value) is int:
39 value = s.Integer(value)
40 if not isinstance(value, s.Expr) or value.has(s.Float, s.nan, s.zoo, s.oo, -s.oo):
41 raise ValueError("Harmonic coefficients must be exact finite SymPy expressions")
42 return value
45def _clean(poly: Mapping) -> HarmonicPolynomial:
46 if not isinstance(poly, Mapping): 46 ↛ 47line 46 didn't jump to line 47 because the condition on line 46 was never true
47 raise TypeError("Harmonic polynomials must map words to exact coefficients")
48 result = {}
49 for word, coefficient in poly.items():
50 word, coefficient = _word(word), _coefficient(coefficient)
51 value = s.expand(result.get(word, s.S.Zero) + coefficient)
52 if value == 0:
53 result.pop(word, None)
54 else:
55 result[word] = value
56 return result
59@lru_cache(maxsize=32768)
60def _quasi_shuffle(left: Word, right: Word) -> tuple[tuple[Word, int], ...]:
61 if not left:
62 return ((right, 1),)
63 if not right:
64 return ((left, 1),)
65 terms = {}
66 for prefix, rest_left, rest_right in (
67 (left[0], left[1:], right),
68 (right[0], left, right[1:]),
69 (left[0] + right[0], left[1:], right[1:]),
70 ):
71 for tail, multiplicity in _quasi_shuffle(rest_left, rest_right):
72 word = (prefix, *tail)
73 terms[word] = terms.get(word, 0) + multiplicity
74 return tuple(sorted(terms.items()))
77def quasi_shuffle(left, right) -> dict[Word, int]:
78 """Multiply two strict finite harmonic words, retaining multiplicities.
80 The return value is a fresh dictionary; modifying it never changes cached
81 products. Merged indices have a positive sign for strict nested sums.
82 """
83 return dict(_quasi_shuffle(_word(left), _word(right)))
86def harmonic_add(*polynomials: Mapping) -> HarmonicPolynomial:
87 """Add finite linear combinations of strict harmonic words."""
88 result = {}
89 for poly in polynomials:
90 for word, coefficient in _clean(poly).items():
91 result[word] = result.get(word, s.S.Zero) + coefficient
92 return _clean(result)
95def harmonic_scale(polynomial: Mapping, coefficient) -> HarmonicPolynomial:
96 """Scale a harmonic polynomial by an exact symbolic scalar."""
97 scalar = _coefficient(coefficient)
98 return _clean({word: scalar * value for word, value in _clean(polynomial).items()})
101def harmonic_product(left: Mapping, right: Mapping) -> HarmonicPolynomial:
102 """Multiply harmonic polynomials using the strict quasi-shuffle algebra."""
103 terms = {}
104 for left_word, left_coefficient in _clean(left).items():
105 for right_word, right_coefficient in _clean(right).items():
106 for word, multiplicity in _quasi_shuffle(left_word, right_word):
107 terms[word] = terms.get(word, s.S.Zero) + (
108 multiplicity * left_coefficient * right_coefficient
109 )
110 return _clean(terms)
113def harmonic_exp(log_coefficients: Mapping[int, Mapping], order: int) -> list[HarmonicPolynomial]:
114 """Coefficients of exp(sum_{m>=1} eps**m L_m), through ``order``.
116 ``L_m`` are harmonic polynomials, and must have strictly positive integer
117 degree keys. The recurrence is F_0=1 and
118 F_n = (1/n) sum_{m=1}^n m L_m * F_{n-m}, where * is quasi-shuffle.
119 Missing L_m are zero. No truncation term is silently inferred from data.
120 """
121 _order(order)
122 if not isinstance(log_coefficients, Mapping): 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true
123 raise TypeError("Logarithmic coefficients must be a degree-to-polynomial mapping")
124 logarithm = {}
125 for degree, poly in log_coefficients.items():
126 if type(degree) is not int or degree <= 0:
127 raise ValueError("Logarithmic degrees must be positive Python integers")
128 logarithm[degree] = _clean(poly)
129 coefficients: list[HarmonicPolynomial] = [{(): s.S.One}]
130 for degree in range(1, order + 1):
131 total = {}
132 for k in range(1, degree + 1):
133 total = harmonic_add(
134 total,
135 harmonic_scale(harmonic_product(logarithm.get(k, {}), coefficients[degree - k]), k),
136 )
137 coefficients.append(harmonic_scale(total, s.Rational(1, degree)))
138 return coefficients
141def harmonic_word_to_hpl(word, argument):
142 """Li_(s1,...,sd)(z) as an expanded 0/1 HPL word, empty word = 1."""
143 indices = _word(word)
144 if not indices:
145 return s.S.One
146 letters = tuple(letter for index in indices for letter in (*([0] * (index - 1)), 1))
147 return HPL(letters, argument)
150def generating_sum(power: int, word, argument):
151 """Exact generating function sum_{n>=1} z^n/n^power H_(n-1)(word).
153 Initially convergent for |z|<1. The native caller enforces its declared real
154 interval 0<z<1 and does not use this identity for a branch-changing rewrite.
155 For power=0, summing the outer geometric series produces z/(1-z).
156 """
157 if type(power) is not int or power < 0:
158 raise ValueError("Generating-sum power must be a nonnegative integer")
159 word = _word(word)
160 if power:
161 return harmonic_word_to_hpl((power, *word), argument)
162 return argument / (1 - argument) * harmonic_word_to_hpl(word, argument)
165def _order(order):
166 if type(order) is not int or order < 0: 166 ↛ 167line 166 didn't jump to line 167 because the condition on line 166 was never true
167 raise ValueError("Expansion order must be a nonnegative Python integer")
170def _rational(value):
171 if type(value) is int:
172 value = s.Integer(value)
173 if not isinstance(value, s.Rational): 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true
174 raise TypeError("Canonical parameter bases must be exact rational numbers")
175 return value
178def _slope(value, regulator=None):
179 """An exact internal polynomial slope, optionally in formal symbols.
181 Public input planning remains rational-affine. Internal contiguous
182 regularization may introduce formal parameters; coefficients must be exact
183 algebraic numbers and dependence on those parameters must be polynomial.
184 """
185 value = _coefficient(value)
186 if regulator is not None and value.has(regulator):
187 raise ValueError("A canonical slope must be independent of the expansion regulator")
188 symbols = tuple(sorted(value.free_symbols, key=s.default_sort_key))
189 if any(type(symbol) is not s.Symbol or symbol.is_commutative is False for symbol in symbols): 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was never true
190 raise ValueError("Formal slopes require ordinary commutative Symbols")
191 if not symbols:
192 if value.is_algebraic is not True: 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true
193 raise ValueError("Constant slopes must be exact algebraic numbers")
194 return value
195 try:
196 polynomial = s.Poly(value, *symbols, extension=True)
197 except (s.PolynomialError, s.CoercionFailed) as exc:
198 raise ValueError("Internal symbolic slopes must be algebraic polynomials") from exc
199 if any(coefficient.is_algebraic is not True for coefficient in polynomial.coeffs()):
200 raise ValueError("Internal slope polynomial coefficients must be exact algebraic numbers")
201 return s.expand(value)
204def canonical_hyper_series(upper_pairs, lower_slopes, z, eps, order):
205 """Expand canonical pF(p-1) with upper bases 0/1 and all lower bases 1.
207 ``upper_pairs`` contains (base, slope) for base+slope*eps; lower parameters
208 are 1+slope*eps. Slopes may be exact algebraic polynomials in internal
209 formal parameters (the public planner admits rational slopes only). The result is an exact finite
210 polynomial through eps**order, with HPL coefficients. It contains no O term:
211 the caller owns the final truncation/provenance and prefactor depth budget.
213 For r zero-base uppers and A their slope product, the n>=1 coefficient is
215 A eps**r / n**r * exp(sum_{m>=1} (-1)**(m+1) eps**m/m *
216 [(sum_upper slopes**m - sum_lower slopes**m)*H_(n-1)(m)
217 +(sum_base1 slopes**m - sum_lower slopes**m)/n**m]).
219 The harmonic and rational n parts are expanded by formal exponential
220 recurrences and then summed by positive-index multiple polylogarithms.
221 This algorithm is not an imported coefficient table.
222 """
223 _order(order)
224 if not isinstance(upper_pairs, Sequence) or not isinstance(lower_slopes, Sequence): 224 ↛ 225line 224 didn't jump to line 225 because the condition on line 224 was never true
225 raise TypeError("Canonical parameters must be finite sequences")
226 if len(upper_pairs) != len(lower_slopes) + 1:
227 raise ValueError("Canonical input must have p upper and p-1 lower parameters")
228 if not isinstance(eps, s.Symbol) or not isinstance(z, s.Expr) or z.has(eps):
229 raise ValueError("Use a symbolic regulator and an epsilon-independent SymPy argument")
230 upper = []
231 for pair in upper_pairs:
232 if not isinstance(pair, (tuple, list, s.Tuple)) or len(pair) != 2: 232 ↛ 233line 232 didn't jump to line 233 because the condition on line 232 was never true
233 raise ValueError("Each upper parameter must be a (base, slope) pair")
234 base, slope = _rational(pair[0]), _slope(pair[1], eps)
235 if base not in (0, 1):
236 raise ValueError("Canonical upper bases must be 0 or 1")
237 upper.append((base, slope))
238 lower = [_slope(value, eps) for value in lower_slopes]
239 zeros = [slope for base, slope in upper if base == 0]
240 count = len(zeros)
241 amplitude = s.prod(zeros)
242 if amplitude == 0 or count > order:
243 return s.S.One
244 residual_order = order - count
245 harmonic_log = {}
246 rational_log = {}
247 for weight in range(1, residual_order + 1):
248 prefactor = s.Rational((-1) ** (weight + 1), weight)
249 lower_power = sum((slope**weight for slope in lower), s.S.Zero)
250 harmonic_log[weight] = {
251 (weight,): prefactor
252 * (sum((slope**weight for _, slope in upper), s.S.Zero) - lower_power)
253 }
254 rational_log[weight] = prefactor * (
255 sum((slope**weight for base, slope in upper if base == 1), s.S.Zero) - lower_power
256 )
257 harmonic_coefficients = harmonic_exp(harmonic_log, residual_order)
258 rational_coefficients = [s.S.One]
259 for degree in range(1, residual_order + 1):
260 rational_coefficients.append(
261 sum(
262 (
263 weight * rational_log[weight] * rational_coefficients[degree - weight]
264 for weight in range(1, degree + 1)
265 ),
266 s.S.Zero,
267 )
268 / degree
269 )
270 result = s.S.One
271 for degree in range(residual_order + 1):
272 for rational_degree in range(degree + 1):
273 for word, coefficient in harmonic_coefficients[degree - rational_degree].items():
274 result += (
275 amplitude
276 * eps ** (count + degree)
277 * coefficient
278 * rational_coefficients[rational_degree]
279 * generating_sum(count + rational_degree, word, z)
280 )
281 return s.expand(result)