Coverage for src/hypra/native/contiguous.py: 82.54%
237 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"""Generic exact contiguous shifts of pF(p-1) canonical regulator expansions.
3Let L=A(theta)-z B(theta), A=theta*prod(theta+b-1), B=prod(theta+a).
4The inverse shifts follow by polynomial division, not an inverse differential
5operator with an unspecified integration constant. At a coefficient z**n they
6multiply by (a-1)/(n+a-1) or b/(n+b), respectively.
8All epsilon orders are propagated coefficientwise. An identically zero shift
9divisor is regularized by ONE formal slope perturbation with distinct nonzero
10integer weights, cancelled exactly and taken to zero algebraically. No numeric
11parameter limit or fixed singular lower parameter is accepted.
12"""
14from __future__ import annotations
16from collections.abc import Callable
17from dataclasses import dataclass
18from typing import cast
20import sympy as s
21from sympy.logic.boolalg import Boolean
23from ..errors import IncompleteExpansionError, UnsupportedExpressionError
24from ..symbolic import HPL
26_MAX_SHIFTS = 24
27_MAX_PARAMETERS = 8
28_MAX_DEPTH = 24
29_MAX_TERMS = 50000
32@dataclass(frozen=True)
33class ShiftStep:
34 kind: str
35 index: int
36 upper_bases: tuple
37 lower_bases: tuple
38 order_loss: int
41@dataclass(frozen=True)
42class ContiguousPlan:
43 steps: tuple[ShiftStep, ...]
44 extra_order: int
45 perturbation_used: bool
46 pole_bound: int
49def _rational(value):
50 if isinstance(value, bool) or not isinstance(value, (int, s.Rational)): 50 ↛ 51line 50 didn't jump to line 51 because the condition on line 50 was never true
51 raise UnsupportedExpressionError("Contiguous bases must be exact rationals")
52 return s.Rational(value)
55def _parameters(upper_pairs, lower_pairs, canonical_upper_bases, canonical_lower_bases):
56 from .nested_sums import _slope
58 try:
59 upper = tuple((_rational(base), _slope(slope)) for base, slope in upper_pairs)
60 lower = tuple((_rational(base), _slope(slope)) for base, slope in lower_pairs)
61 canonical_upper = tuple(map(_rational, canonical_upper_bases))
62 canonical_lower = tuple(map(_rational, canonical_lower_bases))
63 except (TypeError, ValueError) as exc:
64 if isinstance(exc, UnsupportedExpressionError):
65 raise
66 raise UnsupportedExpressionError("Parameters must be (base, slope) pairs") from exc
67 if not 2 <= len(upper) <= _MAX_PARAMETERS or len(upper) != len(lower) + 1: 67 ↛ 68line 67 didn't jump to line 68 because the condition on line 67 was never true
68 raise UnsupportedExpressionError("Contiguous engine requires 2 <= p <= 8 and pF(p-1)")
69 if len(canonical_upper) != len(upper) or len(canonical_lower) != len(lower): 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 raise UnsupportedExpressionError("Canonical and target parameter counts must match")
71 if any( 71 ↛ 75line 71 didn't jump to line 75 because the condition on line 71 was never true
72 not (target - base).is_Integer
73 for (target, _), base in zip(upper + lower, canonical_upper + canonical_lower, strict=True)
74 ):
75 raise UnsupportedExpressionError("Contiguous shifts must be integral")
76 if any(base.is_Integer and base <= 0 and slope == 0 for base, slope in lower):
77 raise UnsupportedExpressionError("Fixed singular lower parameter")
78 if any(base.is_Integer and base <= 0 for base in canonical_lower): 78 ↛ 79line 78 didn't jump to line 79 because the condition on line 78 was never true
79 raise UnsupportedExpressionError("Canonical lower bases must be regular at epsilon=0")
80 return upper, lower, canonical_upper, canonical_lower
83def _divisor_factors(kind, index, upper_bases, lower_bases, upper_slopes, lower_slopes):
84 if kind == "upper_up":
85 return ((upper_bases[index], upper_slopes[index]),)
86 if kind == "upper_down":
87 return tuple(
88 (base - upper_bases[index], slope - upper_slopes[index])
89 for base, slope in zip(lower_bases, lower_slopes, strict=True)
90 )
91 if kind == "lower_down":
92 return ((lower_bases[index] - 1, lower_slopes[index]),)
93 return tuple(
94 (base - lower_bases[index], slope - lower_slopes[index])
95 for base, slope in zip(upper_bases, upper_slopes, strict=True)
96 )
99def plan_contiguous(
100 upper_pairs, lower_pairs, canonical_upper_bases, canonical_lower_bases
101) -> ContiguousPlan:
102 """Plan shifts and their exact canonical-order budget without building a series."""
103 upper, lower, upper_bases, lower_bases = _parameters(
104 upper_pairs, lower_pairs, canonical_upper_bases, canonical_lower_bases
105 )
106 current_upper: list[s.Expr] = list(upper_bases)
107 current_lower: list[s.Expr] = list(lower_bases)
108 upper_slopes = tuple(slope for _, slope in upper)
109 lower_slopes = tuple(slope for _, slope in lower)
110 total_shifts = sum(
111 abs(int(target - base))
112 for (target, _), base in zip(
113 upper + lower, tuple(current_upper) + tuple(current_lower), strict=True
114 )
115 )
116 if total_shifts > _MAX_SHIFTS:
117 raise UnsupportedExpressionError(f"Contiguous shift count exceeds {_MAX_SHIFTS}")
118 steps = []
119 perturbation = False
120 for family, targets, bases in (
121 ("upper", upper, current_upper),
122 ("lower", lower, current_lower),
123 ):
124 for index, (target, _) in enumerate(targets):
125 while bases[index] != target:
126 direction = 1 if bases[index] < target else -1
127 kind = family + ("_up" if direction == 1 else "_down")
128 factors = _divisor_factors(
129 kind, index, current_upper, current_lower, upper_slopes, lower_slopes
130 )
131 loss = sum(1 for base, _ in factors if base == 0)
132 perturbation |= any(base == 0 and slope == 0 for base, slope in factors)
133 steps.append(
134 ShiftStep(kind, index, tuple(current_upper), tuple(current_lower), loss)
135 )
136 bases[index] += direction
137 extra_order = sum(step.order_loss for step in steps)
138 if extra_order > _MAX_DEPTH: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true
139 raise UnsupportedExpressionError(f"Contiguous extra-order budget exceeds {_MAX_DEPTH}")
140 return ContiguousPlan(
141 tuple(steps),
142 extra_order,
143 perturbation,
144 sum(1 for base, _ in lower if base.is_Integer and base <= 0),
145 )
148def _operator(step, upper_slopes, lower_slopes, z, epsilon):
149 x = s.Dummy("theta")
150 upper = [
151 base + slope * epsilon for base, slope in zip(step.upper_bases, upper_slopes, strict=True)
152 ]
153 lower = [
154 base + slope * epsilon for base, slope in zip(step.lower_bases, lower_slopes, strict=True)
155 ]
156 if step.kind == "upper_up":
157 a = upper[step.index]
158 operator = (x + a) / a
159 elif step.kind == "upper_down":
160 a = upper[step.index]
161 A = s.Poly(x * s.prod(x + b - 1 for b in lower), x, domain="EX")
162 quotient, _ = s.div(A, s.Poly(x + a - 1, x, domain="EX"))
163 other_upper = s.prod(x + b for index, b in enumerate(upper) if index != step.index)
164 operator = (quotient.as_expr() - z * other_upper) / s.prod(b - a for b in lower)
165 elif step.kind == "lower_down":
166 b = lower[step.index]
167 operator = (x + b - 1) / (b - 1)
168 else:
169 b = lower[step.index]
170 B = s.Poly(s.prod(x + a for a in upper), x, domain="EX")
171 quotient, _ = s.div(B, s.Poly(x + b, x, domain="EX"))
172 other_lower = x * s.prod(x + a - 1 for index, a in enumerate(lower) if index != step.index)
173 operator = b * (other_lower - z * quotient.as_expr()) / (z * s.prod(a - b for a in upper))
174 return tuple(
175 (degree[0], s.cancel(coefficient))
176 for degree, coefficient in s.Poly(s.expand(operator), x, domain="EX").terms()
177 )
180def _rational_laurent(expression, epsilon, through):
181 """Exact regulator Laurent division of an operator's rational coefficient."""
182 expression = s.cancel(expression)
183 if expression == 0: 183 ↛ 184line 183 didn't jump to line 184 because the condition on line 183 was never true
184 return {}
185 if not expression.is_rational_function(epsilon): 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true
186 raise UnsupportedExpressionError(
187 "Contiguous operator coefficient is not rational in epsilon"
188 )
189 numerator, denominator = s.fraction(expression)
190 numerator, denominator = (
191 s.Poly(numerator, epsilon, domain="EX"),
192 s.Poly(denominator, epsilon, domain="EX"),
193 )
194 nv = min(power[0] for power, coefficient in numerator.terms() if coefficient != 0)
195 dv = min(power[0] for power, coefficient in denominator.terms() if coefficient != 0)
196 valuation = nv - dv
197 coefficients = []
198 for degree in range(max(0, through - valuation + 1)):
199 previous = sum(
200 denominator.nth(dv + j) * coefficients[degree - j] for j in range(1, degree + 1)
201 )
202 coefficients.append(s.cancel((numerator.nth(nv + degree) - previous) / denominator.nth(dv)))
203 return {
204 valuation + degree: coefficient
205 for degree, coefficient in enumerate(coefficients)
206 if coefficient != 0
207 }
210def _coefficients(expression, epsilon, through):
211 if not isinstance(expression, s.Expr) or expression.has( 211 ↛ 214line 211 didn't jump to line 214 because the condition on line 211 was never true
212 s.Order, s.Float, s.nan, s.zoo, s.oo, -s.oo
213 ):
214 raise IncompleteExpansionError(
215 "Canonical builder must return an exact finite Laurent polynomial"
216 )
217 result = {}
218 for term in s.Add.make_args(s.expand(expression, log=False, power_base=False, power_exp=False)):
219 coefficient, power = term.as_coeff_exponent(epsilon)
220 if not power.is_Integer or coefficient.has(epsilon): 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true
221 raise IncompleteExpansionError("Canonical builder left unresolved regulator dependence")
222 if power < 0: 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 raise IncompleteExpansionError(
224 "Canonical regular lower bases unexpectedly produced regulator poles"
225 )
226 if power <= through: 226 ↛ 218line 226 didn't jump to line 218 because the condition on line 226 was always true
227 result[int(power)] = result.get(int(power), s.S.Zero) + coefficient
228 return {
229 power: s.expand(coefficient) for power, coefficient in result.items() if coefficient != 0
230 }
233def _hpl_pieces(expression):
234 """Collect HPL atoms before rational cancellation to avoid denominator swell."""
235 expression = s.expand(expression, log=False, power_base=False, power_exp=False)
236 atoms = sorted(expression.atoms(HPL), key=s.default_sort_key)
237 return (
238 s.collect(expression, atoms, evaluate=False, exact=True) if atoms else {s.S.One: expression}
239 )
242def _normalize_coefficient(expression):
243 return s.Add(
244 *(s.cancel(coefficient) * word for word, coefficient in _hpl_pieces(expression).items())
245 )
248def _finite_delta_limit(expression, delta):
249 """Exact removable limit, with no numeric extrapolation or arbitrary path."""
250 expression = s.cancel(expression)
251 if expression == 0 or not expression.has(delta):
252 return expression
253 if expression.is_rational_function(delta) is not True: 253 ↛ 254line 253 didn't jump to line 254 because the condition on line 253 was never true
254 raise UnsupportedExpressionError("Slope limit is not an exact rational expression")
255 numerator, denominator = s.fraction(expression)
256 numerator, denominator = (
257 s.Poly(numerator, delta, domain="EX"),
258 s.Poly(denominator, delta, domain="EX"),
259 )
260 nterms = [(power[0], s.simplify(coefficient)) for power, coefficient in numerator.terms()]
261 dterms = [(power[0], s.simplify(coefficient)) for power, coefficient in denominator.terms()]
262 nterms = [(power, coefficient) for power, coefficient in nterms if coefficient != 0]
263 dterms = [(power, coefficient) for power, coefficient in dterms if coefficient != 0]
264 if not nterms: 264 ↛ 265line 264 didn't jump to line 265 because the condition on line 264 was never true
265 return s.S.Zero
266 if not dterms: 266 ↛ 267line 266 didn't jump to line 267 because the condition on line 266 was never true
267 raise UnsupportedExpressionError(
268 "Slope perturbation produced an identically zero denominator"
269 )
270 nv, nc = min(nterms)
271 dv, dc = min(dterms)
272 if nv < dv: 272 ↛ 273line 272 didn't jump to line 273 because the condition on line 272 was never true
273 raise UnsupportedExpressionError("Degenerate contiguous slope limit did not cancel exactly")
274 return s.cancel(nc / dc) if nv == dv else s.S.Zero
277def expand_contiguous(
278 upper_pairs,
279 lower_pairs,
280 canonical_upper_bases,
281 canonical_lower_bases,
282 z: s.Symbol,
283 epsilon: s.Symbol,
284 through: int,
285 canonical_builder: Callable,
286 *,
287 max_internal_order: int = _MAX_DEPTH,
288 assumptions: Boolean = s.true,
289) -> s.Expr:
290 """Shift a canonical pF(p-1) expansion to exact rational target parameters.
292 Each parameter is ``(base, slope)`` for base+slope*epsilon. Canonical bases
293 must differ by integers from the targets and have regular lower parameters.
294 The callback is
296 canonical_builder((upper_bases, lower_bases), (upper_slopes, lower_slopes),
297 z, epsilon, inclusive_depth)
299 and must return its complete exact polynomial through that depth. Slopes
300 are exact polynomials in independent formal symbols; a zero divisor may
301 require one additional polynomial delta. Moving singular lower slopes must be
302 provably nonzero under assumptions. Multiplication by their product must
303 clear all final slope denominators; unexplained parameter poles fail.
304 The result has no Order term; the caller owns external prefactors and final
305 expansion provenance. ``plan_contiguous`` exposes the required extra depth.
306 """
307 if not isinstance(z, s.Symbol) or not isinstance(epsilon, s.Symbol) or z == epsilon: 307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true
308 raise TypeError("Use distinct symbolic argument and regulator variables")
309 if type(through) is not int or through < 0: 309 ↛ 310line 309 didn't jump to line 310 because the condition on line 309 was never true
310 raise ValueError("through must be a nonnegative inclusive integer order")
311 if type(max_internal_order) is not int or not 0 <= max_internal_order <= _MAX_DEPTH: 311 ↛ 312line 311 didn't jump to line 312 because the condition on line 311 was never true
312 raise ValueError(f"max_internal_order must be between 0 and {_MAX_DEPTH}")
313 upper, lower, canonical_upper, canonical_lower = _parameters(
314 upper_pairs, lower_pairs, canonical_upper_bases, canonical_lower_bases
315 )
316 plan = plan_contiguous(upper, lower, canonical_upper, canonical_lower)
317 depth = through + plan.extra_order
318 if depth > max_internal_order:
319 raise UnsupportedExpressionError(
320 f"Canonical depth {depth} exceeds contiguous limit {max_internal_order}"
321 )
322 slope_symbols = set().union(*(slope.free_symbols for _, slope in upper + lower))
323 if {z, epsilon} & slope_symbols: 323 ↛ 324line 323 didn't jump to line 324 because the condition on line 323 was never true
324 raise UnsupportedExpressionError("Slopes must be independent of argument and regulator")
325 from .planning import _ask, _facts
327 singular_slopes = [slope for base, slope in lower if base.is_Integer and base <= 0]
328 for slope in singular_slopes:
329 if _ask(s.Q.nonzero(slope), _facts(assumptions)) is not True:
330 raise UnsupportedExpressionError("Moving lower pole slope must be provably nonzero")
331 source_denominator = s.prod(singular_slopes)
332 delta_name = "_hypra_slope_delta"
333 while delta_name in { 333 ↛ 336line 333 didn't jump to line 336 because the condition on line 333 was never true
334 symbol.name for symbol in cast(set[s.Symbol], slope_symbols | {z, epsilon})
335 }:
336 delta_name += "_"
337 delta = s.Symbol(delta_name)
338 slopes = tuple(slope for _, slope in upper + lower)
339 if plan.perturbation_used:
340 slopes = tuple(slope + (index + 1) * delta for index, slope in enumerate(slopes))
341 upper_slopes, lower_slopes = slopes[: len(upper)], slopes[len(upper) :]
342 expression = canonical_builder(
343 (canonical_upper, canonical_lower), (upper_slopes, lower_slopes), z, epsilon, depth
344 )
345 state = _coefficients(expression, epsilon, depth)
346 for step in plan.steps:
347 next_depth = depth - step.order_loss
348 if not state: 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true
349 return s.S.Zero
350 lower_power = min(state)
351 operator = _operator(step, upper_slopes, lower_slopes, z, epsilon)
352 max_derivative = max(degree for degree, _ in operator)
353 derivatives = {0: state}
354 for degree in range(1, max_derivative + 1):
355 derivatives[degree] = {
356 power: z * s.diff(value, z) for power, value in derivatives[degree - 1].items()
357 }
358 next_state = {}
359 for degree, rational in operator:
360 rational_series = _rational_laurent(rational, epsilon, next_depth - lower_power)
361 for left_power, left_coefficient in rational_series.items():
362 for right_power, right_coefficient in derivatives[degree].items():
363 power = left_power + right_power
364 if power <= next_depth:
365 next_state[power] = (
366 next_state.get(power, s.S.Zero) + left_coefficient * right_coefficient
367 )
368 state = {}
369 for power, coefficient in next_state.items():
370 coefficient = _normalize_coefficient(coefficient)
371 if len(s.Add.make_args(coefficient)) > _MAX_TERMS: 371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true
372 raise UnsupportedExpressionError(
373 "Contiguous coefficient exceeds the supported term budget"
374 )
375 if coefficient != 0:
376 state[power] = coefficient
377 depth = next_depth
378 result = s.S.Zero
379 for power, coefficient in state.items():
380 coefficient = _normalize_coefficient(coefficient)
381 if plan.perturbation_used:
382 coefficient = s.Add(
383 *(
384 _finite_delta_limit(value, delta) * word
385 for word, value in _hpl_pieces(coefficient).items()
386 )
387 )
388 if slope_symbols:
389 for value in _hpl_pieces(coefficient).values():
390 if s.cancel(source_denominator * value).is_polynomial(*slope_symbols) is not True: 390 ↛ 391line 390 didn't jump to line 391 because the condition on line 390 was never true
391 raise IncompleteExpansionError("Uncanceled symbolic slope denominator")
392 if coefficient.has(delta, s.nan, s.zoo, s.oo, -s.oo, epsilon): 392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true
393 raise IncompleteExpansionError(
394 "Contiguous result retained invalid or unresolved parameters"
395 )
396 if power < -plan.pole_bound: 396 ↛ 397line 396 didn't jump to line 397 because the condition on line 396 was never true
397 if s.simplify(coefficient) != 0:
398 raise IncompleteExpansionError(
399 "Apparent contiguous regulator poles failed to cancel"
400 )
401 continue
402 if power <= through: 402 ↛ 379line 402 didn't jump to line 379 because the condition on line 402 was always true
403 result += coefficient * epsilon**power
404 return result