hypra 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hypra/__init__.py +163 -0
- hypra/__main__.py +6 -0
- hypra/_json.py +21 -0
- hypra/_typing.py +21 -0
- hypra/api.py +328 -0
- hypra/backend.py +321 -0
- hypra/cli/__init__.py +6 -0
- hypra/cli/application.py +45 -0
- hypra/cli/commands.py +96 -0
- hypra/cli/request.py +35 -0
- hypra/config.py +82 -0
- hypra/errors.py +13 -0
- hypra/hpl/__init__.py +1 -0
- hypra/hpl/algebra.py +459 -0
- hypra/hpl/alternating.py +105 -0
- hypra/hpl/arguments.py +79 -0
- hypra/hpl/boundary_numeric.py +139 -0
- hypra/hpl/classical.py +151 -0
- hypra/hpl/constants.py +171 -0
- hypra/hpl/endpoints.py +171 -0
- hypra/hpl/inversion.py +62 -0
- hypra/hpl/limits.py +105 -0
- hypra/hpl/maps.py +98 -0
- hypra/hpl/mobius.py +56 -0
- hypra/hpl/named_constants.py +50 -0
- hypra/hpl/notation.py +129 -0
- hypra/hpl/numeric.py +303 -0
- hypra/hpl/radial_continuation.py +173 -0
- hypra/hpl/real_continuation.py +75 -0
- hypra/hpl/reduction.py +140 -0
- hypra/hpl/regularization.py +171 -0
- hypra/hpl/series_one.py +67 -0
- hypra/hpl/special.py +49 -0
- hypra/hpl/stuffle.py +106 -0
- hypra/hpl/taylor.py +55 -0
- hypra/hpl/transforms.py +95 -0
- hypra/hypexp_integrals.py +201 -0
- hypra/native/__init__.py +6 -0
- hypra/native/atom.py +220 -0
- hypra/native/backend.py +292 -0
- hypra/native/canonical.py +55 -0
- hypra/native/colored_sums.py +275 -0
- hypra/native/contiguous.py +404 -0
- hypra/native/endpoints.py +263 -0
- hypra/native/half_system.py +148 -0
- hypra/native/integer.py +189 -0
- hypra/native/matched_half.py +127 -0
- hypra/native/nested_sums.py +281 -0
- hypra/native/planning.py +265 -0
- hypra/native/twof1_shift.py +130 -0
- hypra/native/unit_limit.py +119 -0
- hypra/native/worker.py +69 -0
- hypra/nielsen.py +153 -0
- hypra/py.typed +0 -0
- hypra/serialization.py +302 -0
- hypra/symbolic.py +451 -0
- hypra/wolfram_bridge.wls +171 -0
- hypra-0.2.0.dist-info/METADATA +224 -0
- hypra-0.2.0.dist-info/RECORD +61 -0
- hypra-0.2.0.dist-info/WHEEL +4 -0
- hypra-0.2.0.dist-info/entry_points.txt +2 -0
hypra/__init__.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Hypra: a SymPy-native hypergeometric expansion project.
|
|
2
|
+
|
|
3
|
+
Native exact regulator expansions inspired by HypExp; no Mathematica required.
|
|
4
|
+
An experimental external comparison bridge is optional.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from typing import cast
|
|
9
|
+
|
|
10
|
+
from sympy import hyper
|
|
11
|
+
|
|
12
|
+
from ._typing import ExactScalar
|
|
13
|
+
from .api import ExpansionResult, backend_info, expand_epsilon
|
|
14
|
+
from .backend import (
|
|
15
|
+
BackendError,
|
|
16
|
+
BackendProtocolError,
|
|
17
|
+
BackendTimeoutError,
|
|
18
|
+
BackendUnavailableError,
|
|
19
|
+
)
|
|
20
|
+
from .config import BackendConfig
|
|
21
|
+
from .errors import HypraError, IncompleteExpansionError, UnsupportedExpressionError
|
|
22
|
+
from .hpl.algebra import hpl_series, integrate_from_zero, primitive_hpl, shuffle_expand
|
|
23
|
+
from .hpl.alternating import hpl_alternating_at_one, reduce_euler_sum
|
|
24
|
+
from .hpl.arguments import transform_hpl_arguments
|
|
25
|
+
from .hpl.boundary_numeric import HPLBoundaryNumericResult, evaluate_hpl_boundary
|
|
26
|
+
from .hpl.classical import classical_hpl
|
|
27
|
+
from .hpl.constants import ConstantNumericResult, evaluate_euler_sum, evaluate_mzv
|
|
28
|
+
from .hpl.endpoints import hpl_at_one, reduce_mzv
|
|
29
|
+
from .hpl.inversion import invert_hpl
|
|
30
|
+
from .hpl.limits import hpl_limit_at_one
|
|
31
|
+
from .hpl.maps import fractional_hpl, square_hpl
|
|
32
|
+
from .hpl.mobius import mobius_hpl
|
|
33
|
+
from .hpl.named_constants import HPLs6, HPLs7a, HPLs7b, HPLs8a, HPLs8b, HPLs8c, HPLs8d
|
|
34
|
+
from .hpl.notation import compress_indices, expand_indices, hpl_pm, letters_to_pm, pm_to_letters
|
|
35
|
+
from .hpl.numeric import (
|
|
36
|
+
HPLNumericalConvergenceError,
|
|
37
|
+
HPLNumericResult,
|
|
38
|
+
evaluate_hpl,
|
|
39
|
+
hpl_evalf,
|
|
40
|
+
)
|
|
41
|
+
from .hpl.radial_continuation import HPLContinuationResult, continue_hpl
|
|
42
|
+
from .hpl.real_continuation import analytic_continue_hpl
|
|
43
|
+
from .hpl.reduction import extract_hpl_logs, lyndon_factors, lyndon_reduce
|
|
44
|
+
from .hpl.regularization import (
|
|
45
|
+
hpl_endpoint_polynomial,
|
|
46
|
+
hpl_expression_endpoint_polynomial,
|
|
47
|
+
shuffle_regularized_hpl_at_one,
|
|
48
|
+
)
|
|
49
|
+
from .hpl.series_one import hpl_series_at_one
|
|
50
|
+
from .hpl.special import hpl_at_i
|
|
51
|
+
from .hpl.stuffle import stuffle_expand_constants
|
|
52
|
+
from .hpl.taylor import hpl_taylor
|
|
53
|
+
from .hpl.transforms import negate_hpl, reflect_hpl
|
|
54
|
+
from .hypexp_integrals import beta_log_moment, hypergeometric_log_moment
|
|
55
|
+
from .native import NativeBackend, NativeConfig
|
|
56
|
+
from .nielsen import NielsenPolylog, hpl_to_nielsen, nielsen_to_hpl, reduce_nielsen
|
|
57
|
+
from .serialization import SerializationError, decode_expr, encode_expr
|
|
58
|
+
from .symbolic import HPL, MZV, EulerSum
|
|
59
|
+
|
|
60
|
+
__version__ = "0.2.0"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def hypergeometric(
|
|
64
|
+
upper: Iterable[ExactScalar],
|
|
65
|
+
lower: Iterable[ExactScalar],
|
|
66
|
+
argument: ExactScalar,
|
|
67
|
+
) -> hyper:
|
|
68
|
+
"""Construct an unevaluated generalized hypergeometric function.
|
|
69
|
+
|
|
70
|
+
Construction preserves matching upper and lower parameters for later
|
|
71
|
+
validation by `expand_epsilon`.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
upper: Exact numerator parameters in their supplied order.
|
|
75
|
+
lower: Exact denominator parameters in their supplied order.
|
|
76
|
+
argument: Exact argument of the function.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
A SymPy hypergeometric atom with parameter cancellation disabled.
|
|
80
|
+
"""
|
|
81
|
+
return cast(hyper, hyper(tuple(upper), tuple(lower), argument, evaluate=False))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
__all__ = [
|
|
85
|
+
"HPL",
|
|
86
|
+
"MZV",
|
|
87
|
+
"BackendConfig",
|
|
88
|
+
"BackendError",
|
|
89
|
+
"BackendProtocolError",
|
|
90
|
+
"BackendTimeoutError",
|
|
91
|
+
"BackendUnavailableError",
|
|
92
|
+
"ConstantNumericResult",
|
|
93
|
+
"EulerSum",
|
|
94
|
+
"ExpansionResult",
|
|
95
|
+
"HPLBoundaryNumericResult",
|
|
96
|
+
"HPLContinuationResult",
|
|
97
|
+
"HPLNumericResult",
|
|
98
|
+
"HPLNumericalConvergenceError",
|
|
99
|
+
"HPLs6",
|
|
100
|
+
"HPLs7a",
|
|
101
|
+
"HPLs7b",
|
|
102
|
+
"HPLs8a",
|
|
103
|
+
"HPLs8b",
|
|
104
|
+
"HPLs8c",
|
|
105
|
+
"HPLs8d",
|
|
106
|
+
"HypraError",
|
|
107
|
+
"IncompleteExpansionError",
|
|
108
|
+
"NativeBackend",
|
|
109
|
+
"NativeConfig",
|
|
110
|
+
"NielsenPolylog",
|
|
111
|
+
"SerializationError",
|
|
112
|
+
"UnsupportedExpressionError",
|
|
113
|
+
"__version__",
|
|
114
|
+
"analytic_continue_hpl",
|
|
115
|
+
"backend_info",
|
|
116
|
+
"beta_log_moment",
|
|
117
|
+
"classical_hpl",
|
|
118
|
+
"compress_indices",
|
|
119
|
+
"continue_hpl",
|
|
120
|
+
"decode_expr",
|
|
121
|
+
"encode_expr",
|
|
122
|
+
"evaluate_euler_sum",
|
|
123
|
+
"evaluate_hpl",
|
|
124
|
+
"evaluate_hpl_boundary",
|
|
125
|
+
"evaluate_mzv",
|
|
126
|
+
"expand_epsilon",
|
|
127
|
+
"expand_indices",
|
|
128
|
+
"extract_hpl_logs",
|
|
129
|
+
"fractional_hpl",
|
|
130
|
+
"hpl_alternating_at_one",
|
|
131
|
+
"hpl_at_i",
|
|
132
|
+
"hpl_at_one",
|
|
133
|
+
"hpl_endpoint_polynomial",
|
|
134
|
+
"hpl_evalf",
|
|
135
|
+
"hpl_expression_endpoint_polynomial",
|
|
136
|
+
"hpl_limit_at_one",
|
|
137
|
+
"hpl_pm",
|
|
138
|
+
"hpl_series",
|
|
139
|
+
"hpl_series_at_one",
|
|
140
|
+
"hpl_taylor",
|
|
141
|
+
"hpl_to_nielsen",
|
|
142
|
+
"hypergeometric",
|
|
143
|
+
"hypergeometric_log_moment",
|
|
144
|
+
"integrate_from_zero",
|
|
145
|
+
"invert_hpl",
|
|
146
|
+
"letters_to_pm",
|
|
147
|
+
"lyndon_factors",
|
|
148
|
+
"lyndon_reduce",
|
|
149
|
+
"mobius_hpl",
|
|
150
|
+
"negate_hpl",
|
|
151
|
+
"nielsen_to_hpl",
|
|
152
|
+
"pm_to_letters",
|
|
153
|
+
"primitive_hpl",
|
|
154
|
+
"reduce_euler_sum",
|
|
155
|
+
"reduce_mzv",
|
|
156
|
+
"reduce_nielsen",
|
|
157
|
+
"reflect_hpl",
|
|
158
|
+
"shuffle_expand",
|
|
159
|
+
"shuffle_regularized_hpl_at_one",
|
|
160
|
+
"square_hpl",
|
|
161
|
+
"stuffle_expand_constants",
|
|
162
|
+
"transform_hpl_arguments",
|
|
163
|
+
]
|
hypra/__main__.py
ADDED
hypra/_json.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Strict JSON loading shared by the CLI and both backends."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def strict_json_loads(text: str) -> Any:
|
|
8
|
+
"""Reject duplicate object keys and JSON's nonstandard nonfinite constants."""
|
|
9
|
+
|
|
10
|
+
def unique_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
11
|
+
result: dict[str, Any] = {}
|
|
12
|
+
for key, value in pairs:
|
|
13
|
+
if key in result:
|
|
14
|
+
raise ValueError(f"Duplicate JSON key: {key}")
|
|
15
|
+
result[key] = value
|
|
16
|
+
return result
|
|
17
|
+
|
|
18
|
+
def reject_constant(value: str) -> Any:
|
|
19
|
+
raise ValueError(f"Nonfinite JSON constant: {value}")
|
|
20
|
+
|
|
21
|
+
return json.loads(text, object_pairs_hook=unique_pairs, parse_constant=reject_constant)
|
hypra/_typing.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Input types shared by the public symbolic and numerical APIs."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from typing import Literal, cast
|
|
5
|
+
|
|
6
|
+
import sympy as s
|
|
7
|
+
|
|
8
|
+
type ExactInteger = int | s.Integer
|
|
9
|
+
type IntegerWord = (
|
|
10
|
+
tuple[ExactInteger, ...] | list[int] | list[s.Integer] | list[ExactInteger] | s.Tuple
|
|
11
|
+
)
|
|
12
|
+
type ExactScalar = s.Expr | int
|
|
13
|
+
type Interval = Literal["0<z<1"]
|
|
14
|
+
type Boundary = Literal["upper", "lower"]
|
|
15
|
+
type RealRegion = Literal["0<x<1", "-1<x<0", "x>1", "x<-1"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def as_integer_tuple(word: IntegerWord) -> tuple[int, ...]:
|
|
19
|
+
"""Convert a word whose entries have been validated as exact integers."""
|
|
20
|
+
# SymPy Tuple stores its entries as Basic, regardless of their actual type.
|
|
21
|
+
return tuple(map(int, cast(Iterable[ExactInteger], word)))
|
hypra/api.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Public expansion API with exact input and checked Laurent output."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict, dataclass
|
|
4
|
+
from typing import Any, Literal, Protocol, cast
|
|
5
|
+
|
|
6
|
+
import sympy as s
|
|
7
|
+
from sympy.logic.boolalg import Boolean
|
|
8
|
+
|
|
9
|
+
from .config import BackendConfig
|
|
10
|
+
from .errors import IncompleteExpansionError, UnsupportedExpressionError
|
|
11
|
+
from .native import NativeBackend, NativeConfig
|
|
12
|
+
from .native.planning import laurent_coefficient, plan_expansion
|
|
13
|
+
|
|
14
|
+
type BackendName = Literal["native", "wolfram"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ExpansionBackend(Protocol):
|
|
18
|
+
"""Structural interface for an injected expansion backend."""
|
|
19
|
+
|
|
20
|
+
def expand(self, request: dict[str, Any], /) -> dict[str, Any]:
|
|
21
|
+
"""Return a certified expansion response for the exact AST request."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ExpansionResult:
|
|
27
|
+
"""Exact Laurent polynomial plus its remainder and reproducibility record.
|
|
28
|
+
|
|
29
|
+
``sympy.sympify(result)`` includes the order remainder.
|
|
30
|
+
|
|
31
|
+
Attributes:
|
|
32
|
+
polynomial: Exact Laurent polynomial used for coefficient algebra.
|
|
33
|
+
epsilon: Regulator expanded about zero.
|
|
34
|
+
through: Highest certified Laurent power.
|
|
35
|
+
provenance: Input ASTs, plan, backend details, and branch conventions.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
polynomial: s.Expr
|
|
39
|
+
epsilon: s.Symbol
|
|
40
|
+
through: int
|
|
41
|
+
provenance: dict[str, Any]
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def expression(self) -> s.Expr:
|
|
45
|
+
"""Exact Laurent expansion including the SymPy order remainder."""
|
|
46
|
+
return self.polynomial + s.Order(self.epsilon ** (self.through + 1), (self.epsilon, 0))
|
|
47
|
+
|
|
48
|
+
def coefficient(self, power: int) -> s.Expr:
|
|
49
|
+
"""Return the coefficient of the requested Laurent power.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
power: Integer exponent of the regulator.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
TypeError: The exponent is not an integer.
|
|
56
|
+
ValueError: The exponent exceeds the certified order.
|
|
57
|
+
"""
|
|
58
|
+
if not isinstance(power, int) or isinstance(power, bool):
|
|
59
|
+
raise TypeError("power must be an integer")
|
|
60
|
+
if power > self.through:
|
|
61
|
+
raise ValueError("Coefficient is beyond the certified truncation order")
|
|
62
|
+
return laurent_coefficient(self.polynomial, self.epsilon, power)
|
|
63
|
+
|
|
64
|
+
def latex(self, *, include_order: bool = True) -> str:
|
|
65
|
+
"""Render exact mathematics, including symbolic HPL words, as LaTeX.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
include_order: Include the SymPy order remainder.
|
|
69
|
+
"""
|
|
70
|
+
return s.latex(self.expression if include_order else self.polynomial)
|
|
71
|
+
|
|
72
|
+
def _sympy_(self) -> s.Expr:
|
|
73
|
+
return self.expression
|
|
74
|
+
|
|
75
|
+
def to_dict(self) -> dict[str, Any]:
|
|
76
|
+
"""Return the exact JSON-compatible ASTs, LaTeX, and provenance."""
|
|
77
|
+
from .serialization import encode_expr
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
"polynomial": encode_expr(self.polynomial),
|
|
81
|
+
"epsilon": encode_expr(self.epsilon),
|
|
82
|
+
"through": self.through,
|
|
83
|
+
"remainder_order": self.through + 1,
|
|
84
|
+
"latex": self.latex(),
|
|
85
|
+
"provenance": self.provenance,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def backend_info(
|
|
90
|
+
config: NativeConfig | BackendConfig | None = None,
|
|
91
|
+
*,
|
|
92
|
+
backend: BackendName = "native",
|
|
93
|
+
) -> dict[str, Any]:
|
|
94
|
+
"""Report native backend capabilities or inspect an external Wolfram installation.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
config: Configuration for the selected backend.
|
|
98
|
+
backend: Engine to inspect.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
A JSON-compatible capability record including engine availability.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
ValueError: The backend name is unknown.
|
|
105
|
+
"""
|
|
106
|
+
if backend == "native":
|
|
107
|
+
info = NativeBackend(cast(NativeConfig | None, config)).info()
|
|
108
|
+
elif backend == "wolfram":
|
|
109
|
+
from .backend import WolframBackend
|
|
110
|
+
|
|
111
|
+
info = WolframBackend(cast(BackendConfig | None, config)).info()
|
|
112
|
+
else:
|
|
113
|
+
raise ValueError("backend must be 'native' or 'wolfram'")
|
|
114
|
+
return info.as_dict() if hasattr(info, "as_dict") else asdict(info)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _checked_polynomial(
|
|
118
|
+
expr: s.Expr,
|
|
119
|
+
epsilon: s.Symbol,
|
|
120
|
+
through: int,
|
|
121
|
+
lower_bound: int,
|
|
122
|
+
) -> s.Expr:
|
|
123
|
+
if expr.has(
|
|
124
|
+
s.Float, s.nan, s.zoo, s.oo, -s.oo, s.Derivative, s.Subs, s.Integral, s.Sum, s.hyper
|
|
125
|
+
):
|
|
126
|
+
raise IncompleteExpansionError(
|
|
127
|
+
"Backend returned non-exact, unresolved, or non-finite output"
|
|
128
|
+
)
|
|
129
|
+
expanded = s.expand(expr)
|
|
130
|
+
for term in s.Add.make_args(expanded):
|
|
131
|
+
if term == 0:
|
|
132
|
+
continue
|
|
133
|
+
coefficient, power = term.as_coeff_exponent(epsilon)
|
|
134
|
+
if coefficient.has(epsilon) or not power.is_Integer:
|
|
135
|
+
raise IncompleteExpansionError("Backend output is not a Laurent polynomial in epsilon")
|
|
136
|
+
if power > through or (term != 0 and power < lower_bound):
|
|
137
|
+
raise IncompleteExpansionError(
|
|
138
|
+
"Backend output contradicts the requested Laurent bounds"
|
|
139
|
+
)
|
|
140
|
+
return expanded
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def expand_epsilon(
|
|
144
|
+
expr: s.Expr,
|
|
145
|
+
epsilon: s.Symbol,
|
|
146
|
+
through: int = 3,
|
|
147
|
+
assumptions: Boolean | None = None,
|
|
148
|
+
*,
|
|
149
|
+
config: NativeConfig | BackendConfig | None = None,
|
|
150
|
+
backend: BackendName | ExpansionBackend | None = None,
|
|
151
|
+
) -> ExpansionResult:
|
|
152
|
+
"""Expand the complete expression through the inclusive Laurent order.
|
|
153
|
+
|
|
154
|
+
The default backend is native Python/SymPy and supports documented integer and half-integer
|
|
155
|
+
parameter families. Every prefactor is included; atoms are expanded deeper
|
|
156
|
+
when poles require it. Unsupported cases fail closed without fallback.
|
|
157
|
+
Set backend="wolfram" explicitly to use the experimental external bridge.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
expr: Exact symbolic input without floating-point atoms.
|
|
161
|
+
epsilon: Regulator expanded at zero.
|
|
162
|
+
through: Inclusive order. For example, 3 includes all poles and epsilon**3.
|
|
163
|
+
assumptions: Explicit relational assumptions, such as `And(w > 0, w < 1)`.
|
|
164
|
+
Assumptions attached to input symbols are preserved.
|
|
165
|
+
config: Settings for the selected backend. Native settings can opt in
|
|
166
|
+
to meromorphic parameter continuation at z=1.
|
|
167
|
+
backend: Native, Wolfram, or a custom engine implementing `expand`.
|
|
168
|
+
The result records a custom engine as injected.
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
Exact Laurent polynomial, order remainder, and provenance.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
TypeError: The input, regulator, assumptions, or configuration has the wrong type.
|
|
175
|
+
ValueError: The backend name is unknown.
|
|
176
|
+
UnsupportedExpressionError: The expression or its domain is unsupported.
|
|
177
|
+
IncompleteExpansionError: The backend could not certify a complete exact result.
|
|
178
|
+
"""
|
|
179
|
+
from .backend import WolframBackend
|
|
180
|
+
from .serialization import decode_expr, encode_expr
|
|
181
|
+
|
|
182
|
+
if not isinstance(expr, s.Expr):
|
|
183
|
+
raise TypeError("expr must be an exact SymPy expression, not a string")
|
|
184
|
+
if not isinstance(epsilon, s.Symbol):
|
|
185
|
+
raise TypeError("epsilon must be a SymPy Symbol")
|
|
186
|
+
if assumptions is None:
|
|
187
|
+
assumptions = s.true
|
|
188
|
+
if not isinstance(assumptions, Boolean):
|
|
189
|
+
raise TypeError("assumptions must be a SymPy Boolean expression")
|
|
190
|
+
if s.simplify(assumptions) is s.false:
|
|
191
|
+
raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain")
|
|
192
|
+
try:
|
|
193
|
+
if s.satisfiable(assumptions, use_lra_theory=True) is False:
|
|
194
|
+
raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain")
|
|
195
|
+
except (AssertionError, ValueError, NotImplementedError) as exc:
|
|
196
|
+
if isinstance(exc, UnsupportedExpressionError):
|
|
197
|
+
raise
|
|
198
|
+
# Isolated complex-symbol nonzero guards need no ordering theory.
|
|
199
|
+
# Remove only Ne(symbol,0) guards whose symbols occur nowhere else in
|
|
200
|
+
# the assumption formula; all remaining domain relations still pass LRA.
|
|
201
|
+
clauses = list(assumptions.args) if isinstance(assumptions, s.And) else [assumptions]
|
|
202
|
+
independent = []
|
|
203
|
+
for clause in clauses:
|
|
204
|
+
if not isinstance(clause, s.Unequality):
|
|
205
|
+
continue
|
|
206
|
+
symbol = clause.lhs if clause.rhs == 0 else clause.rhs if clause.lhs == 0 else None
|
|
207
|
+
if isinstance(symbol, s.Symbol) and all(
|
|
208
|
+
other == clause or not other.has(symbol) for other in clauses
|
|
209
|
+
):
|
|
210
|
+
independent.append(clause)
|
|
211
|
+
if not independent:
|
|
212
|
+
raise UnsupportedExpressionError(
|
|
213
|
+
"Assumption consistency is unsupported; use linear real-domain relations"
|
|
214
|
+
) from exc
|
|
215
|
+
remaining = s.And(*(clause for clause in clauses if clause not in independent))
|
|
216
|
+
try:
|
|
217
|
+
if s.satisfiable(remaining, use_lra_theory=True) is False:
|
|
218
|
+
raise UnsupportedExpressionError("Contradictory assumptions are not a valid domain")
|
|
219
|
+
except (AssertionError, ValueError, NotImplementedError) as remainder_error:
|
|
220
|
+
if isinstance(remainder_error, UnsupportedExpressionError):
|
|
221
|
+
raise
|
|
222
|
+
raise UnsupportedExpressionError(
|
|
223
|
+
"Assumption consistency is unsupported beyond isolated nonzero guards"
|
|
224
|
+
) from remainder_error
|
|
225
|
+
if expr.has(s.Float, s.nan, s.zoo, s.oo, -s.oo):
|
|
226
|
+
raise UnsupportedExpressionError(
|
|
227
|
+
"Input must be exact and finite; use Rational instead of Float"
|
|
228
|
+
)
|
|
229
|
+
# Encode before invoking anything external: this checks all input heads,
|
|
230
|
+
# identifiers, exact constants and assumption syntax against a whitelist.
|
|
231
|
+
expression_ast, epsilon_ast = encode_expr(expr), encode_expr(epsilon)
|
|
232
|
+
assumption_ast = encode_expr(assumptions)
|
|
233
|
+
declared: dict[str, s.Symbol] = {}
|
|
234
|
+
input_symbols = cast(set[s.Symbol], expr.free_symbols | assumptions.free_symbols | {epsilon})
|
|
235
|
+
for symbol in input_symbols:
|
|
236
|
+
if symbol.name in declared and declared[symbol.name] != symbol:
|
|
237
|
+
raise UnsupportedExpressionError(
|
|
238
|
+
"Symbols with the same name and different assumptions are ambiguous"
|
|
239
|
+
)
|
|
240
|
+
declared[symbol.name] = symbol
|
|
241
|
+
original_ast = expression_ast
|
|
242
|
+
native: NativeBackend | None = None
|
|
243
|
+
if backend is None or backend == "native":
|
|
244
|
+
from .native.endpoints import rewrite_endpoints
|
|
245
|
+
|
|
246
|
+
native = NativeBackend(cast(NativeConfig | None, config))
|
|
247
|
+
expr = rewrite_endpoints(
|
|
248
|
+
expr,
|
|
249
|
+
epsilon,
|
|
250
|
+
assumptions,
|
|
251
|
+
meromorphic=native.config.unit_endpoint == "meromorphic",
|
|
252
|
+
excess_shift=native.config.unit_excess_shift,
|
|
253
|
+
shift_singular_lowers=native.config.unit_shift_singular_lowers,
|
|
254
|
+
)
|
|
255
|
+
expression_ast = encode_expr(expr)
|
|
256
|
+
plan = plan_expansion(expr, epsilon, through, assumptions)
|
|
257
|
+
active: ExpansionBackend
|
|
258
|
+
if backend == "wolfram":
|
|
259
|
+
active = WolframBackend(cast(BackendConfig | None, config))
|
|
260
|
+
injected = False
|
|
261
|
+
elif backend is not None and not isinstance(backend, str):
|
|
262
|
+
active = backend
|
|
263
|
+
injected = True
|
|
264
|
+
elif native is not None:
|
|
265
|
+
active = native
|
|
266
|
+
injected = False
|
|
267
|
+
else:
|
|
268
|
+
raise ValueError("Unknown backend; choose 'native' or 'wolfram'")
|
|
269
|
+
request = {
|
|
270
|
+
"protocol": 1,
|
|
271
|
+
"operation": "expand",
|
|
272
|
+
"expression": expression_ast,
|
|
273
|
+
"epsilon": epsilon_ast,
|
|
274
|
+
"through": through,
|
|
275
|
+
"internal_order": plan.internal_order,
|
|
276
|
+
"assumptions": assumption_ast,
|
|
277
|
+
}
|
|
278
|
+
response = active.expand(request)
|
|
279
|
+
if not isinstance(response, dict):
|
|
280
|
+
raise IncompleteExpansionError("Backend result must be a structured object")
|
|
281
|
+
if response.get("complete") is not True:
|
|
282
|
+
raise IncompleteExpansionError("Backend marked the expansion incomplete")
|
|
283
|
+
if (
|
|
284
|
+
type(response.get("achieved_through")) is not int
|
|
285
|
+
or response["achieved_through"] != through
|
|
286
|
+
or type(response.get("remainder_order")) is not int
|
|
287
|
+
or response["remainder_order"] != through + 1
|
|
288
|
+
):
|
|
289
|
+
raise IncompleteExpansionError("Backend did not certify the requested inclusive order")
|
|
290
|
+
try:
|
|
291
|
+
polynomial = decode_expr(response["result"])
|
|
292
|
+
except (KeyError, ValueError, TypeError) as exc:
|
|
293
|
+
raise IncompleteExpansionError("Backend returned an invalid symbolic result") from exc
|
|
294
|
+
if not isinstance(polynomial, s.Expr):
|
|
295
|
+
raise IncompleteExpansionError("Backend result must be a scalar SymPy expression")
|
|
296
|
+
output_symbols = cast(set[s.Symbol], polynomial.free_symbols)
|
|
297
|
+
if any(symbol.name not in declared for symbol in output_symbols):
|
|
298
|
+
raise IncompleteExpansionError("Backend introduced undeclared symbols")
|
|
299
|
+
polynomial = cast(
|
|
300
|
+
s.Expr,
|
|
301
|
+
polynomial.xreplace({symbol: declared[symbol.name] for symbol in output_symbols}),
|
|
302
|
+
)
|
|
303
|
+
polynomial = _checked_polynomial(polynomial, epsilon, through, plan.valuation_lower_bound)
|
|
304
|
+
backend_record = response.get("backend", {})
|
|
305
|
+
if not isinstance(backend_record, dict):
|
|
306
|
+
raise IncompleteExpansionError("Backend provenance must be a structured object")
|
|
307
|
+
provenance = {
|
|
308
|
+
"hypra_version": "0.2.0",
|
|
309
|
+
"sympy_version": s.__version__,
|
|
310
|
+
"input": original_ast,
|
|
311
|
+
"planned_input": expression_ast,
|
|
312
|
+
"epsilon": epsilon_ast,
|
|
313
|
+
"assumptions": assumption_ast,
|
|
314
|
+
"plan": asdict(plan),
|
|
315
|
+
"backend": backend_record,
|
|
316
|
+
"backend_fingerprint": response.get("provenance", {}),
|
|
317
|
+
"cache_hit": response.get("cache_hit", False),
|
|
318
|
+
"order_basis": response.get("order_basis"),
|
|
319
|
+
"injected_backend": injected,
|
|
320
|
+
"branch_convention": "Principal branches",
|
|
321
|
+
"unit_endpoint": native.config.unit_endpoint if native is not None else None,
|
|
322
|
+
"unit_excess_shift": native.config.unit_excess_shift if native is not None else None,
|
|
323
|
+
"unit_shift_singular_lowers": (
|
|
324
|
+
native.config.unit_shift_singular_lowers if native is not None else None
|
|
325
|
+
),
|
|
326
|
+
"certificate_scope": "Conditional on backend correctness and the stated input domain",
|
|
327
|
+
}
|
|
328
|
+
return ExpansionResult(polynomial, epsilon, through, provenance)
|