Coverage for src/hypra/hpl/radial_continuation.py: 87.14%
102 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"""Explicit radial numerical HPL continuation by bounded Taylor ODE steps.
3The mathematical truncation bound excludes floating-point roundoff. A second
4higher-precision run is a stability check, not an interval certificate.
5"""
7from dataclasses import dataclass
8from typing import Literal
10import mpmath as mp
11import sympy as s
13from .._typing import IntegerWord
14from ..errors import UnsupportedExpressionError
15from .numeric import (
16 _DECIMAL,
17 HPLNumericalConvergenceError,
18 MPReal,
19 NumericArgument,
20 NumericValue,
21 _word,
22 evaluate_hpl,
23)
26@dataclass(frozen=True)
27class HPLContinuationResult:
28 """Numerical radial continuation and its truncation and precision diagnostics."""
30 value: NumericValue
31 tail_bound: MPReal
32 stability_gap: MPReal
33 steps: int
34 max_degree: int
35 dps: int
36 working_dps: int
37 method: str = "triangular-suffix-ODE-Taylor"
38 domain: str = "principal branch off real cuts; straight radial path from origin germ"
41def _target(value, ctx):
42 if isinstance(value, bool): 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true
43 raise TypeError("A boolean is not a numerical argument")
44 if isinstance(value, s.Expr):
45 if value.free_symbols or value.is_finite is not True: 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true
46 raise UnsupportedExpressionError("Use a finite numerical argument")
47 real, imag = value.as_real_imag()
48 z = ctx.mpc(str(s.N(real, ctx.dps + 10)), str(s.N(imag, ctx.dps + 10)))
49 elif isinstance(value, str): 49 ↛ 50line 49 didn't jump to line 50 because the condition on line 49 was never true
50 if len(value) > 4096 or not _DECIMAL.fullmatch(value):
51 raise ValueError("Use a decimal string, not executable text")
52 z = ctx.mpc(value)
53 else:
54 try:
55 z = ctx.mpc(value)
56 except (TypeError, ValueError) as exc:
57 raise TypeError("Use an exact SymPy number or a numerical scalar") from exc
58 if not ctx.isfinite(z) or z == 0 or (ctx.im(z) == 0 and not 0 < ctx.re(z) < 1):
59 raise UnsupportedExpressionError(
60 "Radial continuation excludes zero, endpoints and real cuts (-infinity,0] and [1,infinity)"
61 )
62 return z
65def _transport(word, initial, targets, dps, working, max_steps, max_degree, max_terms):
66 """Transport the suffix ODE along nonsingular segments supplied by the caller.
68 The initial point must be in the principal slit disk. This internal helper
69 does not select a branch: its caller supplies a path with the required
70 homotopy. Each step stays in a disk excluding all three kernel poles.
71 """
72 ctx = mp.mp.clone()
73 ctx.dps = working
75 def point(value):
76 real, imag = value.as_real_imag()
77 return ctx.mpc(str(s.N(real, working + 10)), str(s.N(imag, working + 10)))
79 c = point(initial)
80 values = []
81 error = ctx.zero
82 for j in range(len(word)):
83 evaluated = evaluate_hpl(
84 word[j:], initial, dps=working, max_terms=max_terms, domain="principal-disk"
85 )
86 values.append(ctx.mpc(evaluated.value))
87 error = max(error, ctx.mpf(evaluated.tail_bound))
88 values.append(ctx.one)
89 steps = degree_used = 0
90 local_tolerance = ctx.power(10, -dps - 15) / max_steps
91 for endpoint in targets:
92 target = point(endpoint)
93 while c != target:
94 if steps >= max_steps:
95 raise HPLNumericalConvergenceError("HPL continuation exceeded max_steps")
96 distance = min(abs(c), abs(c - 1), abs(c + 1))
97 h = target - c
98 if abs(h) > distance / 4:
99 h = h * (distance / (4 * abs(h)))
100 radius = distance / 2
101 ratio = abs(h) / radius
102 majorant = max(map(abs, values)) * ctx.exp(radius / (distance - radius))
103 degree = max(
104 1,
105 int(ctx.ceil(ctx.log(local_tolerance * (1 - ratio) / majorant) / ctx.log(ratio)))
106 - 1,
107 )
108 if degree > max_degree:
109 raise HPLNumericalConvergenceError("HPL continuation exceeded max_degree")
110 coefficients = [[v] + [ctx.zero] * degree for v in values]
111 for j in range(len(word) - 1, -1, -1):
112 letter = word[j]
113 denominator = c if letter == 0 else (1 - c if letter == 1 else 1 + c)
114 sign = 1 if letter == 1 else -1
115 # Kernel Taylor coefficients form a geometric sequence. Its
116 # convolution with the suffix series obeys this first-order
117 # recurrence, costing O(degree), not O(degree**2).
118 convolution = ctx.zero
119 for n in range(degree):
120 convolution = (coefficients[j + 1][n] + sign * convolution) / denominator
121 coefficients[j][n + 1] = convolution / (n + 1)
122 values = [ctx.polyval(list(reversed(row)), h) for row in coefficients]
123 local_error = majorant * ratio ** (degree + 1) / (1 - ratio)
124 error = error * ctx.exp(abs(h) / (distance - abs(h))) + local_error
125 c = target if h == target - c else c + h
126 steps += 1
127 degree_used = max(degree_used, degree)
128 if error > ctx.power(10, -dps) * max(ctx.one, abs(values[0])): 128 ↛ 129line 128 didn't jump to line 129 because the condition on line 128 was never true
129 raise HPLNumericalConvergenceError(
130 "Propagated truncation bound exceeds requested tolerance"
131 )
132 return values[0], error, steps, degree_used
135def _run(word, argument, dps, working, max_steps, max_degree, max_terms):
136 ctx = mp.mp.clone()
137 ctx.dps = working
138 target = _target(argument, ctx)
139 c = target * min(ctx.one, ctx.mpf("0.25") / abs(target))
140 # Exact decimal data avoids cross-context mpc type/coercion limitations.
141 initial = s.Rational(str(ctx.re(c))) + s.I * s.Rational(str(ctx.im(c)))
142 endpoint = s.Rational(str(ctx.re(target))) + s.I * s.Rational(str(ctx.im(target)))
143 return _transport(word, initial, [endpoint], dps, working, max_steps, max_degree, max_terms)
146def continue_hpl(
147 word: IntegerWord,
148 argument: NumericArgument,
149 *,
150 domain: Literal["principal-cut-plane"],
151 path: Literal["radial"],
152 dps: int = 50,
153 max_steps: int = 4096,
154 max_degree: int = 1024,
155 max_terms: int = 100000,
156) -> HPLContinuationResult:
157 """Numerically continue along an explicitly requested principal radial path.
159 Required choices: domain='principal-cut-plane', path='radial'. Real input
160 is permitted only between zero and one. Complex paths must be off the real
161 cuts. No boundary value, winding path or exact symbolic identity is inferred.
163 Args:
164 word: Expanded HPL letters, up to weight 24.
165 argument: Finite target point off the cuts.
166 domain: Principal cut plane.
167 path: Straight radial continuation from the origin germ.
168 dps: Requested decimal precision.
169 max_steps: Maximum number of Taylor continuation steps.
170 max_degree: Highest Taylor degree allowed in each step.
171 max_terms: Maximum terms in each initial interior HPL series.
173 Returns:
174 Approximation with propagated truncation bound and precision diagnostics.
175 """
176 if domain != "principal-cut-plane" or path != "radial":
177 raise UnsupportedExpressionError(
178 'Specify domain="principal-cut-plane", path="radial" explicitly'
179 )
180 word = _word(word)
181 for name, value, upper in [
182 ("dps", dps, 500),
183 ("max_steps", max_steps, 100000),
184 ("max_degree", max_degree, 4096),
185 ("max_terms", max_terms, 1000000),
186 ]:
187 if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= upper: 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was never true
188 raise ValueError(f"{name} must be an integer between 1 and {upper}")
189 first = _run(word, argument, dps, dps + 25, max_steps, max_degree, max_terms)
190 second = _run(word, argument, dps, dps + 45, max_steps, max_degree, max_terms)
191 ctx = mp.mp.clone()
192 ctx.dps = dps + 45
193 gap = abs(ctx.mpc(first[0]) - ctx.mpc(second[0]))
194 if gap > ctx.power(10, -dps) * max(ctx.one, abs(second[0])): 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true
195 raise HPLNumericalConvergenceError("Higher-precision continuation did not stabilize")
196 return HPLContinuationResult(second[0], second[1], gap, second[2], second[3], dps, dps + 45)