Coverage for src/hypra/hpl/boundary_numeric.py: 87.50%
78 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"""Numerical real-cut boundary values from exact symbolic continuation maps."""
3from dataclasses import dataclass
5import mpmath as mp
6import sympy as s
8from .._typing import Boundary, ExactScalar, IntegerWord, RealRegion
9from ..errors import UnsupportedExpressionError
10from ..symbolic import HPL, MZV, EulerSum
11from .constants import evaluate_euler_sum, evaluate_mzv
12from .numeric import HPLNumericalConvergenceError, MPComplex, MPReal, _word, evaluate_hpl
13from .radial_continuation import _transport
14from .real_continuation import analytic_continue_hpl
17@dataclass(frozen=True)
18class HPLBoundaryNumericResult:
19 """Boundary value and non-certified precision diagnostics.
21 component_tail_bounds are individual interior-HPL series truncation bounds,
22 NOT a bound on the transformed result. For Taylor transport, tail_bound
23 instead bounds propagated truncation. Neither includes roundoff error.
24 """
26 value: MPComplex
27 stability_gap: MPReal
28 component_tail_bounds: tuple[MPReal, ...]
29 dps: int
30 working_dps: int
31 region: RealRegion
32 boundary: Boundary
33 method: str = "exact-real-boundary-map-to-interior"
34 path: str = "principal boundary limit; no extra winding"
35 tail_bound: MPReal | None = None
38def _point(argument, region):
39 if type(argument) is int:
40 argument = s.Integer(argument)
41 if (
42 not isinstance(argument, s.Expr)
43 or argument.free_symbols
44 or argument.has(s.Float)
45 or argument.is_real is not True
46 or argument.is_finite is not True
47 ):
48 raise UnsupportedExpressionError(
49 "Boundary argument must be an exact finite real SymPy number"
50 )
51 conditions = {
52 "0<x<1": (argument.is_positive, (1 - argument).is_positive),
53 "-1<x<0": ((-argument).is_positive, (argument + 1).is_positive),
54 "x>1": ((argument - 1).is_positive,),
55 "x<-1": ((-argument - 1).is_positive,),
56 }
57 if region not in conditions or any(test is not True for test in conditions[region]):
58 raise UnsupportedExpressionError(
59 "Exact argument does not satisfy the declared open real region"
60 )
61 return argument
64def _evaluate(expression, digits, max_terms):
65 ctx = mp.mp.clone()
66 ctx.dps = digits
67 replacements, tails = {}, []
68 for atom in expression.atoms(HPL):
69 result = evaluate_hpl(tuple(atom.word), atom.argument, dps=digits, max_terms=max_terms)
70 replacements[atom] = s.Float(ctx.nstr(result.value, n=digits), digits)
71 tails.append(result.tail_bound)
72 for atom in expression.atoms(EulerSum, MZV): 72 ↛ 73line 72 didn't jump to line 73 because the loop on line 72 never started
73 result = (
74 evaluate_euler_sum(atom.indices, atom.colors, dps=digits, max_terms=max_terms)
75 if isinstance(atom, EulerSum)
76 else evaluate_mzv(atom.indices, dps=digits, max_terms=max_terms)
77 )
78 replacements[atom] = s.Float(ctx.nstr(result.value, n=digits), digits)
79 result = expression.xreplace(replacements).evalf(digits)
80 if ( 80 ↛ 86line 80 didn't jump to line 86 because the condition on line 80 was never true
81 result.has(HPL, EulerSum, MZV)
82 or result.free_symbols
83 or result.is_number is not True
84 or result.is_finite is not True
85 ):
86 raise UnsupportedExpressionError(
87 "Boundary transformation left an unevaluated numerical expression"
88 )
89 real, imag = result.as_real_imag()
90 return ctx.mpc(str(real.evalf(digits)), str(imag.evalf(digits))), tuple(tails)
93def _boundary_transport(word, argument, region, boundary, dps, max_terms):
94 """Continue along a finite detour ending exactly on the specified cut.
96 Starting at 1/4, the three-segment path lies in the chosen open half
97 plane until it reaches the target. It avoids 0, +/-1 and is homotopic
98 to the requested principal boundary approach. The target has no small
99 imaginary displacement. Interior real targets use a straight segment.
100 """
101 initial = s.Rational(1, 4)
102 if region == "0<x<1":
103 targets = [argument]
104 else:
105 height = s.I / 2 if boundary == "upper" else -s.I / 2
106 targets = [initial + height, argument + height, argument]
107 first = _transport(word, initial, targets, dps, dps + 25, 4096, 4096, max_terms)
108 second = _transport(word, initial, targets, dps, dps + 45, 4096, 4096, max_terms)
109 ctx = mp.mp.clone()
110 ctx.dps = dps + 45
111 gap = abs(ctx.mpc(first[0]) - ctx.mpc(second[0]))
112 if gap > ctx.power(10, -dps - 4) * max(ctx.one, abs(second[0])): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true
113 raise HPLNumericalConvergenceError(
114 "Boundary transport unstable under increased working precision"
115 )
116 return HPLBoundaryNumericResult(
117 ctx.mpc(second[0]),
118 gap,
119 (),
120 dps,
121 dps + 45,
122 region,
123 boundary,
124 method="triangular-suffix-ODE-Taylor-boundary",
125 path=(
126 "real interior straight path"
127 if region == "0<x<1"
128 else "principal boundary limit via finite half-plane detour; no extra winding"
129 ),
130 tail_bound=second[1],
131 )
134def evaluate_hpl_boundary(
135 word: IntegerWord,
136 argument: ExactScalar,
137 *,
138 region: RealRegion,
139 boundary: Boundary,
140 dps: int = 50,
141 max_terms: int = 100000,
142) -> HPLBoundaryNumericResult:
143 """Evaluate H_word(x +/- i0) by exact maps, never a tiny imaginary offset.
145 Both region and boundary are mandatory. Regions: '0<x<1', '-1<x<0',
146 'x>1', 'x<-1'. Boundaries: 'upper' (+i0), 'lower' (-i0). The real
147 argument must satisfy the declared open region exactly. Singular endpoints
148 and extra winding paths are excluded. All ternary words through weight
149 24 are supported. Above weight six, a finite
150 half-plane detour transports the defining ODE to the exact real target.
151 Taylor transport also supplies a fallback if interior series do not
152 converge within their term budget.
154 The reported component bounds cover interior series tails individually,
155 not propagation/cancellation/roundoff in the final boundary value. For
156 Taylor transport, tail_bound gives the propagated truncation bound.
157 Two guarded precision calculations must agree; this is not interval proof.
159 Args:
160 word: Expanded HPL letters.
161 argument: Exact finite real point in the declared region.
162 region: Open real interval containing the argument.
163 boundary: Side of approach to the real axis.
164 dps: Requested decimal precision, from 2 to 800.
165 max_terms: Maximum terms per interior HPL series.
167 Returns:
168 Boundary value with stability and component truncation diagnostics.
169 """
170 if type(dps) is not int or not 2 <= dps <= 800: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true
171 raise ValueError("dps must be an integer between 2 and 800")
172 if type(max_terms) is not int or not 1 <= max_terms <= 1000000: 172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true
173 raise ValueError("max_terms must be an integer between 1 and 1000000")
174 argument = _point(argument, region)
175 word = _word(word)
176 if boundary not in ("upper", "lower"):
177 raise UnsupportedExpressionError("Continuation boundary must be 'upper' or 'lower'")
178 if len(word) > 6 and region in ("x>1", "x<-1"):
179 return _boundary_transport(word, argument, region, boundary, dps, max_terms)
180 x = s.Symbol("boundary_argument", real=True)
181 expression = analytic_continue_hpl(word, x, region=region, boundary=boundary).subs(x, argument)
182 try:
183 first, _ = _evaluate(expression, dps + 20, max_terms)
184 second, tails = _evaluate(expression, dps + 40, max_terms)
185 except HPLNumericalConvergenceError:
186 return _boundary_transport(word, argument, region, boundary, dps, max_terms)
187 ctx = mp.mp.clone()
188 ctx.dps = dps + 40
189 gap = abs(ctx.convert(first) - ctx.convert(second))
190 if gap > ctx.power(10, -dps - 4) * max(ctx.one, abs(second)): 190 ↛ 191line 190 didn't jump to line 191 because the condition on line 190 was never true
191 raise HPLNumericalConvergenceError(
192 "Boundary value unstable under increased working precision"
193 )
194 return HPLBoundaryNumericResult(second, gap, tails, dps, dps + 40, region, boundary)