Coverage for src/hypra/native/colored_sums.py: 90.40%

164 statements  

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

1"""Matched-half canonical hypergeometric expansions by colored strict sums. 

2 

3Color convention: H_N((a1,s1),...) sums prod(sj**nj/nj**aj) over 

4N >= n1 > ... > nd >= 1, with signs sj in {-1,1}. In particular the 

5negative color is (-1)**n, not (-1)**(n-1). Products merge indices by 

6addition and colors by multiplication, with a positive stuffle sign. 

7 

8For equally many half-integer upper and lower bases, their unperturbed 

9Pochhammer factors cancel. Doubling the sum index and projecting onto even 

10indices then reduces all coefficient sums to the HPL alphabet {0,1,-1}. 

11This implements the defining-product derivation, not imported expansion tables. 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Mapping, Sequence 

17from functools import lru_cache 

18 

19import sympy as s 

20 

21from ..symbolic import HPL 

22from .nested_sums import _coefficient, _order, _rational, _slope, canonical_hyper_series 

23 

24ColoredWord = tuple[tuple[int, int], ...] 

25ColoredPolynomial = dict[ColoredWord, s.Expr] 

26 

27 

28def _word(value) -> ColoredWord: 

29 if not isinstance(value, (tuple, list, s.Tuple)): 29 ↛ 30line 29 didn't jump to line 30 because the condition on line 29 was never true

30 raise TypeError("A colored word must be a sequence of (positive index, sign) pairs") 

31 result = [] 

32 for pair in value: 

33 if not isinstance(pair, (tuple, list, s.Tuple)) or len(pair) != 2: 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true

34 raise ValueError("A colored letter must be an (index, sign) pair") 

35 index, sign = pair 

36 if isinstance(index, bool) or not isinstance(index, (int, s.Integer)) or index <= 0: 

37 raise ValueError("Colored indices must be positive integers") 

38 if isinstance(sign, bool) or not isinstance(sign, (int, s.Integer)) or sign not in (-1, 1): 

39 raise ValueError("Colored signs must be exact -1 or +1") 

40 result.append((int(index), int(sign))) 

41 return tuple(result) 

42 

43 

44def _clean(poly: Mapping) -> ColoredPolynomial: 

45 if not isinstance(poly, Mapping): 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true

46 raise TypeError("Colored polynomials must map words to exact coefficients") 

47 result = {} 

48 for word, coefficient in poly.items(): 

49 word, coefficient = _word(word), _coefficient(coefficient) 

50 value = s.expand(result.get(word, s.S.Zero) + coefficient) 

51 if value == 0: 

52 result.pop(word, None) 

53 else: 

54 result[word] = value 

55 return result 

56 

57 

58@lru_cache(maxsize=32768) 

59def _quasi_shuffle(left: ColoredWord, right: ColoredWord) -> tuple[tuple[ColoredWord, int], ...]: 

60 if not left: 

61 return ((right, 1),) 

62 if not right: 

63 return ((left, 1),) 

64 terms = {} 

65 merged = (left[0][0] + right[0][0], left[0][1] * right[0][1]) 

66 for prefix, rest_left, rest_right in ( 

67 (left[0], left[1:], right), 

68 (right[0], left, right[1:]), 

69 (merged, 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())) 

75 

76 

77def colored_quasi_shuffle(left, right) -> dict[ColoredWord, int]: 

78 """Strict colored stuffle product, including coincident-word multiplicities.""" 

79 return dict(_quasi_shuffle(_word(left), _word(right))) 

80 

81 

82def colored_add(*polynomials: Mapping) -> ColoredPolynomial: 

83 result = {} 

84 for poly in polynomials: 

85 for word, coefficient in _clean(poly).items(): 

86 result[word] = result.get(word, s.S.Zero) + coefficient 

87 return _clean(result) 

88 

89 

90def colored_scale(polynomial: Mapping, coefficient) -> ColoredPolynomial: 

91 scalar = _coefficient(coefficient) 

92 return _clean({word: scalar * value for word, value in _clean(polynomial).items()}) 

93 

94 

95def colored_product(left: Mapping, right: Mapping) -> ColoredPolynomial: 

96 terms = {} 

97 for left_word, left_coefficient in _clean(left).items(): 

98 for right_word, right_coefficient in _clean(right).items(): 

99 for word, multiplicity in _quasi_shuffle(left_word, right_word): 

100 terms[word] = terms.get(word, s.S.Zero) + ( 

101 multiplicity * left_coefficient * right_coefficient 

102 ) 

103 return _clean(terms) 

104 

105 

106def colored_exp(log_coefficients: Mapping[int, Mapping], order: int) -> list[ColoredPolynomial]: 

107 """Formal exp coefficients via n F_n = sum_m m L_m * F_(n-m).""" 

108 _order(order) 

109 if not isinstance(log_coefficients, Mapping): 109 ↛ 110line 109 didn't jump to line 110 because the condition on line 109 was never true

110 raise TypeError("Logarithmic coefficients must be a degree-to-polynomial mapping") 

111 logarithm = {} 

112 for degree, poly in log_coefficients.items(): 

113 if type(degree) is not int or degree <= 0: 113 ↛ 114line 113 didn't jump to line 114 because the condition on line 113 was never true

114 raise ValueError("Logarithmic degrees must be positive Python integers") 

115 logarithm[degree] = _clean(poly) 

116 coefficients: list[ColoredPolynomial] = [{(): s.S.One}] 

117 for degree in range(1, order + 1): 

118 total = {} 

119 for weight in range(1, degree + 1): 

120 total = colored_add( 

121 total, 

122 colored_scale( 

123 colored_product(logarithm.get(weight, {}), coefficients[degree - weight]), 

124 weight, 

125 ), 

126 ) 

127 coefficients.append(colored_scale(total, s.Rational(1, degree))) 

128 return coefficients 

129 

130 

131def colored_word_to_hpl(word, argument): 

132 """Map a colored multiple polylogarithm to expanded HPL letters. 

133 

134 The input denotes sum_{n1>...>nd>0} argument**n1 * prod(sign_j**nj/nj**aj). 

135 Nonzero HPL letters are cumulative products of these signs. Multiplication 

136 by the product of those cumulative signs converts the standard HPL kernels 

137 to the chosen colored-sum convention. The empty word is one. 

138 """ 

139 word = _word(word) 

140 if not word: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true

141 return s.S.One 

142 letters = [] 

143 cumulative, prefactor = 1, 1 

144 for index, sign in word: 

145 cumulative *= sign 

146 prefactor *= cumulative 

147 letters.extend([0] * (index - 1)) 

148 letters.append(cumulative) 

149 return prefactor * HPL(tuple(letters), argument) 

150 

151 

152def colored_generating_sum(power: int, word, argument, outer_color: int = 1): 

153 """Sum delta**n*x**n/n**power H_(n-1)(word), initially |x|<1. 

154 

155 ``delta`` is outer_color. For power zero the geometric sum must be done 

156 before HPL conversion; simply adding an index zero would be incorrect. 

157 """ 

158 if type(power) is not int or power < 0: 158 ↛ 159line 158 didn't jump to line 159 because the condition on line 158 was never true

159 raise ValueError("Generating-sum power must be a nonnegative integer") 

160 if type(outer_color) is not int or outer_color not in (-1, 1): 

161 raise ValueError("Outer color must be -1 or +1") 

162 word = _word(word) 

163 if power: 

164 return colored_word_to_hpl(((power, outer_color), *word), argument) 

165 prefactor = outer_color * argument / (1 - outer_color * argument) 

166 if not word: 

167 return prefactor 

168 first, *tail = word 

169 return prefactor * colored_word_to_hpl(((first[0], outer_color * first[1]), *tail), argument) 

170 

171 

172def even_generating_sum(power: int, word, argument): 

173 """Project the generating series to even outer indices, at argument t.""" 

174 return ( 

175 colored_generating_sum(power, word, argument, 1) 

176 + colored_generating_sum(power, word, argument, -1) 

177 ) / 2 

178 

179 

180def _pairs(pairs, allowed, label, regulator=None): 

181 if not isinstance(pairs, Sequence): 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true

182 raise TypeError(f"{label} parameters must be a finite sequence") 

183 result = [] 

184 for pair in pairs: 

185 if not isinstance(pair, (tuple, list, s.Tuple)) or len(pair) != 2: 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true

186 raise ValueError(f"Each {label} parameter must be a (base, slope) pair") 

187 base, slope = _rational(pair[0]), _slope(pair[1], regulator) 

188 if base not in allowed: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 raise ValueError(f"Unsupported canonical {label} parameter base") 

190 result.append((base, slope)) 

191 return result 

192 

193 

194def canonical_colored_hyper_series(upper_pairs, lower_pairs, z, eps, order): 

195 """Exact canonical matched-half pF(p-1) series as unreduced HPLs at sqrt(z). 

196 

197 Upper bases may be 0, 1 or 1/2; lower bases 1 or 1/2. Half-base counts must 

198 match. Internal slopes may be exact algebraic polynomials in formal 

199 regularization symbols; public planning still restricts slopes to rationals. 

200 The caller enforces the real domain 

201 0<z<1 before using this expansion, and owns the truncation/prefactor budget. 

202 This routine does not attempt branch transformations or emit an O term. 

203 

204 With integer-base slope power differences U_m (all integer uppers minus 

205 integer lowers), V_m (base-one uppers minus integer lowers), and half-base 

206 difference D_m, the doubled-index logarithm has harmonic coefficients 

207 (-1)**(m+1)*2**(m-1)/m times [(U_m+D_m)H^+ + (U_m-D_m)H^-], 

208 plus (-1)**(m+1)*2**m*V_m/(m*(2n)**m). The global coefficient is 

209 A*eps**r*2**r/(2n)**r, where r counts zero bases and A is their slope product. 

210 """ 

211 _order(order) 

212 half = s.Rational(1, 2) 

213 upper = _pairs(upper_pairs, (0, 1, half), "upper", eps) 

214 lower = _pairs(lower_pairs, (1, half), "lower", eps) 

215 if len(upper) != len(lower) + 1: 215 ↛ 216line 215 didn't jump to line 216 because the condition on line 215 was never true

216 raise ValueError("Canonical colored input must be pF(p-1)") 

217 if not isinstance(eps, s.Symbol) or not isinstance(z, s.Expr) or z.has(eps): 217 ↛ 218line 217 didn't jump to line 218 because the condition on line 217 was never true

218 raise ValueError("Use a symbolic regulator and an epsilon-independent SymPy argument") 

219 if z.has(s.Float, s.nan, s.zoo, s.oo, -s.oo): 

220 raise ValueError("Canonical arguments must be exact and finite") 

221 upper_half = [slope for base, slope in upper if base == half] 

222 lower_half = [slope for base, slope in lower if base == half] 

223 if len(upper_half) != len(lower_half): 

224 raise ValueError("Canonical colored expansion requires matched half-base counts") 

225 if not upper_half: 

226 return canonical_hyper_series(upper, [slope for _, slope in lower], z, eps, order) 

227 zeros = [slope for base, slope in upper if base == 0] 

228 count, amplitude = len(zeros), s.prod(zeros) 

229 if amplitude == 0 or count > order: 

230 return s.S.One 

231 residual_order = order - count 

232 upper_integer = [slope for base, slope in upper if base != half] 

233 upper_one = [slope for base, slope in upper if base == 1] 

234 lower_integer = [slope for base, slope in lower if base == 1] 

235 harmonic_log, rational_log = {}, {} 

236 for weight in range(1, residual_order + 1): 

237 prefactor = s.Rational((-1) ** (weight + 1), weight) 

238 lower_power = sum((slope**weight for slope in lower_integer), s.S.Zero) 

239 integer_difference = sum((slope**weight for slope in upper_integer), s.S.Zero) - lower_power 

240 one_difference = sum((slope**weight for slope in upper_one), s.S.Zero) - lower_power 

241 half_difference = sum((slope**weight for slope in upper_half), s.S.Zero) - sum( 

242 (slope**weight for slope in lower_half), s.S.Zero 

243 ) 

244 harmonic_log[weight] = { 

245 ((weight, 1),): prefactor * 2 ** (weight - 1) * (integer_difference + half_difference), 

246 ((weight, -1),): prefactor * 2 ** (weight - 1) * (integer_difference - half_difference), 

247 } 

248 rational_log[weight] = prefactor * 2**weight * one_difference 

249 harmonic_coefficients = colored_exp(harmonic_log, residual_order) 

250 rational_coefficients = [s.S.One] 

251 for degree in range(1, residual_order + 1): 

252 rational_coefficients.append( 

253 sum( 

254 ( 

255 weight * rational_log[weight] * rational_coefficients[degree - weight] 

256 for weight in range(1, degree + 1) 

257 ), 

258 s.S.Zero, 

259 ) 

260 / degree 

261 ) 

262 t = s.sqrt(z) 

263 result = s.S.One 

264 for degree in range(residual_order + 1): 

265 for rational_degree in range(degree + 1): 

266 for word, coefficient in harmonic_coefficients[degree - rational_degree].items(): 

267 result += ( 

268 amplitude 

269 * 2**count 

270 * eps ** (count + degree) 

271 * coefficient 

272 * rational_coefficients[rational_degree] 

273 * even_generating_sum(count + rational_degree, word, t) 

274 ) 

275 return s.expand(result)