Coverage for src/hypra/native/endpoints.py: 86.67%
165 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"""Unit endpoint identities and exact terminating hypergeometric sums.
3Rewriting precedes Laurent planning because Gamma quotients and excess
4recurrences can introduce regulator poles.
5"""
7from __future__ import annotations
9from functools import cache
10from typing import cast
12import sympy as s
13from sympy.logic.boolalg import Boolean
15from ..errors import UnsupportedExpressionError
16from .planning import _positive, _positive_real_part
19def _fixed_nonpositive_integer(value, epsilon):
20 return not value.has(epsilon) and value.is_integer is True and value.is_nonpositive is True
23def _affine(value, epsilon):
24 base = value.subs(epsilon, 0)
25 slope = s.diff(value, epsilon)
26 if slope.has(epsilon) or s.expand(value - base - slope * epsilon) != 0:
27 raise UnsupportedExpressionError(
28 "Gauss endpoint support requires affine regulator parameters"
29 )
30 if base.has(s.oo, -s.oo, s.zoo, s.nan) or slope.has(s.oo, -s.oo, s.zoo, s.nan): 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true
31 raise UnsupportedExpressionError("Endpoint parameters must be finite")
32 return base, slope
35def _convergent(excess, epsilon, assumptions):
36 base, slope = _affine(excess, epsilon)
37 # A strictly positive real part gives an open neighborhood of convergence,
38 # irrespective of the direction of a fixed finite complex slope. Gauss's
39 # identity also applies to irrational and symbolic bases; restricting this
40 # proof to rational values unnecessarily excluded exact Gamma expansions.
41 try:
42 if _positive_real_part(base, assumptions):
43 return True
44 except (ValueError, TypeError):
45 pass
46 if base != 0 or slope == 0:
47 return False
48 # At the boundary, require an explicit punctured-side domain. Do not
49 # infer convergence merely from the existence of a Gamma continuation.
50 real_excess = s.re(excess)
51 try:
52 return _positive(real_excess, assumptions)
53 except (ValueError, TypeError):
54 return False
57def convergent_unit(hyper, epsilon):
58 """Test strictly positive base excess for affine integer/half-integer pF(p-1)."""
59 from .matched_half import half_parameters
61 parsed = half_parameters(hyper, epsilon)
62 if parsed is None or len(hyper.ap) != len(hyper.bq) + 1: 62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true
63 return False
64 upper, lower = parsed
65 if any(base.is_Integer and base <= 0 and slope == 0 for base, slope in lower): 65 ↛ 66line 65 didn't jump to line 66 because the condition on line 65 was never true
66 return False
67 return sum(base for base, _ in lower) > sum(base for base, _ in upper)
70def _raise_unit_excess(upper, lower, excess):
71 """Sum the telescoping coefficient difference on the convergent side."""
72 n = s.Dummy("index")
73 denominator = s.prod(n + b for b in lower)
74 remainder = s.Poly(s.expand(s.prod(n + a for a in upper) + (excess - n) * denominator), n)
75 # The two leading degrees cancel. Express the remainder in falling
76 # factorials so each term can be summed by reindexing a shifted pFq.
77 terms = []
78 for j in range(len(lower) - 1, -1, -1):
79 coefficient = remainder.nth(j)
80 if coefficient == 0: 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true
81 continue
82 remainder -= s.Poly(coefficient * s.ff(n, j), n)
83 scale = s.prod(s.rf(a, j) for a in upper) / s.prod(s.rf(b, j + 1) for b in lower)
84 shifted = s.hyper([a + j for a in upper], [b + j + 1 for b in lower], 1, evaluate=False)
85 terms.append((coefficient * scale, shifted))
86 return terms
89def _reduce_unit_rank(upper, lower):
90 """Remove an upper/lower pair whose ratio is polynomial in the index."""
91 for a in upper:
92 for b in lower:
93 shift = a - b
94 if not shift.is_Integer or not 1 <= shift <= 8:
95 continue
96 ap, bq = list(upper), list(lower)
97 ap.remove(a)
98 bq.remove(b)
99 # Expand (b+n)_shift in the falling factorials of n.
100 return s.Add(
101 *(
102 s.binomial(shift, j)
103 * s.rf(b + j, shift - j)
104 * s.prod(s.rf(value, j) for value in ap)
105 / (s.rf(b, shift) * s.prod(s.rf(value, j) for value in bq))
106 * s.hyper(
107 [value + j for value in ap], [value + j for value in bq], 1, evaluate=False
108 )
109 for j in range(int(shift) + 1)
110 )
111 )
112 return None
115def _continue_unit(upper, lower, excess, epsilon):
116 """Iterate the convergent identity as a meromorphic parameter identity."""
117 base, slope = _affine(excess, epsilon)
118 steps = int(s.floor(-base)) + 1
119 if steps > 8 or len(upper) > 8: 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true
120 raise UnsupportedExpressionError("Unit continuation exceeds eight shifts or rank eight")
121 if base.is_Integer and slope == 0:
122 raise UnsupportedExpressionError("Unit continuation lies on a fixed excess pole")
124 @cache
125 def raise_until_convergent(atom):
126 delta = s.expand(sum(atom.bq) - sum(atom.ap))
127 if cast(s.Expr, delta.subs(epsilon, 0)) > 0:
128 return {atom: s.S.One}
129 result = {}
130 for weight, shifted in _raise_unit_excess(atom.ap, atom.bq, delta):
131 for leaf, coefficient in raise_until_convergent(shifted).items():
132 result[leaf] = result.get(leaf, s.S.Zero) + weight * coefficient
133 return {leaf: s.cancel(coefficient / delta) for leaf, coefficient in result.items()}
135 atom = s.hyper(upper, lower, 1, evaluate=False)
136 return s.Add(*(weight * leaf for leaf, weight in raise_until_convergent(atom).items()))
139def rewrite_endpoints(
140 expr: s.Expr,
141 epsilon: s.Symbol,
142 assumptions: Boolean | None = s.true,
143 *,
144 meromorphic: bool = False,
145 excess_shift: int | None = None,
146 shift_singular_lowers: bool = False,
147) -> s.Expr:
148 """Rewrite terminating sums and unit endpoints before Laurent planning.
150 Other nonterminating arguments are unchanged. With meromorphic=True,
151 continue supported unit endpoints in the parameters. The explicit
152 lower-pole prescription shifts fixed singular lowers before cancellation
153 or termination.
154 """
155 if type(shift_singular_lowers) is not bool or (shift_singular_lowers and not meromorphic): 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true
156 raise ValueError("shift_singular_lowers requires a Boolean and meromorphic mode")
157 if excess_shift is not None and ( 157 ↛ 160line 157 didn't jump to line 160 because the condition on line 157 was never true
158 not meromorphic or type(excess_shift) is not int or excess_shift < 1
159 ):
160 raise ValueError("excess_shift requires meromorphic mode and a positive index")
161 if assumptions is None: 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true
162 assumptions = s.true
163 if not isinstance(expr, s.Expr) or not isinstance(epsilon, s.Symbol): 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true
164 raise TypeError("Expected a SymPy expression and regulator Symbol")
165 if not isinstance(assumptions, s.logic.boolalg.Boolean): 165 ↛ 166line 165 didn't jump to line 166 because the condition on line 165 was never true
166 raise TypeError("assumptions must be a SymPy Boolean")
167 if s.simplify(assumptions) is s.false:
168 raise UnsupportedExpressionError("Contradictory endpoint assumptions")
169 replacements = {}
170 for atom in expr.atoms(s.hyper):
171 upper = list(cast(tuple[s.Expr, ...], tuple(atom.ap)))
172 lower = list(cast(tuple[s.Expr, ...], tuple(atom.bq)))
173 argument = cast(s.Expr, atom.argument)
174 singular = [_fixed_nonpositive_integer(b, epsilon) for b in lower]
175 if any(singular):
176 if argument != 1 or not shift_singular_lowers:
177 raise UnsupportedExpressionError(
178 "Fixed nonpositive lower parameter has an ambiguous singular definition"
179 )
180 lower = [b + epsilon if fixed else b for b, fixed in zip(lower, singular, strict=True)]
181 for b in tuple(lower):
182 if b in upper:
183 upper.remove(b)
184 lower.remove(b)
185 reduced = s.hyper(upper, lower, argument, evaluate=False)
186 terminating = [u for u in upper if _fixed_nonpositive_integer(u, epsilon)]
187 if not terminating and argument != 1:
188 if reduced != atom:
189 replacements[atom] = reduced
190 continue
191 if atom.has(s.Float, s.oo, -s.oo, s.zoo, s.nan): 191 ↛ 192line 191 didn't jump to line 192 because the condition on line 191 was never true
192 raise UnsupportedExpressionError(
193 "Endpoint and terminating inputs must be exact and finite"
194 )
195 if terminating:
196 if any(not isinstance(u, s.Integer) for u in terminating): 196 ↛ 197line 196 didn't jump to line 197 because the condition on line 196 was never true
197 raise UnsupportedExpressionError("Termination degree must be an explicit integer")
198 degree = min(-int(u) for u in cast(list[s.Integer], terminating))
199 if degree > 4096: 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true
200 raise UnsupportedExpressionError(
201 "Terminating sum exceeds the supported 4096-degree budget"
202 )
203 replacements[atom] = s.Add(
204 *(
205 argument**n
206 * s.prod(s.rf(a, n) for a in upper)
207 / (s.factorial(n) * s.prod(s.rf(b, n) for b in lower))
208 for n in range(degree + 1)
209 )
210 )
211 continue
212 if excess_shift is not None and len(upper) == len(lower) + 1 and lower:
213 excess = s.expand(sum(lower) - sum(upper))
214 if _fixed_nonpositive_integer(excess, epsilon): 214 ↛ 227line 214 didn't jump to line 227 because the condition on line 214 was always true
215 if excess_shift > len(lower):
216 raise UnsupportedExpressionError(
217 "Unit excess shift index exceeds the reduced lower parameter count"
218 )
219 # Move transversely before any rank reduction or excess
220 # raising. Lower parameters follow SymPy's canonical order.
221 lower[excess_shift - 1] += epsilon
222 shifted = s.hyper(upper, lower, 1, evaluate=False)
223 replacements[atom] = rewrite_endpoints(
224 shifted, epsilon, assumptions, meromorphic=True
225 )
226 continue
227 if len(upper) == 1 and not lower:
228 # Binomial theorem at its convergent endpoint; often obtained by
229 # exact cancellation in a Gauss sum. This is not continuation.
230 if meromorphic or _convergent(-upper[0], epsilon, assumptions): 230 ↛ 233line 230 didn't jump to line 233 because the condition on line 230 was always true
231 replacements[atom] = s.S.Zero
232 continue
233 raise UnsupportedExpressionError("Binomial z=1 convergence is not proven")
234 if len(upper) != 2 or len(lower) != 1:
235 if convergent_unit(reduced, epsilon):
236 replacements[atom] = reduced
237 continue
238 if len(upper) == len(lower) + 1: 238 ↛ 253line 238 didn't jump to line 253 because the condition on line 238 was always true
239 from .matched_half import half_parameters
241 excess = s.expand(sum(lower) - sum(upper))
242 parsed = half_parameters(reduced, epsilon)
243 if parsed is not None and (
244 meromorphic or _convergent(excess, epsilon, assumptions)
245 ):
246 lowered = _reduce_unit_rank(upper, lower) if meromorphic else None
247 replacements[atom] = (
248 rewrite_endpoints(lowered, epsilon, assumptions, meromorphic=True)
249 if lowered is not None
250 else _continue_unit(upper, lower, excess, epsilon)
251 )
252 continue
253 raise UnsupportedExpressionError(
254 "Nonterminating z=1 requires supported parameters and proven positive excess"
255 )
256 a, b = upper
257 c = lower[0]
258 for parameter in (a, b, c):
259 _affine(parameter, epsilon)
260 excess = s.expand(c - a - b)
261 if meromorphic and _fixed_nonpositive_integer(excess, epsilon):
262 raise UnsupportedExpressionError("Gauss continuation lies on a fixed excess pole")
263 if not meromorphic and not _convergent(excess, epsilon, assumptions):
264 raise UnsupportedExpressionError(
265 "Gauss z=1 convergence is not proven on a regulator neighborhood or punctured side"
266 )
267 replacements[atom] = s.gamma(c) * s.gamma(excess) / (s.gamma(c - a) * s.gamma(c - b))
268 return cast(s.Expr, expr.xreplace(replacements))