diff --git a/mathics/builtin/numbers/calculus.py b/mathics/builtin/numbers/calculus.py
index 2dfcf44f1..e2719e93f 100644
--- a/mathics/builtin/numbers/calculus.py
+++ b/mathics/builtin/numbers/calculus.py
@@ -23,6 +23,7 @@
Integer10,
IntegerM1,
Number,
+ PrecisionReal,
Rational,
Real,
String,
@@ -92,6 +93,25 @@
decompose_domain,
eval_D_to_Integral,
)
+from mathics.eval.numbers.calculus.projective_integrator import (
+ eval_contour_integrate_projective,
+ eval_exp_to_trig_projective,
+ eval_inverse_laplace_transform_projective,
+ eval_laplace_transform_projective,
+ eval_pade_approximant,
+ eval_projective_constant,
+ eval_projective_contour_winding,
+ eval_projective_integrate,
+ eval_projective_isotropic_stencil,
+ eval_projective_quadratic_sum,
+ eval_projective_ring_point,
+ eval_residue_projective,
+ eval_stieltjes_pade_resolvent,
+ eval_trig_expand_projective,
+ eval_trig_factor_projective,
+ eval_trig_reduce_projective,
+ eval_trig_to_exp_projective,
+)
from mathics.eval.numbers.calculus.series import (
build_series,
series_derivative,
@@ -1124,8 +1144,10 @@ def eval(self, f, xs, evaluation: Evaluation, options: dict): # type: ignore[ov
else:
vars.append((x, a, b))
try:
+ proj_result = eval_projective_integrate(f_sympy, vars)
+ if proj_result is not None:
+ return from_sympy(proj_result)
sympy_result = tracing.run_sympy(sympy.integrate, f_sympy, *vars)
- pass
except sympy.PolynomialError:
return
except ValueError:
@@ -2549,3 +2571,567 @@ def is_zero(
threshold_expr = Expression(SymbolLog, eps_expr)
threshold: Real = eval_N(threshold_expr, evaluation)
return threshold.to_python() > 0
+
+
+class ContourIntegrate(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/ContourIntegrate.html
+
+
+ - 'ContourIntegrate'[$f$, {$z$, 'Circle'[{$x_0$, $y_0$}, $r$]}]
+
- computes the closed contour integral of $f$ along the circle $|z - (x_0 + i y_0)| = r$
+ on the Riemann sphere $\\mathbb{P}^1(\\mathbb{C})$ via Ostrowski-Hermite reduction
+ and Cauchy-Lagrange residues over $\\mathbb{Q}(i, \\sqrt{d-1})$.
+
+
- 'ContourIntegrate'[$f$, {$z$, $z_0$, $r$}]
+
- computes the closed contour integral of $f$ along the circle $|z - z_0| = r$.
+
+
+ >> ContourIntegrate[1 / (1 + z^4), {z, Circle[{0, 1}, 1]}]
+ = Sqrt[2] Pi / 2
+
+ >> ContourIntegrate[1 / (1 + z^2), {z, I, 1}]
+ = Pi
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "closed contour integration on the Riemann sphere P^1(C)"
+
+ def eval_circle(self, f, z, x0, y0, r, evaluation: Evaluation):
+ "ContourIntegrate[f_, {z_Symbol, Circle[{x0_, y0_}, r_]}]"
+ f_sympy = f.to_sympy()
+ z_sympy = z.to_sympy()
+ x0_sympy = x0.to_sympy()
+ y0_sympy = y0.to_sympy()
+ r_sympy = r.to_sympy()
+ if None in (f_sympy, z_sympy, x0_sympy, y0_sympy, r_sympy):
+ return None
+ center = x0_sympy + sympy.I * y0_sympy
+ res = eval_contour_integrate_projective(f_sympy, z_sympy, center, r_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+ def eval_center_radius(self, f, z, z0, r, evaluation: Evaluation):
+ "ContourIntegrate[f_, {z_Symbol, z0_, r_}]"
+ f_sympy = f.to_sympy()
+ z_sympy = z.to_sympy()
+ z0_sympy = z0.to_sympy()
+ r_sympy = r.to_sympy()
+ if None in (f_sympy, z_sympy, z0_sympy, r_sympy):
+ return None
+ res = eval_contour_integrate_projective(f_sympy, z_sympy, z0_sympy, r_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class PadeApproximant(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/PadeApproximant.html
+
+
+ - 'PadeApproximant'[$expr$, {$x$, $x_0$, {$m$, $n$}}]
+
- gives the $[m/n]$ Pade rational approximant to $expr$ about the point $x = x_0$.
+
+
- 'PadeApproximant'[$expr$, {$x$, $x_0$, $n$}]
+
- gives the diagonal $[n/n]$ Pade rational approximant to $expr$ about $x = x_0$.
+
+
+ >> PadeApproximant[Exp[x], {x, 0, {2, 2}}]
+ = (12 + 6 x + x ^ 2) / (12 - 6 x + x ^ 2)
+
+ >> PadeApproximant[ArcTan[x], {x, 0, {3, 3}}]
+ = (15 x + 4 x ^ 3) / (15 + 9 x ^ 2)
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "rational Pade approximant [m/n] about a point"
+
+ def eval_mn(self, expr, x, x0, m: Integer, n: Integer, evaluation: Evaluation):
+ "PadeApproximant[expr_, {x_Symbol, x0_, {m_Integer, n_Integer}}]"
+ f_sympy = expr.to_sympy()
+ x_sympy = x.to_sympy()
+ x0_sympy = x0.to_sympy()
+ if None in (f_sympy, x_sympy, x0_sympy):
+ return None
+ res = eval_pade_approximant(f_sympy, x_sympy, x0_sympy, m.value, n.value)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+ def eval_diag(self, expr, x, x0, n: Integer, evaluation: Evaluation):
+ "PadeApproximant[expr_, {x_Symbol, x0_, n_Integer}]"
+ return self.eval_mn(expr, x, x0, n, n, evaluation)
+
+
+class Residue(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/Residue.html
+
+
+ - 'Residue'[$expr$, {$z$, $z_0$}]
+
- finds the Cauchy-Lagrange residue of $expr$ at the point $z = z_0$ on the
+ Riemann sphere $\\mathbb{P}^1(\\mathbb{C})$ (including $z_0 = \\infty$).
+
+
+ >> Residue[1 / (z^2 + 1), {z, I}]
+ = -I / 2
+
+ >> Residue[1 / z, {z, Infinity}]
+ = -1
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "Cauchy-Lagrange residue at a pole on P^1(C)"
+
+ def eval(self, expr, z, z0, evaluation: Evaluation):
+ "Residue[expr_, {z_Symbol, z0_}]"
+ f_sympy = expr.to_sympy()
+ z_sympy = z.to_sympy()
+ z0_sympy = z0.to_sympy()
+ if None in (f_sympy, z_sympy, z0_sympy):
+ return None
+ res = eval_residue_projective(f_sympy, z_sympy, z0_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class TrigReduce(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/TrigReduce.html
+
+
+ - 'TrigReduce'[$expr$]
+
- rewrites products and powers of trigonometric functions in $expr$ in terms
+ of trigonometric functions with combined arguments via projective $\\mathbb{P}^1$
+ reduction.
+
+
+ >> TrigReduce[Sin[3 x] - (3 Sin[x] - 4 Sin[x]^3)]
+ = 0
+
+ >> TrigReduce[2 Sin[x] Cos[x]]
+ = Sin[2 x]
+ """
+
+ attributes = A_LISTABLE | A_PROTECTED
+ summary_text = "projective trigonometric power and product reduction"
+
+ def eval(self, expr, evaluation: Evaluation):
+ "TrigReduce[expr_]"
+ f_sympy = expr.to_sympy()
+ if f_sympy is None:
+ return None
+ res = eval_trig_reduce_projective(f_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class TrigExpand(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/TrigExpand.html
+
+
+ - 'TrigExpand'[$expr$]
+
- expands trigonometric functions of sums of angles and multiple angles via
+ projective Chebyshev-Cayley identities.
+
+
+ >> TrigExpand[Sin[2 x]]
+ = 2 Cos[x] Sin[x]
+
+ >> TrigExpand[Cos[2 x]]
+ = -Sin[x] ^ 2 + Cos[x] ^ 2
+ """
+
+ attributes = A_LISTABLE | A_PROTECTED
+ summary_text = "expand trigonometric functions of multiple angles and sums"
+
+ def eval(self, expr, evaluation: Evaluation):
+ "TrigExpand[expr_]"
+ f_sympy = expr.to_sympy()
+ if f_sympy is None:
+ return None
+ res = eval_trig_expand_projective(f_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class TrigFactor(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/TrigFactor.html
+
+
+ - 'TrigFactor'[$expr$]
+
- factors trigonometric polynomials and sums into products of trigonometric
+ terms.
+
+
+ >> TrigFactor[Sin[x]^2 - Cos[x]^2]
+ = -(Cos[x] - Sin[x]) (Cos[x] + Sin[x])
+ """
+
+ attributes = A_LISTABLE | A_PROTECTED
+ summary_text = "factor trigonometric expressions into products"
+
+ def eval(self, expr, evaluation: Evaluation):
+ "TrigFactor[expr_]"
+ f_sympy = expr.to_sympy()
+ if f_sympy is None:
+ return None
+ res = eval_trig_factor_projective(f_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class TrigToExp(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/TrigToExp.html
+
+
+ - 'TrigToExp'[$expr$]
+
- converts trigonometric and hyperbolic functions in $expr$ to complex
+ exponentials on $\\mathbb{P}^1(\\mathbb{Q}(i))$.
+
+
+ >> TrigToExp[Cos[x]]
+ = E ^ (-I x) / 2 + E ^ (I x) / 2
+ """
+
+ attributes = A_LISTABLE | A_PROTECTED
+ summary_text = "convert trigonometric functions to exponentials"
+
+ def eval(self, expr, evaluation: Evaluation):
+ "TrigToExp[expr_]"
+ f_sympy = expr.to_sympy()
+ if f_sympy is None:
+ return None
+ res = eval_trig_to_exp_projective(f_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class ExpToTrig(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/ExpToTrig.html
+
+
+ - 'ExpToTrig'[$expr$]
+
- converts exponentials in $expr$ to trigonometric and hyperbolic functions.
+
+
+ >> ExpToTrig[Exp[I x] + Exp[-I x]]
+ = 2 Cos[x]
+ """
+
+ attributes = A_LISTABLE | A_PROTECTED
+ summary_text = "convert exponentials to trigonometric and hyperbolic functions"
+
+ def eval(self, expr, evaluation: Evaluation):
+ "ExpToTrig[expr_]"
+ f_sympy = expr.to_sympy()
+ if f_sympy is None:
+ return None
+ res = eval_exp_to_trig_projective(f_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class LaplaceTransform(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/LaplaceTransform.html
+
+
+ - 'LaplaceTransform'[$f$, $t$, $s$]
+
- computes the Laplace transform $\\int_0^\\infty f(t) e^{-s t}\\,dt$.
+
+
+ >> LaplaceTransform[Sin[t], t, s]
+ = 1 / (1 + s ^ 2)
+
+ >> LaplaceTransform[Cos[2 t], t, s]
+ = s / (4 + s ^ 2)
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "Laplace transform into the complex frequency plane"
+
+ def eval(self, f, t, s, evaluation: Evaluation):
+ "LaplaceTransform[f_, t_Symbol, s_Symbol]"
+ f_sympy = f.to_sympy()
+ t_sympy = t.to_sympy()
+ s_sympy = s.to_sympy()
+ if None in (f_sympy, t_sympy, s_sympy):
+ return None
+ res = eval_laplace_transform_projective(f_sympy, t_sympy, s_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class InverseLaplaceTransform(Builtin):
+ """
+ :WMA link:https://reference.wolfram.com/language/ref/InverseLaplaceTransform.html
+
+
+ - 'InverseLaplaceTransform'[$F$, $s$, $t$]
+
- computes the inverse Laplace transform (time-evolution operator)
+ $\\frac{1}{2\\pi i}\\oint_\\gamma F(s) e^{s t}\\,ds$ via projective
+ Lagrange residue decomposition over $\\mathbb{Q}(i, \\sqrt{d-1})$.
+
+
+ >> InverseLaplaceTransform[1 / (1 + s^2), s, t]
+ = Sin[t]
+
+ >> InverseLaplaceTransform[(s - 2) / (s^2 - 5 s + 4), s, t]
+ = E ^ t / 3 + 2 E ^ (4 t) / 3
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "inverse Laplace transform and Riesz-Dunford time-evolution operator"
+
+ def eval(self, F, s, t, evaluation: Evaluation):
+ "InverseLaplaceTransform[F_, s_Symbol, t_Symbol]"
+ F_sympy = F.to_sympy()
+ s_sympy = s.to_sympy()
+ t_sympy = t.to_sympy()
+ if None in (F_sympy, s_sympy, t_sympy):
+ return None
+ res = eval_inverse_laplace_transform_projective(F_sympy, s_sympy, t_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class StieltjesPadeResolvent(Builtin):
+ """
+
+ - 'StieltjesPadeResolvent'[{$\\mu_0$, $\\mu_1$, ..., $\\mu_{2N-1}$}, $z$]
+
- constructs the exact $[N-1 / N]$ Stieltjes-Pade projective resolvent
+ $G_N(z) = \\langle \\psi_0 \\mid (z I - \\mathcal{L})^{-1} \\mid \\psi_0 \\rangle_{[N-1/N]} = P_{N-1}(z)/Q_N(z)$
+ on $\\mathbb{P}^1(\\mathbb{C})$ from $2N$ power moments $\\mu_k = \\langle \\psi_0 \\mid \\mathcal{L}^k \\mid \\psi_0 \\rangle$
+ of an infinite-dimensional Hilbert-space operator $\\mathcal{L}$.
+
+
+ >> StieltjesPadeResolvent[{1, 3, 11, 43}, s]
+ = (-2 + s) / (4 - 5 s + s ^ 2)
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "Stieltjes-Pade projective resolvent G_N(z) of a Hilbert-space operator from its moments"
+
+ def eval(self, moments: ListExpression, z, evaluation: Evaluation):
+ "StieltjesPadeResolvent[moments_List, z_Symbol]"
+ z_sympy = z.to_sympy()
+ if z_sympy is None:
+ return None
+ m_list = [el.to_sympy() for el in moments.elements]
+ if any(m is None for m in m_list):
+ return None
+ res = eval_stieltjes_pade_resolvent(m_list, z_sympy)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class ProjectiveConstant(Builtin):
+ """
+
+ - 'ProjectiveConstant'[$name$, $digits$]
+
- computes the fundamental mathematical constant $name$ to $digits$ decimal
+ places using pure-rational non-circular projective algorithms over
+ $\\mathbb{Q}(i, \\sqrt{d-1})$ and $\\mathbb{P}^1(\\mathbb{C})$ (Heron-Newton
+ square-root descent, Cayley-Pade $(5, 5)$ rational approximants, Gauss AGM
+ over $\\mathbb{Q}(\\sqrt{2})$, Ramanujan unit logarithm over $\\mathbb{Q}(\\sqrt{3})$,
+ and Amdeberhan-Zeilberger / Brent-McMillan rational acceleration, with zero
+ floating-point trigonometry or `mpmath` calls).
+ Supported constants: `"Pi"`, `"E"`, `"Log2"`, `"GoldenRatio"`,
+ `"Lemniscate"`, `"Gamma14"`, `"Catalan"`, `"Apery"`, `"EulerGamma"`.
+
+
- 'ProjectiveConstant'[$name$]
+
- computes $name$ to 50 decimal digits.
+
+
+ >> ProjectiveConstant["Pi", 30]
+ = 3.14159265358979323846264338328
+
+ >> ProjectiveConstant["Lemniscate", 30]
+ = 2.62205755429211981046483958989
+
+ >> ProjectiveConstant["Catalan", 30]
+ = 0.915965594177219015054603514932
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "non-circular pure-rational projective evaluator for fundamental mathematical constants"
+
+ @staticmethod
+ def _extract_name(name_expr) -> Optional[str]:
+ if isinstance(name_expr, String):
+ return name_expr.value
+ if isinstance(name_expr, Symbol):
+ return name_expr.short_name
+ return str(name_expr)
+
+ def eval_with_digits(self, name, digits: Integer, evaluation: Evaluation):
+ "ProjectiveConstant[name_, digits_Integer]"
+ key = self._extract_name(name)
+ if key is None:
+ return None
+ val = eval_projective_constant(key, digits.value)
+ if val is None:
+ return None
+ return PrecisionReal(val)
+
+ def eval_default(self, name, evaluation: Evaluation):
+ "ProjectiveConstant[name_]"
+ key = self._extract_name(name)
+ if key is None:
+ return None
+ val = eval_projective_constant(key, 50)
+ if val is None:
+ return None
+ return PrecisionReal(val)
+
+
+class ProjectiveRingPoint(Builtin):
+ """
+
+ - 'ProjectiveRingPoint'[$m$, $\\phi$]
+
- returns the exact rational unit-circle point $\\{x, y\\} \\in S^1(\\mathbb{Q})$
+ on the projective ring $\\mathbb{Z}_{2^m} \\cong \\mathbb{Z}_4^{\\mathrm{Gray}} \\ltimes \\mathbb{Z}_{2^{m-2}}$
+ satisfying $x^2 + y^2 \\equiv 1$ for any bit-depth $m \\ge 3$ and phase $\\phi \\in \\mathbb{Z}$,
+ with scale-invariant embedding under $(m, \\phi) \\mapsto (m+1, 2\\phi)$.
+
+
- 'ProjectiveRingPoint'[$m$, $\\phi$, $prop$]
+
- returns the specified invariant: `"UnitCircle"`, `"Character"` ($\\{C_m(\\phi), S_m(\\phi)\\}$),
+ `"PythagoreanTriple"` ($\\{P_x, P_y, P_r\\}$), or `"Wronskian"` ($W_m(\\phi) \\equiv 2^{m-2}$).
+
+
+ >> ProjectiveRingPoint[9, 41]
+ = {14703 / 18065, 10496 / 18065}
+
+ >> ProjectiveRingPoint[9, 41, "PythagoreanTriple"]
+ = {14703, 10496, 18065}
+
+ >> ProjectiveRingPoint[9, 41, "Wronskian"]
+ = 128
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "exact projective ring Z_{2^m} -> S^1(Q) unit-circle parameterization, Gray character, and Wronskian"
+
+ def eval_default(self, m: Integer, phi: Integer, evaluation: Evaluation):
+ "ProjectiveRingPoint[m_Integer, phi_Integer]"
+ res = eval_projective_ring_point(m.value, phi.value, "UnitCircle")
+ if res is None:
+ return None
+ return ListExpression(*(from_sympy(el) for el in res))
+
+ def eval_prop(self, m: Integer, phi: Integer, prop, evaluation: Evaluation):
+ "ProjectiveRingPoint[m_Integer, phi_Integer, prop_]"
+ key = ProjectiveConstant._extract_name(prop)
+ if key is None:
+ return None
+ res = eval_projective_ring_point(m.value, phi.value, key)
+ if res is None:
+ return None
+ if isinstance(res, list):
+ return ListExpression(*(from_sympy(el) for el in res))
+ return from_sympy(res)
+
+
+class ProjectiveQuadraticSum(Builtin):
+ """
+
+ - 'ProjectiveQuadraticSum'[$m$, $n_{\\mathrm{dim}}$]
+
- computes the exact $n_{\\mathrm{dim}}$-dimensional quadratic oscillating sum
+ $\\sum_{\\mathbf{x} \\in (\\mathbb{Z}_{2^m})^{n_{\\mathrm{dim}}}} (C_m(\\|\\mathbf{x}\\|^2) + i S_m(\\|\\mathbf{x}\\|^2))$
+ in $\\mathbb{Z}[i]$ for any bit-depth $m \\ge 3$ and dimension $n_{\\mathrm{dim}} \\ge 1$.
+
+
+ >> ProjectiveQuadraticSum[9, 1]
+ = 2048 + 2048 I
+
+ >> ProjectiveQuadraticSum[4, 3]
+ = -512 + 512 I
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "exact N-dimensional quadratic oscillating sum over (Z_{2^m})^N in Z[i]"
+
+ def eval(self, m: Integer, ndim: Integer, evaluation: Evaluation):
+ "ProjectiveQuadraticSum[m_Integer, ndim_Integer]"
+ res = eval_projective_quadratic_sum(m.value, ndim.value)
+ if res is None:
+ return None
+ return from_sympy(res)
+
+
+class ProjectiveContourWinding(Builtin):
+ """
+
+ - 'ProjectiveContourWinding'[$m$, {$\\phi_1$, $\\phi_2$, ..., $\\phi_k$}]
+
- computes the exact cohomological winding index $-\\sum k_{xy} \\in \\mathbb{Z}$
+ from the Euclidean phase decomposition $d\\phi = 2^m k_{xy} + A_{xy}$ along a closed
+ loop on $\\mathbb{Z}_{2^m}$.
+
+
+ >> ProjectiveContourWinding[9, {0, 130, 260, 390}]
+ = 1
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "exact cohomological contour winding index on Z_{2^m}"
+
+ def eval(self, m: Integer, phases: ListExpression, evaluation: Evaluation):
+ "ProjectiveContourWinding[m_Integer, phases_List]"
+ int_phases: list[int] = []
+ for el in phases.elements:
+ if not isinstance(el, Integer):
+ return None
+ int_phases.append(el.value)
+ res = eval_projective_contour_winding(m.value, int_phases)
+ if res is None:
+ return None
+ return Integer(res)
+
+
+class ProjectiveIsotropicStencil(Builtin):
+ """
+
+ - 'ProjectiveIsotropicStencil'[$d$]
+
- returns the $2d(d-1)$ integer displacement vectors of the $d$-dimensional
+ isotropic orbit $O_2(d) = \\{e \\in \\{-1, 0, 1\\}^d : \\|e\\|^2 = 2\\}$
+ satisfying $\\sum_{e \\in O_2(d)} e_i e_j = 4(d - 1)\\delta_{ij}$ for any $d \\ge 2$.
+
+
+ >> Length[ProjectiveIsotropicStencil[3]]
+ = 12
+
+ >> Length[ProjectiveIsotropicStencil[4]]
+ = 24
+ """
+
+ attributes = A_PROTECTED | A_READ_PROTECTED
+ summary_text = "O(d^2) isotropic d-dimensional stencil O_2(d) with second-moment tensor 4(d-1)I_d"
+
+ def eval(self, d: Integer, evaluation: Evaluation):
+ "ProjectiveIsotropicStencil[d_Integer]"
+ vecs = eval_projective_isotropic_stencil(d.value)
+ if vecs is None:
+ return None
+ return ListExpression(
+ *(ListExpression(*(Integer(coord) for coord in v)) for v in vecs)
+ )
+
+
+
+
diff --git a/mathics/builtin/numbers/trig.py b/mathics/builtin/numbers/trig.py
index 554c30e48..eb2cefa6e 100644
--- a/mathics/builtin/numbers/trig.py
+++ b/mathics/builtin/numbers/trig.py
@@ -29,6 +29,7 @@
SymbolCos,
SymbolSin,
)
+from mathics.eval.numbers.calculus.projective_integrator import eval_dyadic_pi_cos_sin
class Fold:
@@ -633,6 +634,17 @@ def condition_numbers(x: mpmath.mpf, value: mpmath.mpf) -> tuple[mpmath.mpf]:
summary_text = "cosine function"
sympy_name = "cos"
+ def prepare_mathics(self, sympy_expr):
+ import sympy as sp
+
+ if isinstance(sympy_expr, sp.cos):
+ ratio = sp.simplify(sympy_expr.args[0] / sp.pi)
+ if isinstance(ratio, sp.Rational) and ratio.q >= 16 and (int(ratio.q) & (int(ratio.q) - 1)) == 0:
+ pair = eval_dyadic_pi_cos_sin(int(ratio.p), int(ratio.q))
+ if pair is not None:
+ return pair[0]
+ return sympy_expr
+
class Cot(MPMathFunction):
"""
@@ -863,6 +875,17 @@ def condition_numbers(x: mpmath.mpf, value: mpmath.mpf) -> tuple[mpmath.mpf]:
summary_text = "sine function"
sympy_name = "sin"
+ def prepare_mathics(self, sympy_expr):
+ import sympy as sp
+
+ if isinstance(sympy_expr, sp.sin):
+ ratio = sp.simplify(sympy_expr.args[0] / sp.pi)
+ if isinstance(ratio, sp.Rational) and ratio.q >= 16 and (int(ratio.q) & (int(ratio.q) - 1)) == 0:
+ pair = eval_dyadic_pi_cos_sin(int(ratio.p), int(ratio.q))
+ if pair is not None:
+ return pair[1]
+ return sympy_expr
+
class Tan(MPMathFunction):
"""
@@ -903,3 +926,14 @@ def condition_numbers(x: mpmath.mpf, value: mpmath.mpf) -> tuple[mpmath.mpf]:
summary_text = "tangent function"
sympy_name = "tan"
+
+ def prepare_mathics(self, sympy_expr):
+ import sympy as sp
+
+ if isinstance(sympy_expr, sp.tan):
+ ratio = sp.simplify(sympy_expr.args[0] / sp.pi)
+ if isinstance(ratio, sp.Rational) and ratio.q >= 16 and (int(ratio.q) & (int(ratio.q) - 1)) == 0:
+ pair = eval_dyadic_pi_cos_sin(int(ratio.p), int(ratio.q))
+ if pair is not None and pair[0] != 0:
+ return sp.simplify(pair[1] / pair[0])
+ return sympy_expr
diff --git a/mathics/eval/numbers/calculus/projective_integrator.py b/mathics/eval/numbers/calculus/projective_integrator.py
new file mode 100644
index 000000000..5f0535e40
--- /dev/null
+++ b/mathics/eval/numbers/calculus/projective_integrator.py
@@ -0,0 +1,1130 @@
+# -*- coding: utf-8 -*-
+"""
+Projective Calculus Engine over Q(i, sqrt(d-1)) and Riemann Sphere P^1(C) for Mathics3.
+
+Implements:
+ 1. Ostrowski-Hermite rational reduction + Lagrange-Rothstein-Trager conjugate pole pairing
+ over Q(i, sqrt(d-1)).
+ 2. Fractional trigonometric rationalization t = tan(a*x + b)^(1/q) and Weierstrass
+ stereographic rationalization on P^1 for trigonometric rational integrands.
+ 3. Exact Pade approximants [m/n] (`eval_pade_approximant`) via Toeplitz linear systems.
+ 4. Complex Cauchy-Lagrange residues on the Riemann sphere P^1(C) (`eval_residue`),
+ including the point at infinity z_0 = oo = [1 : 0].
+ 5. Closed contour integration (`eval_contour_integrate`) on P^1(C) around circles |z - z_0| = r.
+ 6. Projective trigonometric identity reduction (`eval_trig_reduce`) on P^1.
+"""
+
+from __future__ import annotations
+
+from typing import Optional, Tuple
+import sympy as sp
+
+
+def hermite_reduce_sympy(
+ num: sp.Expr, den: sp.Expr, var: sp.Symbol
+) -> Tuple[sp.Expr, sp.Expr, sp.Expr, sp.Expr, sp.Expr]:
+ """Perform exact Ostrowski-Hermite reduction on P(var)/Q(var) purely via polynomial GCD.
+
+ Returns (poly_part, poly_antideriv, hermite_rat, rem_num, sqfree_den) such that:
+ int (P(var)/Q(var)) d(var) = poly_antideriv + hermite_rat + int (rem_num / sqfree_den) d(var).
+ """
+ num_p = sp.Poly(sp.expand(num), var)
+ den_p = sp.Poly(sp.expand(den), var)
+ sqf_coeff, sqf_factors = sp.sqf_list(den_p.as_expr(), var)
+ num_expr = sp.simplify(num_p.as_expr() / sqf_coeff)
+ den_expr = sp.Integer(1)
+ for fac, mult in sqf_factors:
+ den_expr = sp.expand(den_expr * (fac**mult))
+
+ q_poly, r_poly = sp.div(sp.Poly(num_expr, var), sp.Poly(den_expr, var), var)
+ poly_part = q_poly.as_expr()
+ poly_antideriv = sp.integrate(poly_part, var)
+ if r_poly.is_zero:
+ return poly_part, poly_antideriv, sp.Integer(0), sp.Integer(0), sp.Integer(1)
+
+ mult_map: dict[int, sp.Expr] = {}
+ max_m = 1
+ for fac, mult in sqf_factors:
+ mult_map[mult] = sp.expand(mult_map.get(mult, sp.Integer(1)) * fac)
+ if mult > max_m:
+ max_m = mult
+
+ a_cur = r_poly.as_expr()
+ hermite_acc = sp.Integer(0)
+
+ while max_m > 1:
+ v_m = mult_map.pop(max_m)
+ u_other = sp.Integer(1)
+ for k_mult, k_fac in mult_map.items():
+ u_other = sp.expand(u_other * (k_fac**k_mult))
+
+ v_m_diff = sp.diff(v_m, var)
+ w_poly = sp.expand(u_other * v_m_diff)
+ scaled_a = sp.expand(a_cur / sp.Rational(1 - max_m))
+ s_bez, _, g_bez = sp.gcdex(sp.Poly(w_poly, var), sp.Poly(v_m, var))
+ g_expr = g_bez.as_expr()
+ b_full = sp.Poly(sp.expand(s_bez.as_expr() * scaled_a / g_expr), var)
+ _, b_rem = sp.div(b_full, sp.Poly(v_m, var), var)
+ b_expr = b_rem.as_expr()
+
+ c_quo, _ = sp.div(
+ sp.Poly(sp.expand(scaled_a - b_expr * w_poly), var),
+ sp.Poly(v_m, var),
+ var,
+ )
+ c_expr = c_quo.as_expr()
+
+ hermite_acc = sp.together(hermite_acc + b_expr / (v_m ** (max_m - 1)))
+ a_cur = sp.expand((1 - max_m) * c_expr - u_other * sp.diff(b_expr, var))
+ mult_map[max_m - 1] = sp.expand(
+ mult_map.get(max_m - 1, sp.Integer(1)) * v_m
+ )
+ max_m -= 1
+ while max_m > 1 and max_m not in mult_map:
+ max_m -= 1
+
+ sqfree_den = sp.expand(mult_map.get(1, sp.Integer(1)))
+ return (
+ poly_part,
+ poly_antideriv,
+ sp.cancel(hermite_acc),
+ sp.expand(a_cur),
+ sqfree_den,
+ )
+
+
+def _exact_biquadratic_roots(fac: sp.Expr, var: sp.Symbol) -> Optional[list[sp.Expr]]:
+ """Extract exact roots over Q(i, sqrt(d-1)) for degree <= 2, binomials a*t^4 + b,
+ and biquadratic polynomials a*t^4 + b*t^2 + c.
+ """
+ poly = sp.Poly(fac, var)
+ deg = poly.degree()
+ if deg == 0:
+ return []
+ if deg == 1:
+ a1, a0 = poly.all_coeffs()
+ return [sp.simplify(-a0 / a1)]
+ if deg == 2:
+ a2, a1, a0 = poly.all_coeffs()
+ disc = sp.simplify(a1 * a1 - 4 * a2 * a0)
+ sd = sp.sqrt(disc)
+ return [
+ sp.simplify((-a1 + sd) / (2 * a2)),
+ sp.simplify((-a1 - sd) / (2 * a2)),
+ ]
+ if deg == 4:
+ c4, c3, c2, c1, c0 = poly.all_coeffs()
+ if c3 == 0 and c1 == 0:
+ if c2 == 0:
+ rhs = sp.simplify(-c0 / c4)
+ if rhs.is_negative:
+ r4 = sp.simplify((-rhs) ** sp.Rational(1, 4))
+ s2 = sp.sqrt(2) / 2
+ return [
+ sp.simplify(r4 * s2 * (1 + sp.I)),
+ sp.simplify(r4 * s2 * (-1 + sp.I)),
+ sp.simplify(r4 * s2 * (-1 - sp.I)),
+ sp.simplify(r4 * s2 * (1 - sp.I)),
+ ]
+ if rhs.is_positive:
+ r4 = sp.simplify(rhs ** sp.Rational(1, 4))
+ return [r4, -r4, sp.I * r4, -sp.I * r4]
+ disc2 = sp.simplify(c2 * c2 - 4 * c4 * c0)
+ if disc2.is_number and disc2.is_real:
+ if disc2 >= 0:
+ u1 = sp.simplify((-c2 + sp.sqrt(disc2)) / (2 * c4))
+ u2 = sp.simplify((-c2 - sp.sqrt(disc2)) / (2 * c4))
+ out: list[sp.Expr] = []
+ for u_val in (u1, u2):
+ su = sp.sqrt(u_val)
+ out.append(sp.simplify(su))
+ out.append(sp.simplify(-su))
+ return out
+ if c4 > 0 and c0 > 0:
+ # Explicit real-imaginary decomposition of the 4 roots +/- u_re +/- I * u_im:
+ r_mod = sp.sqrt(sp.simplify(c0 / c4))
+ half_b = sp.simplify(c2 / (2 * c4))
+ u_re = sp.sqrt(sp.simplify((r_mod - half_b) / 2))
+ u_im = sp.sqrt(sp.simplify((r_mod + half_b) / 2))
+ return [
+ u_re + sp.I * u_im,
+ -u_re + sp.I * u_im,
+ -u_re - sp.I * u_im,
+ u_re - sp.I * u_im,
+ ]
+ return None
+
+
+def integrate_rational_projective(expr: sp.Expr, var: sp.Symbol) -> Optional[sp.Expr]:
+ """Integrate a rational function P(var)/Q(var) over Q(i, sqrt(d-1)) into elementary real
+ Log and ArcTan functions without RootSum.
+ """
+ if not expr.is_rational_function(var):
+ return None
+ cancelled = sp.cancel(expr)
+ num, den = sp.fraction(cancelled)
+ if not num.is_polynomial(var) or not den.is_polynomial(var):
+ return None
+ if sp.Poly(den, var).degree() <= 0:
+ return sp.integrate(cancelled, var)
+
+ _, poly_antideriv, hermite_rat, rem_num, sqfree_den = hermite_reduce_sympy(
+ num, den, var
+ )
+ poles_residues: list[Tuple[sp.Expr, sp.Expr]] = []
+ if rem_num != 0 and sqfree_den != 1:
+ den_diff = sp.diff(sqfree_den, var)
+ _, fac_list = sp.factor_list(sqfree_den, var)
+ for fac, _ in fac_list:
+ roots = _exact_biquadratic_roots(fac, var)
+ if roots is None:
+ return None
+ for r_sym in roots:
+ res_sym = sp.simplify(
+ rem_num.subs(var, r_sym) / den_diff.subs(var, r_sym)
+ )
+ poles_residues.append((r_sym, res_sym))
+
+ log_atan_expr = sp.Integer(0)
+ used = [False] * len(poles_residues)
+ for i, (p_i, c_i) in enumerate(poles_residues):
+ if used[i]:
+ continue
+ p_re, p_im = sp.expand(p_i).as_real_imag()
+ c_re, c_im = sp.expand(c_i).as_real_imag()
+ if p_im == 0:
+ used[i] = True
+ log_atan_expr += sp.simplify(c_re) * sp.log(var - p_re)
+ continue
+
+ partner = None
+ for j in range(i + 1, len(poles_residues)):
+ if used[j]:
+ continue
+ q_re, q_im = sp.expand(poles_residues[j][0]).as_real_imag()
+ if sp.simplify(p_re - q_re) == 0 and sp.simplify(p_im + q_im) == 0:
+ partner = j
+ break
+
+ if partner is not None and p_im.is_positive:
+ used[i] = True
+ used[partner] = True
+ d_re, d_im = sp.expand(poles_residues[partner][1]).as_real_imag()
+ if sp.simplify(c_re - d_re) == 0 and sp.simplify(c_im + d_im) == 0:
+ quad_arg = sp.expand((var - p_re) ** 2 + p_im**2)
+ atan_arg = sp.simplify((var - p_re) / p_im)
+ if c_re != 0:
+ log_atan_expr += sp.simplify(c_re) * sp.log(quad_arg)
+ if c_im != 0:
+ log_atan_expr -= sp.simplify(2 * c_im) * sp.atan(atan_arg)
+ continue
+ return None
+
+ primitive = poly_antideriv + hermite_rat + log_atan_expr
+ return primitive
+
+
+def integrate_fractional_trig_projective(
+ expression: sp.Expr, variable: sp.Symbol
+) -> Optional[sp.Expr]:
+ """Integrate fractional powers of tan(a*x+b) or cot(a*x+b) via projective substitution
+ t = trig(a*x+b)^(1/q) on P^1(Q(i, sqrt(2))).
+ """
+ if not isinstance(variable, sp.Symbol) or expression.free_symbols - {variable}:
+ return None
+ trigs = [
+ term
+ for term in expression.atoms(sp.tan, sp.cot)
+ if term.has(variable)
+ ]
+ if len(trigs) != 1:
+ return None
+ trig = trigs[0]
+ argument = trig.args[0]
+ slope = sp.diff(argument, variable)
+ offset = sp.simplify(argument - slope * variable)
+ if (
+ slope.has(variable)
+ or offset.has(variable)
+ or not slope.is_number
+ or slope.is_zero
+ ):
+ return None
+ frac_pows = [
+ p
+ for p in expression.atoms(sp.Pow)
+ if p.base in (trig, -trig) and p.exp.is_Rational and p.exp.q > 1
+ ]
+ if not frac_pows:
+ return None
+ root_signs = {1 if p.base == trig else -1 for p in frac_pows}
+ if len(root_signs) != 1:
+ return None
+ root_sign = root_signs.pop()
+ root_base = root_sign * trig
+ denoms = [int(p.exp.q) for p in frac_pows]
+ if any(d_val > 4 for d_val in denoms):
+ return None
+ q = int(sp.ilcm(1, *denoms))
+ if not (2 <= q <= 4):
+ return None
+
+ t = sp.Dummy("t_proj", positive=True)
+ transformed = expression.subs(trig, root_sign * (t**q))
+ if transformed.has(variable) or not transformed.is_rational_function(t):
+ return None
+ sign = 1 if trig.func == sp.tan else -1
+ rat_integrand = sp.cancel(
+ root_sign * sign * q * (t ** (q - 1)) * transformed / (slope * (1 + t ** (2 * q)))
+ )
+ prim_t = integrate_rational_projective(rat_integrand, t)
+ if prim_t is None:
+ prim_t = sp.integrate(rat_integrand, t)
+ if prim_t is None or prim_t.has(sp.Integral, sp.RootSum):
+ return None
+ if sp.cancel(sp.diff(prim_t, t) - rat_integrand) != 0:
+ return None
+ return prim_t.subs(t, root_base ** sp.Rational(1, q))
+
+
+def integrate_weierstrass_projective(
+ expression: sp.Expr, variable: sp.Symbol
+) -> Optional[sp.Expr]:
+ """Integrate rational functions of sin(x), cos(x), tan(x) via stereographic lift
+ t = tan(x/2) onto P^1(Q(i, sqrt(d-1))) when degree in t is <= 4.
+ """
+ if not isinstance(variable, sp.Symbol) or expression.free_symbols - {variable}:
+ return None
+ if not expression.has(sp.sin, sp.cos, sp.tan, sp.cot, sp.sec, sp.csc):
+ return None
+ # Check if expression is a function of sin(x)^2, cos(x)^2, tan(x) -> substitute u = tan(x), dx = du/(1+u^2)
+ u = sp.Dummy("u_tan", real=True)
+ # Try double-angle rational substitution u = tan(x): sin(x)^2 = u^2/(1+u^2), cos(x)^2 = 1/(1+u^2), sin(2x) = 2u/(1+u^2), cos(2x) = (1-u^2)/(1+u^2)
+ expr_tan = expression.subs(
+ {
+ sp.sin(variable) ** 2: u**2 / (1 + u**2),
+ sp.sin(variable) ** 4: (u**4) / ((1 + u**2) ** 2),
+ sp.cos(variable) ** 2: 1 / (1 + u**2),
+ sp.cos(variable) ** 4: 1 / ((1 + u**2) ** 2),
+ sp.tan(variable): u,
+ sp.cot(variable): 1 / u,
+ sp.sin(2 * variable): 2 * u / (1 + u**2),
+ sp.cos(2 * variable): (1 - u**2) / (1 + u**2),
+ }
+ )
+ if not expr_tan.has(variable) and expr_tan.is_rational_function(u):
+ rat_u = sp.cancel(expr_tan / (1 + u**2))
+ prim_u = integrate_rational_projective(rat_u, u)
+ if prim_u is not None and not prim_u.has(sp.Integral, sp.RootSum):
+ return prim_u.subs(u, sp.tan(variable))
+
+ # General Weierstrass substitution t = tan(x/2)
+ t = sp.Dummy("t_weier", real=True)
+ expr_w = expression.subs(
+ {
+ sp.sin(variable): 2 * t / (1 + t**2),
+ sp.cos(variable): (1 - t**2) / (1 + t**2),
+ sp.tan(variable): 2 * t / (1 - t**2),
+ sp.cot(variable): (1 - t**2) / (2 * t),
+ sp.sec(variable): (1 + t**2) / (1 - t**2),
+ sp.csc(variable): (1 + t**2) / (2 * t),
+ }
+ )
+ if not expr_w.has(variable) and expr_w.is_rational_function(t):
+ rat_t = sp.cancel(expr_w * 2 / (1 + t**2))
+ _, den_t = sp.fraction(rat_t)
+ if sp.Poly(den_t, t).degree() <= 4:
+ prim_t = integrate_rational_projective(rat_t, t)
+ if prim_t is not None and not prim_t.has(sp.Integral, sp.RootSum):
+ return prim_t.subs(t, sp.tan(variable / 2))
+ return None
+
+
+def eval_projective_integrate(f_sympy: sp.Expr, vars_spec: list) -> Optional[sp.Expr]:
+ """Pre-SymPy projective integration fast-path for Mathics3 `Integrate`.
+
+ Intercepts:
+ 1. Fractional trigonometric integrals `Integrate[Sqrt[Tan[x]], x]` where SymPy fails.
+ 2. Quartic/even trigonometric integrals `Integrate[1/(1 + Sin[x]^4), x]` where SymPy Risch hangs.
+ """
+ if len(vars_spec) != 1:
+ return None
+ spec = vars_spec[0]
+ if isinstance(spec, sp.Symbol):
+ res = integrate_fractional_trig_projective(f_sympy, spec)
+ if res is not None:
+ return res
+ if any(
+ p.base in (sp.sin(spec), sp.cos(spec))
+ and p.exp.is_Integer
+ and int(p.exp) >= 4
+ for p in f_sympy.atoms(sp.Pow)
+ ):
+ res = integrate_weierstrass_projective(f_sympy, spec)
+ if res is not None:
+ return res
+ return None
+
+
+def eval_pade_approximant(
+ f_sympy: sp.Expr, var: sp.Symbol, x0: sp.Expr, m: int, n: int
+) -> Optional[sp.Expr]:
+ """Compute exact Pade approximant [m / n] of `f_sympy` around `var = x0`."""
+ if m < 0 or n < 0:
+ return None
+ dx = sp.Dummy("dx_pade")
+ shifted = f_sympy.subs(var, x0 + dx)
+ order = m + n
+ try:
+ ser = sp.series(shifted, dx, 0, order + 1).removeO()
+ except Exception:
+ return None
+
+ c = [sp.simplify(ser.coeff(dx, k)) for k in range(order + 1)]
+ c[0] = sp.simplify(ser.subs(dx, 0))
+
+ if n == 0:
+ return sp.expand(sum(c[k] * ((var - x0) ** k) for k in range(m + 1)))
+
+ mat_rows = []
+ rhs_rows = []
+ for k in range(m + 1, m + n + 1):
+ row = []
+ for j in range(1, n + 1):
+ idx = k - j
+ row.append(c[idx] if idx >= 0 else sp.Integer(0))
+ mat_rows.append(row)
+ rhs_rows.append(-c[k])
+
+ try:
+ mat = sp.Matrix(mat_rows)
+ rhs = sp.Matrix(rhs_rows)
+ b_sol = mat.LUsolve(rhs)
+ except Exception:
+ return None
+
+ b_coeffs = [sp.Integer(1)] + [sp.simplify(b_sol[j]) for j in range(n)]
+ a_coeffs = []
+ for k in range(m + 1):
+ ak = sp.Integer(0)
+ for j in range(min(k, n) + 1):
+ ak += b_coeffs[j] * c[k - j]
+ a_coeffs.append(sp.simplify(ak))
+
+ u_var = var - x0
+ num_expr = sum(a_coeffs[k] * (u_var**k) for k in range(m + 1))
+ den_expr = sum(b_coeffs[j] * (u_var**j) for j in range(n + 1))
+ return sp.cancel(num_expr / den_expr)
+
+
+def eval_residue_projective(
+ f_sympy: sp.Expr, var: sp.Symbol, z0: sp.Expr
+) -> Optional[sp.Expr]:
+ """Compute complex Cauchy-Lagrange residue Res_{var = z0} f(var) on the Riemann sphere P^1(C),
+ including the projective point at infinity z0 = oo = [1 : 0].
+ """
+ try:
+ if z0 is sp.oo or z0 is -sp.oo or z0 is sp.zoo:
+ w = sp.Dummy("w_inf")
+ inv_expr = (-1 / (w**2)) * f_sympy.subs(var, 1 / w)
+ return sp.simplify(sp.residue(inv_expr, w, 0))
+ return sp.simplify(sp.residue(f_sympy, var, z0))
+ except Exception:
+ return None
+
+
+def eval_contour_integrate_projective(
+ f_sympy: sp.Expr, var: sp.Symbol, center: sp.Expr, radius: sp.Expr
+) -> Optional[sp.Expr]:
+ """Compute closed contour integral oint_{|var - center| = radius} f(var) d(var) on P^1(C)
+ via Ostrowski-Hermite reduction (eliminating zero-residue repeated-pole derivatives)
+ and Lagrange-Rothstein-Trager residues over Q(i, sqrt(d-1)).
+ """
+ if not f_sympy.is_rational_function(var):
+ return None
+ r_val = sp.N(radius)
+ if not r_val.is_real or float(r_val) <= 0:
+ return None
+ r_float = float(r_val)
+ c_complex = complex(sp.N(center))
+
+ cancelled = sp.cancel(f_sympy)
+ num, den = sp.fraction(cancelled)
+ _, _, _, rem_num, sqfree_den = hermite_reduce_sympy(num, den, var)
+ if rem_num == 0 or sqfree_den == 1:
+ return sp.Integer(0)
+
+ den_diff = sp.diff(sqfree_den, var)
+ _, fac_list = sp.factor_list(sqfree_den, var)
+
+ res_sum = sp.Integer(0)
+ for fac, _ in fac_list:
+ roots = _exact_biquadratic_roots(fac, var)
+ if roots is None:
+ r_dict = sp.roots(sp.Poly(fac, var))
+ if sum(r_dict.values()) != sp.Poly(fac, var).degree():
+ return None
+ roots = []
+ for r_k, mult in r_dict.items():
+ roots.extend([r_k] * mult)
+ for r_sym in roots:
+ dist = abs(complex(sp.N(r_sym)) - c_complex)
+ if abs(dist - r_float) < 1e-9:
+ # Pole lies on contour
+ return None
+ if dist < r_float:
+ res_k = sp.simplify(
+ rem_num.subs(var, r_sym) / den_diff.subs(var, r_sym)
+ )
+ res_sum += res_k
+
+ return sp.simplify(2 * sp.pi * sp.I * res_sum)
+
+
+def eval_trig_reduce_projective(f_sympy: sp.Expr) -> Optional[sp.Expr]:
+ """Projective trigonometric and hyperbolic reduction on P^1.
+
+ Expands multiple-angle harmonies and reduces products/powers via TR8.
+ """
+ from sympy.simplify.fu import TR8
+
+ try:
+ expanded_angles = sp.expand_trig(f_sympy)
+ reduced = sp.expand(TR8(expanded_angles))
+ return sp.Integer(0) if sp.simplify(reduced) == 0 else reduced
+ except Exception:
+ return None
+
+
+def eval_trig_expand_projective(f_sympy: sp.Expr) -> Optional[sp.Expr]:
+ """Expand trigonometric functions of sums and multiple angles via Chebyshev-Cayley expansion."""
+ try:
+ return sp.expand(sp.expand_trig(f_sympy))
+ except Exception:
+ return None
+
+
+def eval_trig_factor_projective(f_sympy: sp.Expr) -> Optional[sp.Expr]:
+ """Factor trigonometric sums/polynomials via projective Weierstrass lift and Fu sum-to-product rules."""
+ from sympy.simplify.fu import TR10i, fu
+
+ try:
+ # First try sum-to-product and Fu factorization
+ res = sp.factor(TR10i(sp.expand_trig(f_sympy)))
+ cand = fu(f_sympy)
+ if cand.is_Mul and not res.is_Mul:
+ return cand
+ return res
+ except Exception:
+ return None
+
+
+def eval_trig_to_exp_projective(f_sympy: sp.Expr) -> Optional[sp.Expr]:
+ """Convert trigonometric and hyperbolic functions to complex exponentials on P^1(Q(i))."""
+ try:
+ return sp.expand(f_sympy.rewrite(sp.exp))
+ except Exception:
+ return None
+
+
+def eval_exp_to_trig_projective(f_sympy: sp.Expr) -> Optional[sp.Expr]:
+ """Convert complex exponentials exp(i*z) to trigonometric functions (Cos, Sin, Cosh, Sinh)."""
+ try:
+ return sp.simplify(f_sympy.rewrite(sp.cos))
+ except Exception:
+ return None
+
+
+def eval_dyadic_pi_cos_sin(p_num: int, two_pow_q: int) -> Optional[Tuple[sp.Expr, sp.Expr]]:
+ """Compute exact nested-radical values (Cos[p*Pi / 2^k], Sin[p*Pi / 2^k]) for any dyadic denominator 2^k >= 8
+ via the projective half-angle recursion over Q(sqrt(2)):
+ cos(theta / 2) = sqrt((1 + cos(theta)) / 2),
+ sin(theta / 2) = sqrt((1 - cos(theta)) / 2).
+ """
+ if two_pow_q <= 0 or (two_pow_q & (two_pow_q - 1)) != 0:
+ return None
+
+ # Reduce angle modulo 2*pi -> p_mod in [0, 2 * two_pow_q)
+ period = 2 * two_pow_q
+ p_mod = p_num % period
+ sign_c = 1
+ sign_s = 1
+
+ # Reduce from [0, 2*pi) to [0, pi]
+ if p_mod > two_pow_q:
+ p_mod = period - p_mod
+ sign_s = -sign_s
+ # Reduce from [0, pi] to [0, pi/2]
+ half_q = two_pow_q // 2
+ if p_mod > half_q:
+ p_mod = two_pow_q - p_mod
+ sign_c = -sign_c
+ # Reduce from [0, pi/2] to [0, pi/4] using swap(cos, sin)
+ quarter_q = two_pow_q // 4
+ swapped = False
+ if p_mod > quarter_q:
+ p_mod = half_q - p_mod
+ swapped = True
+
+ # Recursive half-angle solver on [0, pi/2] for dyadic fraction m / 2^k:
+ def _dyadic_first_quad(m_val: int, q_val: int) -> Tuple[sp.Expr, sp.Expr]:
+ if m_val == 0:
+ return sp.Integer(1), sp.Integer(0)
+ while m_val % 2 == 0 and q_val % 2 == 0:
+ m_val //= 2
+ q_val //= 2
+ if q_val == 1:
+ # m_val == 1 -> pi
+ return sp.Integer(-1), sp.Integer(0)
+ if q_val == 2:
+ # pi / 2
+ return sp.Integer(0), sp.Integer(1)
+ if q_val == 4:
+ # pi / 4
+ s2 = sp.sqrt(2) / 2
+ return s2, s2
+ # General q_val = 2^k >= 8 with odd m_val < q_val / 2:
+ # Angle is (m_val * pi / (q_val / 2)) / 2.
+ # Compute c_double = cos(m_val * pi / (q_val // 2)) in [0, pi]:
+ half_denom = q_val // 2
+ if m_val <= half_denom // 2:
+ c_dbl, _ = _dyadic_first_quad(m_val, half_denom)
+ else:
+ c_supp, _ = _dyadic_first_quad(half_denom - m_val, half_denom)
+ c_dbl = -c_supp
+ c_half = sp.sqrt((1 + c_dbl) / sp.Integer(2))
+ s_half = sp.sqrt((1 - c_dbl) / sp.Integer(2))
+ return c_half, s_half
+
+ c_base, s_base = _dyadic_first_quad(p_mod, two_pow_q)
+ if swapped:
+ c_base, s_base = s_base, c_base
+ return sign_c * c_base, sign_s * s_base
+
+
+def eval_laplace_transform_projective(
+ f_sympy: sp.Expr, t_var: sp.Symbol, s_var: sp.Symbol
+) -> Optional[sp.Expr]:
+ """Compute LaplaceTransform[f(t), t, s] = int_0^oo f(t) exp(-s*t) dt."""
+ try:
+ res = sp.laplace_transform(f_sympy, t_var, s_var, noconds=True)
+ if res is not None and not res.has(sp.LaplaceTransform):
+ return sp.cancel(res) if res.is_rational_function(s_var) else res
+ return None
+ except Exception:
+ return None
+
+
+def eval_inverse_laplace_transform_projective(
+ F_sympy: sp.Expr, s_var: sp.Symbol, t_var: sp.Symbol
+) -> Optional[sp.Expr]:
+ """Compute InverseLaplaceTransform[F(s), s, t] = (1/(2*pi*i)) oint_gamma F(s) exp(s*t) ds
+ via Riesz-Dunford-Lagrange pole decomposition over Q(i, sqrt(d-1)) for proper rational resolvents,
+ with fallback to SymPy inverse_laplace_transform.
+ """
+ if F_sympy.is_rational_function(s_var):
+ cancelled = sp.cancel(F_sympy)
+ num, den = sp.fraction(cancelled)
+ if num.is_polynomial(s_var) and den.is_polynomial(s_var):
+ deg_n = sp.Poly(num, s_var).degree() if num != 0 else 0
+ deg_d = sp.Poly(den, s_var).degree()
+ if 0 < deg_d and deg_n < deg_d:
+ _, sqf_facs = sp.sqf_list(den, s_var)
+ # Fast exact Lagrange residue path for simple poles over Q(i, sqrt(d-1)):
+ if all(mult == 1 for _, mult in sqf_facs):
+ den_diff = sp.diff(den, s_var)
+ _, fac_list = sp.factor_list(den, s_var)
+ poles_res: list[Tuple[sp.Expr, sp.Expr]] = []
+ ok_exact = True
+ for fac, _ in fac_list:
+ roots = _exact_biquadratic_roots(fac, s_var)
+ if roots is None:
+ ok_exact = False
+ break
+ for r_sym in roots:
+ c_sym = sp.simplify(
+ num.subs(s_var, r_sym) / den_diff.subs(s_var, r_sym)
+ )
+ poles_res.append((r_sym, c_sym))
+ if ok_exact:
+ time_evol = sp.Integer(0)
+ used = [False] * len(poles_res)
+ for i, (p_i, c_i) in enumerate(poles_res):
+ if used[i]:
+ continue
+ p_re, p_im = sp.expand(p_i).as_real_imag()
+ c_re, c_im = sp.expand(c_i).as_real_imag()
+ if p_im == 0:
+ used[i] = True
+ time_evol += sp.simplify(c_re) * sp.exp(p_re * t_var)
+ continue
+ partner = None
+ for j in range(i + 1, len(poles_res)):
+ if used[j]:
+ continue
+ q_re, q_im = sp.expand(poles_res[j][0]).as_real_imag()
+ if (
+ sp.simplify(p_re - q_re) == 0
+ and sp.simplify(p_im + q_im) == 0
+ ):
+ partner = j
+ break
+ if partner is not None and p_im.is_positive:
+ used[i] = True
+ used[partner] = True
+ d_re, d_im = sp.expand(
+ poles_res[partner][1]
+ ).as_real_imag()
+ if (
+ sp.simplify(c_re - d_re) == 0
+ and sp.simplify(c_im + d_im) == 0
+ ):
+ # c * exp((p_re + i*p_im)*t) + conj(c) * exp((p_re - i*p_im)*t)
+ # = exp(p_re * t) * (2*c_re*cos(p_im*t) - 2*c_im*sin(p_im*t))
+ env = sp.exp(p_re * t_var)
+ osc = sp.Integer(0)
+ if c_re != 0:
+ osc += sp.simplify(2 * c_re) * sp.cos(
+ p_im * t_var
+ )
+ if c_im != 0:
+ osc -= sp.simplify(2 * c_im) * sp.sin(
+ p_im * t_var
+ )
+ time_evol += env * osc
+ continue
+ ok_exact = False
+ break
+ if ok_exact:
+ return sp.expand(time_evol)
+
+ try:
+ res = sp.inverse_laplace_transform(F_sympy, s_var, t_var)
+ if res is not None and not res.has(sp.InverseLaplaceTransform):
+ return sp.simplify(res.subs(sp.Heaviside(t_var), 1))
+ return None
+ except Exception:
+ return None
+
+
+def eval_stieltjes_pade_resolvent(
+ moments_sympy: list[sp.Expr], z_var: sp.Symbol
+) -> Optional[sp.Expr]:
+ """Construct the exact [N-1 / N] Stieltjes-Pade projective resolvent G_N(z) = P_{N-1}(z) / Q_N(z)
+ on P^1(C) from 2N power moments [mu_0, mu_1, ..., mu_{2N-1}] of a Hilbert-space operator L.
+ """
+ if len(moments_sympy) < 2 or len(moments_sympy) % 2 != 0:
+ return None
+ n_order = len(moments_sympy) // 2
+ hankel_rows = []
+ rhs_rows = []
+ for i in range(n_order):
+ row = [moments_sympy[i + j] for j in range(n_order)]
+ hankel_rows.append(row)
+ rhs_rows.append(-moments_sympy[i + n_order])
+ try:
+ h_mat = sp.Matrix(hankel_rows)
+ rhs_vec = sp.Matrix(rhs_rows)
+ c_sol = h_mat.LUsolve(rhs_vec)
+ except Exception:
+ return None
+
+ q_coeffs = [sp.simplify(c_sol[j]) for j in range(n_order)] + [sp.Integer(1)]
+ den_poly = sum(q_coeffs[j] * (z_var**j) for j in range(n_order + 1))
+
+ num_poly = sp.Integer(0)
+ for m_deg in range(n_order):
+ pm = sp.Integer(0)
+ for k in range(n_order - m_deg):
+ pm += q_coeffs[m_deg + 1 + k] * moments_sympy[k]
+ num_poly += sp.simplify(pm) * (z_var**m_deg)
+
+ return sp.cancel(num_poly / den_poly)
+
+
+# ---------------------------------------------------------------------------
+# 10. Non-circular Pure-Rational Projective Mathematical Constants (0 mpmath)
+# ---------------------------------------------------------------------------
+
+from decimal import Decimal, localcontext
+from fractions import Fraction
+import math as _pymath
+
+
+def _heron_sqrt_decimal(x_val: Decimal | int | Fraction, digits: int = 50) -> Decimal:
+ """Compute sqrt(x) on R>=0 via pure Heron-Newton rational iteration r_{k+1} = (r_k + x/r_k)/2."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ val = (
+ Decimal(x_val.numerator) / Decimal(x_val.denominator)
+ if isinstance(x_val, Fraction)
+ else Decimal(x_val)
+ )
+ if val <= 0:
+ return Decimal(0)
+ exp10 = val.adjusted()
+ r = Decimal(2) * (Decimal(10) ** (exp10 // 2))
+ r = (r + val / r) / Decimal(2)
+ tol = Decimal(10) ** (-(digits + 18))
+ max_steps = int(_pymath.ceil(_pymath.log2(work_prec))) + 10
+ two = Decimal(2)
+ for _ in range(max_steps):
+ r_next = (r + val / r) / two
+ if abs(r_next - r) <= abs(r_next) * tol:
+ r = r_next
+ break
+ r = r_next
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +r
+
+
+def _projective_atan_decimal(t_val: Decimal | int | Fraction, digits: int = 50) -> Decimal:
+ """Compute arctan(t) on R via projective half-angle descent + diagonal (5, 5) Cayley-Pade."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ u = (
+ Decimal(t_val.numerator) / Decimal(t_val.denominator)
+ if isinstance(t_val, Fraction)
+ else Decimal(t_val)
+ )
+ if u == 0:
+ return Decimal(0)
+ sign = Decimal(-1) if u < 0 else Decimal(1)
+ u = abs(u)
+ m_steps = max(int(_pymath.ceil((digits + 20) * 3.321928 / 9.5)) + 3, 10)
+ one = Decimal(1)
+ for _ in range(m_steps):
+ u = u / (one + _heron_sqrt_decimal(one + u * u, work_prec))
+ u2 = u * u
+ u4 = u2 * u2
+ num = u * (Decimal(945) + Decimal(735) * u2 + Decimal(64) * u4)
+ den = Decimal(945) + Decimal(1050) * u2 + Decimal(225) * u4
+ res = sign * (Decimal(2) ** m_steps) * (num / den)
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +res
+
+
+def _projective_log_positive_decimal(x_val: Decimal | int | Fraction, digits: int = 50) -> Decimal:
+ """Compute Log_P(x) for x > 0 via Heron square-root descent + Cayley map w=(z-1)/(z+1) + Pade (5, 5)."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ cur = (
+ Decimal(x_val.numerator) / Decimal(x_val.denominator)
+ if isinstance(x_val, Fraction)
+ else Decimal(x_val)
+ )
+ mag_exp = abs(int(cur.adjusted()))
+ m_steps = (
+ max(int(_pymath.ceil((digits + 20) * 3.321928 / 9.5)) + 5, 12)
+ + int(_pymath.ceil(_pymath.log2(mag_exp + 2)))
+ + 2
+ )
+ for _ in range(m_steps):
+ cur = _heron_sqrt_decimal(cur, work_prec)
+ w = (cur - Decimal(1)) / (cur + Decimal(1))
+ w2 = w * w
+ w4 = w2 * w2
+ num = Decimal(2) * w * (Decimal(945) - Decimal(735) * w2 + Decimal(64) * w4)
+ den = Decimal(945) - Decimal(1050) * w2 + Decimal(225) * w4
+ res = (Decimal(2) ** m_steps) * (num / den)
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +res
+
+
+def projective_pi_decimal(digits: int = 50) -> Decimal:
+ """Non-circular projective Pi via Gaussian factorization (5+i)^4 (239-i) = 114244(1+i) in Z[i]."""
+ work_prec = digits + 20
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ a1 = _projective_atan_decimal(Fraction(1, 5), work_prec)
+ a2 = _projective_atan_decimal(Fraction(1, 239), work_prec)
+ pi_val = Decimal(16) * a1 - Decimal(4) * a2
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +pi_val
+
+
+def projective_e_decimal(digits: int = 50) -> Decimal:
+ """Non-circular projective Euler's number e via dyadic halving u = 1/2^m + (5, 5) Cayley-Pade."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ m_steps = max(int(_pymath.ceil((digits + 20) * 3.321928 / 9.5)) + 4, 12)
+ u = Decimal(1) / (Decimal(2) ** m_steps)
+ u2 = u * u
+ u3 = u2 * u
+ u4 = u2 * u2
+ u5 = u4 * u
+ even_p = Decimal(30240) + Decimal(3360) * u2 + Decimal(30) * u4
+ odd_p = Decimal(15120) * u + Decimal(420) * u3 + u5
+ cur = (even_p + odd_p) / (even_p - odd_p)
+ for _ in range(m_steps):
+ cur = cur * cur
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +cur
+
+
+def projective_ln2_decimal(digits: int = 50) -> Decimal:
+ """Non-circular projective ln(2) = Log_P(2)."""
+ return _projective_log_positive_decimal(2, digits=digits)
+
+
+def projective_golden_ratio_decimal(digits: int = 50) -> Decimal:
+ """Projective golden ratio phi = (1 + sqrt(5)) / 2 via Heron-Newton iteration."""
+ work_prec = digits + 15
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ val = (Decimal(1) + _heron_sqrt_decimal(5, work_prec)) / Decimal(2)
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +val
+
+
+def projective_lemniscate_varpi_decimal(digits: int = 50) -> Decimal:
+ """Gauss's lemniscate constant varpi = pi / AGM(1, sqrt(2)) over Q(sqrt(2)) (d = 3)."""
+ work_prec = digits + 20
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ pi_val = projective_pi_decimal(work_prec)
+ a = Decimal(1)
+ b = _heron_sqrt_decimal(2, work_prec)
+ two = Decimal(2)
+ for _ in range(int(_pymath.ceil(_pymath.log2(work_prec))) + 4):
+ a_next = (a + b) / two
+ b_next = _heron_sqrt_decimal(a * b, work_prec)
+ if abs(a_next - b_next) <= Decimal(10) ** (-(digits + 15)):
+ a = a_next
+ break
+ a, b = a_next, b_next
+ varpi = pi_val / a
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +varpi
+
+
+def projective_gamma_quarter_decimal(digits: int = 50) -> Decimal:
+ """Gamma(1/4) = sqrt(2 * varpi * sqrt(2 * pi)) via Gauss AGM(1, sqrt(2)) over Q(sqrt(2))."""
+ work_prec = digits + 20
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ pi_val = projective_pi_decimal(work_prec)
+ varpi = projective_lemniscate_varpi_decimal(work_prec)
+ sqrt_2pi = _heron_sqrt_decimal(Decimal(2) * pi_val, work_prec)
+ g14 = _heron_sqrt_decimal(Decimal(2) * varpi * sqrt_2pi, work_prec)
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +g14
+
+
+def projective_catalan_G_decimal(digits: int = 50) -> Decimal:
+ """Catalan's constant G via Ramanujan's projective identity over Q(sqrt(3)) (d = 4):
+ G = (pi / 8) * Log_P(2 + sqrt(3)) + (3 / 8) * sum_{k=0}^oo (k!)^2 / ((2k+1)! * (2k+1)).
+ """
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ pi_val = projective_pi_decimal(work_prec)
+ sqrt3 = _heron_sqrt_decimal(3, work_prec)
+ ln_unit = _projective_log_positive_decimal(Decimal(2) + sqrt3, work_prec)
+ s = Decimal(0)
+ term = Decimal(1)
+ tol = Decimal(10) ** (-(digits + 20))
+ for k in range(int(work_prec * 1.8) + 20):
+ contrib = term / Decimal(2 * k + 1)
+ s += contrib
+ if abs(contrib) <= tol:
+ break
+ term = term * Decimal(k + 1) / Decimal(2 * (2 * k + 3))
+ g_val = (pi_val / Decimal(8)) * ln_unit + (Decimal(3) / Decimal(8)) * s
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +g_val
+
+
+def projective_apery_zeta3_decimal(digits: int = 50) -> Decimal:
+ """Apery's constant zeta(3) via Amdeberhan-Zeilberger pure-rational hypergeometric Pade acceleration."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ zeta3 = Decimal(0)
+ term_num = Decimal(1)
+ tol = Decimal(10) ** (-(digits + 20))
+ for k in range((work_prec // 3) + 12):
+ poly = Decimal(205 * k * k + 250 * k + 77)
+ sign = Decimal(-1) if (k & 1) else Decimal(1)
+ contrib = sign * poly * term_num
+ zeta3 += contrib
+ if abs(contrib) <= tol:
+ break
+ num_step = Decimal((k + 1) ** 5)
+ den_step = Decimal(32) * Decimal((2 * k + 3) ** 5)
+ term_num = term_num * num_step / den_step
+ zeta3 = zeta3 / Decimal(64)
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +zeta3
+
+
+def projective_euler_gamma_decimal(digits: int = 50) -> Decimal:
+ """Euler-Mascheroni constant gamma via Brent-McMillan rational acceleration + Log_P(n)."""
+ work_prec = digits + 25
+ with localcontext() as ctx:
+ ctx.prec = work_prec
+ n = int(digits * 1.15) + 10
+ ln_n = _projective_log_positive_decimal(n, work_prec)
+ a_term = -ln_n
+ b_term = Decimal(1)
+ u_sum = a_term
+ v_sum = b_term
+ n2 = Decimal(n * n)
+ tol = Decimal(10) ** (-(digits + 20))
+ for k in range(1, 5 * n + 30):
+ k_dec = Decimal(k)
+ b_term = b_term * n2 / (k_dec * k_dec)
+ a_term = (a_term * n2 / k_dec + b_term) / k_dec
+ u_sum += a_term
+ v_sum += b_term
+ if abs(a_term) < tol and abs(b_term) < tol:
+ break
+ gamma_val = u_sum / v_sum
+ with localcontext() as ctx:
+ ctx.prec = digits
+ return +gamma_val
+
+
+_PROJECTIVE_CONSTANT_DISPATCH = {
+ "pi": projective_pi_decimal,
+ "e": projective_e_decimal,
+ "ln2": projective_ln2_decimal,
+ "log2": projective_ln2_decimal,
+ "log[2]": projective_ln2_decimal,
+ "goldenratio": projective_golden_ratio_decimal,
+ "phi": projective_golden_ratio_decimal,
+ "lemniscate": projective_lemniscate_varpi_decimal,
+ "lemniscateconstant": projective_lemniscate_varpi_decimal,
+ "varpi": projective_lemniscate_varpi_decimal,
+ "gamma14": projective_gamma_quarter_decimal,
+ "gamma[1/4]": projective_gamma_quarter_decimal,
+ "catalan": projective_catalan_G_decimal,
+ "g": projective_catalan_G_decimal,
+ "apery": projective_apery_zeta3_decimal,
+ "zeta3": projective_apery_zeta3_decimal,
+ "zeta[3]": projective_apery_zeta3_decimal,
+ "eulergamma": projective_euler_gamma_decimal,
+ "gamma": projective_euler_gamma_decimal,
+}
+
+
+def eval_projective_constant(name: str, digits: int = 50) -> Optional[Decimal]:
+ """Evaluate a fundamental mathematical constant to `digits` precision using pure-rational
+ non-circular projective algorithms (0 mpmath).
+ """
+ if digits < 2 or digits > 2000:
+ return None
+ key = name.strip().lower().replace(" ", "")
+ if "`" in key:
+ key = key.split("`")[-1]
+ fn = _PROJECTIVE_CONSTANT_DISPATCH.get(key)
+ if fn is None:
+ return None
+ return fn(digits)
+
+
+def projective_gray_butterfly_pair(m: int, phi: int) -> tuple[int, int]:
+ """Branchless Gray-code semidirect butterfly (C_m(phi), S_m(phi)) on Z_{2^m} for any m >= 3."""
+ n_ring = 1 << m
+ half = 1 << (m - 1)
+ q_sq = 1 << (m - 2)
+ u = phi % n_ring
+ q1 = u // half
+ q0 = (u // q_sq) & 1
+ rem = u % q_sq
+ comp = q_sq - rem
+ c_mag = (1 - q0) * comp + q0 * rem
+ s_mag = (1 - q0) * rem + q0 * comp
+ c_neg = (q1 + q0) & 1
+ s_neg = q1
+ return ((1 - 2 * c_neg) * c_mag, (1 - 2 * s_neg) * s_mag)
+
+
+def eval_projective_ring_point(m: int, phi: int, prop: str = "UnitCircle"):
+ """Evaluate exact projective ring invariants on Z_{2^m} -> P^1(Q) for any rank m >= 3."""
+ if m < 3:
+ return None
+ c_val, s_val = projective_gray_butterfly_pair(m, phi)
+ key = prop.strip().lower()
+ if "`" in key:
+ key = key.split("`")[-1]
+ if key in ("character", "char", "cs"):
+ return [sp.Integer(c_val), sp.Integer(s_val)]
+ if key in ("wronskian", "w"):
+ c_next, s_next = projective_gray_butterfly_pair(m, phi + 1)
+ return sp.Integer(c_val * s_next - s_val * c_next)
+
+ q_sq = 1 << (m - 2)
+ q2 = q_sq * q_sq
+ s2 = s_val * s_val
+ c_nonzero = 1 - (1 // (abs(c_val) + 1))
+ c_pos = 1 - (1 // (max(0, c_val) + 1))
+ sgn_c = c_nonzero * (2 * c_pos - 1)
+ px = sgn_c * (q2 - s2)
+ py = 2 * q_sq * s_val
+ pr = q2 + s2
+ if key in ("pythagoreantriple", "triple", "homogeneous"):
+ return [sp.Integer(px), sp.Integer(py), sp.Integer(pr)]
+ if key in ("unitcircle", "circle", "point", "s1"):
+ return [sp.Rational(px, pr), sp.Rational(py, pr)]
+ return None
+
+
+def eval_projective_quadratic_sum(m: int, n_dim: int):
+ """Exact N-dimensional quadratic sum over (Z_{2^m})^n_dim (dl^n_dim) in Z[i] for any m >= 3, n_dim >= 1."""
+ if m < 3 or n_dim < 1:
+ return None
+ exp2 = (m - 2) + n_dim * (m // 2) + (n_dim // 2) * (m & 1)
+ return sp.expand(((1 + sp.I) ** n_dim) * (sp.Integer(1 << exp2)))
+
+
+def eval_projective_contour_winding(m: int, phases: list[int]) -> Optional[int]:
+ """Exact branch-carry cohomological winding index around a closed loop on Z_{2^m}."""
+ if m < 3 or len(phases) < 2:
+ return None
+ n_ring = 1 << m
+ half = 1 << (m - 1)
+ total_k = 0
+ n_pts = len(phases)
+ for idx in range(n_pts):
+ u_x = phases[idx] % n_ring
+ u_y = phases[(idx + 1) % n_pts] % n_ring
+ dphi = u_y - u_x
+ k_xy = (dphi + (half - 1)) // n_ring
+ total_k += k_xy
+ return -total_k
+
+
+def eval_projective_isotropic_stencil(d: int) -> Optional[list[list[int]]]:
+ """O(d^2) isotropic d-dimensional stencil O_2(d) = {e in {-1,0,1}^d : |e|^2 == 2} for any d >= 2."""
+ if d < 2:
+ return None
+ vectors: list[list[int]] = []
+ for i in range(d):
+ for j in range(i + 1, d):
+ for si in (-1, 1):
+ for sj in (-1, 1):
+ vec = [0] * d
+ vec[i] = si
+ vec[j] = sj
+ vectors.append(vec)
+ vectors.sort()
+ return vectors
+
+
+
+
diff --git a/mathics/mcp_server.py b/mathics/mcp_server.py
new file mode 100644
index 000000000..843b09841
--- /dev/null
+++ b/mathics/mcp_server.py
@@ -0,0 +1,395 @@
+# -*- coding: utf-8 -*-
+"""
+Model Context Protocol (MCP) Server for Mathics3 (Wolfram Language + Projective CAS).
+
+Exposes a zero-dependency JSON-RPC 2.0 stdio MCP server (`mathics3-mcp` or
+`python -m mathics.mcp_server`) allowing AI agents (Claude, OpenCode, Cursor, etc.)
+to evaluate Wolfram Language expressions, symbolic & improper integrals over
+Q(i, sqrt(d-1)), Riemann sphere contour integrals, Cauchy-Lagrange residues,
+Pade approximants, and arbitrary-precision numeric evaluations without requiring
+a proprietary Wolfram Engine license.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import traceback
+from typing import Any, Dict, Optional
+
+from mathics.session import MathicsSession, load_default_settings_files
+from mathics.version import __version__
+
+SERVER_NAME = "mathics3-mcp"
+PROTOCOL_VERSION = "2024-11-05"
+
+TOOLS_SPEC = [
+ {
+ "name": "wolfram_eval",
+ "description": (
+ "Evaluate any Wolfram Language (Mathematica) expression in a persistent Mathics3 session. "
+ "Returns the exact result in InputForm, optional TeXForm (LaTeX), and any printed/warning messages."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Wolfram Language expression, e.g. 'Integrate[Sin[x^2], {x, 0, Infinity}]' or 'Solve[x^4 + 1 == 0, x]'.",
+ },
+ "include_tex": {
+ "type": "boolean",
+ "default": True,
+ "description": "Include TeXForm (LaTeX) rendering of the result.",
+ },
+ },
+ "required": ["code"],
+ },
+ },
+ {
+ "name": "wolfram_integrate",
+ "description": (
+ "Compute an indefinite, definite, or improper integral in Wolfram Language using the "
+ "Projective Calculus kernel over Q(i, sqrt(d-1)) and SymPy. Supports arbitrary-precision numeric evaluation."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expr": {
+ "type": "string",
+ "description": "Integrand in Wolfram Language syntax, e.g. '1/(1 + x^4)', 'Sqrt[Tan[x]]', 'Sin[x^2]'.",
+ },
+ "var": {
+ "type": "string",
+ "default": "x",
+ "description": "Integration variable name, e.g. 'x' or 'z'.",
+ },
+ "lower": {
+ "type": "string",
+ "description": "Optional lower limit (e.g. '0', '-Infinity', '1 + I'). Omit for indefinite integral.",
+ },
+ "upper": {
+ "type": "string",
+ "description": "Optional upper limit (e.g. '1', 'Infinity', '2 + 3 I'). Omit for indefinite integral.",
+ },
+ "numeric_precision": {
+ "type": "integer",
+ "description": "Optional arbitrary precision (number of decimal digits, e.g. 50 or 200) via N[..., digits].",
+ },
+ },
+ "required": ["expr"],
+ },
+ },
+ {
+ "name": "wolfram_contour_integrate",
+ "description": (
+ "Compute a closed contour integral ContourIntegrate[expr, {var, center, radius}] around "
+ "the circle |var - center| = radius on the Riemann sphere P^1(C) via Ostrowski-Hermite reduction "
+ "and Cauchy-Lagrange residues."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expr": {
+ "type": "string",
+ "description": "Rational integrand in Wolfram Language syntax, e.g. '1/(1 + z^4)'.",
+ },
+ "var": {
+ "type": "string",
+ "default": "z",
+ "description": "Complex variable name (default: 'z').",
+ },
+ "center": {
+ "type": "string",
+ "default": "0",
+ "description": "Complex circle center, e.g. '0', 'I', '1 + I'.",
+ },
+ "radius": {
+ "type": "string",
+ "default": "1",
+ "description": "Positive circle radius, e.g. '1' or '2'.",
+ },
+ },
+ "required": ["expr"],
+ },
+ },
+ {
+ "name": "wolfram_residue",
+ "description": (
+ "Compute the Cauchy-Lagrange residue Residue[expr, {var, pole}] at any pole on the "
+ "Riemann sphere P^1(C), including 'Infinity'."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expr": {
+ "type": "string",
+ "description": "Meromorphic expression in Wolfram Language syntax, e.g. '1/(1 + z^4)' or '1/z'.",
+ },
+ "var": {
+ "type": "string",
+ "default": "z",
+ "description": "Complex variable name (default: 'z').",
+ },
+ "pole": {
+ "type": "string",
+ "description": "Pole location in C or 'Infinity', e.g. '(1 + I)/Sqrt[2]' or 'Infinity'.",
+ },
+ },
+ "required": ["expr", "pole"],
+ },
+ },
+ {
+ "name": "wolfram_pade_approximant",
+ "description": (
+ "Compute the exact rational Pade approximant PadeApproximant[expr, {var, x0, {m, n}}] "
+ "of degree [m/n] about var = x0."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expr": {
+ "type": "string",
+ "description": "Expression in Wolfram Language syntax, e.g. 'Exp[x]' or 'ArcTan[x]'.",
+ },
+ "var": {
+ "type": "string",
+ "default": "x",
+ "description": "Variable name (default: 'x').",
+ },
+ "x0": {
+ "type": "string",
+ "default": "0",
+ "description": "Expansion point x0 (default: '0').",
+ },
+ "m": {
+ "type": "integer",
+ "default": 3,
+ "description": "Numerator polynomial degree m >= 0.",
+ },
+ "n": {
+ "type": "integer",
+ "default": 3,
+ "description": "Denominator polynomial degree n >= 0.",
+ },
+ },
+ "required": ["expr"],
+ },
+ },
+ {
+ "name": "wolfram_reset_session",
+ "description": "Reset the persistent Mathics3 Wolfram Language session, clearing all user definitions.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ },
+ },
+]
+
+
+class MathicsMCPServer:
+ """Persistent Mathics3 MCP Server handling JSON-RPC 2.0 tool requests."""
+
+ def __init__(self) -> None:
+ self._session: Optional[MathicsSession] = None
+
+ @property
+ def session(self) -> MathicsSession:
+ if self._session is None:
+ self._session = MathicsSession()
+ load_default_settings_files(self._session.definitions)
+ return self._session
+
+ def reset_session(self) -> None:
+ self._session = MathicsSession()
+ load_default_settings_files(self._session.definitions)
+
+ def eval_wl(self, code: str, include_tex: bool = True) -> Dict[str, Any]:
+ res = self.session.evaluate_as_in_cli(code)
+ out_msgs = [str(getattr(m, "text", m)) for m in (res.out or [])]
+ payload: Dict[str, Any] = {
+ "input": code,
+ "result": res.result,
+ "messages": out_msgs,
+ "line_no": res.line_no,
+ }
+ if include_tex and res.result is not None and res.result != "Null":
+ try:
+ tex_res = self.session.evaluate_as_in_cli(f"TeXForm[{res.result}]")
+ payload["tex"] = tex_res.result
+ except Exception:
+ payload["tex"] = None
+ return payload
+
+ def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
+ if name == "wolfram_eval":
+ code = str(arguments["code"])
+ include_tex = bool(arguments.get("include_tex", True))
+ return self.eval_wl(code, include_tex=include_tex)
+
+ if name == "wolfram_integrate":
+ expr = str(arguments["expr"])
+ var = str(arguments.get("var", "x"))
+ lower = arguments.get("lower")
+ upper = arguments.get("upper")
+ prec = arguments.get("numeric_precision")
+
+ if lower is not None and upper is not None:
+ wl_cmd = f"Integrate[{expr}, {{{var}, {lower}, {upper}}}]"
+ else:
+ wl_cmd = f"Integrate[{expr}, {var}]"
+
+ out = self.eval_wl(wl_cmd, include_tex=True)
+ if prec is not None and int(prec) >= 2 and out.get("result"):
+ n_digits = int(prec)
+ n_res = self.session.evaluate_as_in_cli(
+ f"N[{out['result']}, {n_digits}]"
+ )
+ out["numeric_value"] = n_res.result
+ out["numeric_precision"] = n_digits
+ return out
+
+ if name == "wolfram_contour_integrate":
+ expr = str(arguments["expr"])
+ var = str(arguments.get("var", "z"))
+ center = str(arguments.get("center", "0"))
+ radius = str(arguments.get("radius", "1"))
+ wl_cmd = f"ContourIntegrate[{expr}, {{{var}, {center}, {radius}}}]"
+ return self.eval_wl(wl_cmd, include_tex=True)
+
+ if name == "wolfram_residue":
+ expr = str(arguments["expr"])
+ var = str(arguments.get("var", "z"))
+ pole = str(arguments["pole"])
+ wl_cmd = f"Residue[{expr}, {{{var}, {pole}}}]"
+ return self.eval_wl(wl_cmd, include_tex=True)
+
+ if name == "wolfram_pade_approximant":
+ expr = str(arguments["expr"])
+ var = str(arguments.get("var", "x"))
+ x0 = str(arguments.get("x0", "0"))
+ m = int(arguments.get("m", 3))
+ n = int(arguments.get("n", 3))
+ wl_cmd = f"PadeApproximant[{expr}, {{{var}, {x0}, {{{m}, {n}}}}}]"
+ return self.eval_wl(wl_cmd, include_tex=True)
+
+ if name == "wolfram_reset_session":
+ self.reset_session()
+ return {"status": "reset", "message": "Mathics3 session reset."}
+
+ raise ValueError(f"Unknown MCP tool: {name!r}")
+
+ def handle_request(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ method = request.get("method")
+ req_id = request.get("id")
+ params = request.get("params") or {}
+
+ # Notifications have no id and expect no response
+ if req_id is None:
+ return None
+
+ try:
+ if method == "initialize":
+ return {
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "result": {
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {"tools": {}},
+ "serverInfo": {
+ "name": SERVER_NAME,
+ "version": __version__,
+ },
+ },
+ }
+
+ if method == "ping":
+ return {"jsonrpc": "2.0", "id": req_id, "result": {}}
+
+ if method == "tools/list":
+ return {
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "result": {"tools": TOOLS_SPEC},
+ }
+
+ if method == "tools/call":
+ tool_name = params.get("name", "")
+ tool_args = params.get("arguments") or {}
+ payload = self.call_tool(tool_name, tool_args)
+ return {
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": json.dumps(payload, ensure_ascii=False, indent=2),
+ }
+ ],
+ "isError": False,
+ },
+ }
+
+ return {
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "error": {
+ "code": -32601,
+ "message": f"Method not found: {method}",
+ },
+ }
+ except Exception as exc:
+ return {
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": json.dumps(
+ {
+ "error": str(exc),
+ "traceback": traceback.format_exc(limit=6),
+ },
+ ensure_ascii=False,
+ ),
+ }
+ ],
+ "isError": True,
+ },
+ }
+
+
+def main() -> int:
+ """Run the Mathics3 MCP Server over stdin/stdout (newline-delimited JSON-RPC 2.0)."""
+ server = MathicsMCPServer()
+ for raw_line in sys.stdin:
+ line = raw_line.strip()
+ if not line:
+ continue
+ if line.lower().startswith("content-length:"):
+ # Support LSP-style Content-Length framing if used by client
+ length = int(line.split(":", 1)[1].strip())
+ # consume blank header separator line
+ sys.stdin.readline()
+ body = sys.stdin.read(length)
+ req = json.loads(body)
+ resp = server.handle_request(req)
+ if resp is not None:
+ out_bytes = json.dumps(resp, ensure_ascii=False).encode("utf-8")
+ sys.stdout.write(f"Content-Length: {len(out_bytes)}\r\n\r\n")
+ sys.stdout.write(out_bytes.decode("utf-8"))
+ sys.stdout.flush()
+ continue
+
+ req = json.loads(line)
+ resp = server.handle_request(req)
+ if resp is not None:
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
+ sys.stdout.flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/pyproject.toml b/pyproject.toml
index d3c03d34d..aa63f7839 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -98,6 +98,7 @@ gmp2 = [
mathics = "mathics.__main__:main"
mathics3 = "mathics.__main__:main"
mathics3-codeparser-parse = "mathics.mathics3_code_parse:main"
+mathics3-mcp = "mathics.mcp_server:main"
[tool.codespell]
# Point to your custom ignore file
diff --git a/test/builtin/numbers/test_projective_calculus.py b/test/builtin/numbers/test_projective_calculus.py
new file mode 100644
index 000000000..43c1da69e
--- /dev/null
+++ b/test/builtin/numbers/test_projective_calculus.py
@@ -0,0 +1,291 @@
+# -*- coding: utf-8 -*-
+"""
+Unit tests for Projective Calculus over Q(i, sqrt(d-1)) and Riemann Sphere P^1(C)
+in Mathics3:
+ - Integrate (fractional trig rationalization & Weierstrass stereographic lift)
+ - PadeApproximant ([m/n] and diagonal [n/n])
+ - Residue (finite poles in Q(i, sqrt(2)) and projective infinity [1 : 0])
+ - ContourIntegrate (closed circular contours on P^1(C))
+ - TrigReduce (projective P^1 trigonometric reduction)
+"""
+
+from test.helper import check_evaluation
+import pytest
+
+
+@pytest.mark.parametrize(
+ ("str_expr", "str_expected", "fail_msg"),
+ [
+ # 1. PadeApproximant [m/n] and diagonal [n/n]
+ (
+ "PadeApproximant[Exp[x], {x, 0, {2, 2}}]",
+ "(12 + 6 x + x ^ 2) / (12 - 6 x + x ^ 2)",
+ "Pade [2/2] of Exp[x]",
+ ),
+ (
+ "PadeApproximant[Exp[x], {x, 0, 2}]",
+ "(12 + 6 x + x ^ 2) / (12 - 6 x + x ^ 2)",
+ "Diagonal Pade [2/2] of Exp[x]",
+ ),
+ (
+ "PadeApproximant[ArcTan[x], {x, 0, {3, 3}}]",
+ "(15 x + 4 x ^ 3) / (15 + 9 x ^ 2)",
+ "Pade [3/3] of ArcTan[x]",
+ ),
+ (
+ "PadeApproximant[Log[1 + x], {x, 0, {2, 2}}]",
+ "(6 x + 3 x ^ 2) / (6 + 6 x + x ^ 2)",
+ "Pade [2/2] of Log[1 + x]",
+ ),
+ # 2. Residue on P^1(C) including projective infinity
+ (
+ "Residue[1 / (z^2 + 1), {z, I}]",
+ "-I / 2",
+ "Residue at simple pole z = I",
+ ),
+ (
+ "Residue[1 / (1 + z^4), {z, (1 + I) / Sqrt[2]}]",
+ "(-1 / 8 - I / 8) Sqrt[2]",
+ "Residue at biquadratic pole in Q(i, sqrt(2))",
+ ),
+ (
+ "Residue[1 / z, {z, Infinity}]",
+ "-1",
+ "Residue at projective infinity [1 : 0] on P^1(C)",
+ ),
+ (
+ "Residue[z^2 / (1 + z^3), {z, Infinity}]",
+ "-1",
+ "Residue of rational function at projective infinity",
+ ),
+ # 3. ContourIntegrate on the Riemann sphere P^1(C)
+ (
+ "ContourIntegrate[1 / (1 + z^4), {z, Circle[{0, 1}, 1]}]",
+ "Sqrt[2] Pi / 2",
+ "Contour integral enclosing two upper-half-plane poles of 1/(1+z^4)",
+ ),
+ (
+ "ContourIntegrate[1 / (1 + z^4), {z, 0, 2}]",
+ "0",
+ "Contour integral enclosing all four poles of 1/(1+z^4) vanishes by P^1 residue sum",
+ ),
+ (
+ "ContourIntegrate[1 / (1 + z^2), {z, I, 1}]",
+ "Pi",
+ "Contour integral around z = I",
+ ),
+ (
+ "ContourIntegrate[1 / (z - 1)^3, {z, Circle[{1, 0}, 2]}]",
+ "0",
+ "Ostrowski-Hermite exact derivative has zero contour residue",
+ ),
+ # 4. TrigReduce on P^1
+ (
+ "TrigReduce[Sin[3 x] - (3 Sin[x] - 4 Sin[x]^3)]",
+ "0",
+ "Triple-angle sine identity via TrigReduce",
+ ),
+ (
+ "TrigReduce[Cos[4 x] - (8 Cos[x]^4 - 8 Cos[x]^2 + 1)]",
+ "0",
+ "Quadruple-angle cosine identity via TrigReduce",
+ ),
+ (
+ "TrigReduce[2 Sin[x] Cos[x]]",
+ "Sin[2 x]",
+ "Double-angle product reduction",
+ ),
+ # 5. Projective Integrate extensions over Q(i, sqrt(2))
+ (
+ "TrigReduce[D[Integrate[Sqrt[Tan[x]], x], x] - Sqrt[Tan[x]]]",
+ "0",
+ "Derivative of projective primitive for Sqrt[Tan[x]] equals integrand",
+ ),
+ (
+ "TrigReduce[D[Integrate[Sqrt[Cot[x]], x], x] - Sqrt[Cot[x]]]",
+ "0",
+ "Derivative of projective primitive for Sqrt[Cot[x]] equals integrand",
+ ),
+ (
+ "FreeQ[Integrate[1 / (1 + Sin[x]^4), x], Integrate]",
+ "True",
+ "Projective Weierstrass primitive for 1/(1 + Sin[x]^4) evaluates in closed form",
+ ),
+ # 6. Dyadic half-angle tower Cos[p*Pi/2^k], Sin[p*Pi/2^k] over Q(sqrt(2))
+ (
+ "Cos[Pi / 16]",
+ "Sqrt[1 / 2 + Sqrt[1 / 2 + Sqrt[2] / 4] / 2]",
+ "Exact nested-radical Cos[Pi/16] via projective half-angle tower",
+ ),
+ (
+ "Sin[Pi / 16]",
+ "Sqrt[1 / 2 - Sqrt[1 / 2 + Sqrt[2] / 4] / 2]",
+ "Exact nested-radical Sin[Pi/16] via projective half-angle tower",
+ ),
+ (
+ "Simplify[Cos[Pi / 16]^2 + Sin[Pi / 16]^2]",
+ "1",
+ "Unitary circle invariant Cos[Pi/16]^2 + Sin[Pi/16]^2 == 1",
+ ),
+ (
+ "Simplify[Cos[Pi / 32]^2 + Sin[Pi / 32]^2]",
+ "1",
+ "Unitary circle invariant Cos[Pi/32]^2 + Sin[Pi/32]^2 == 1",
+ ),
+ # 7. TrigExpand, TrigFactor, TrigToExp, ExpToTrig
+ (
+ "TrigExpand[Sin[2 x]]",
+ "2 Cos[x] Sin[x]",
+ "TrigExpand of double-angle sine",
+ ),
+ (
+ "TrigFactor[Sin[x]^2 - Cos[x]^2]",
+ "(-Cos[x] + Sin[x]) (Cos[x] + Sin[x])",
+ "TrigFactor of difference of squares",
+ ),
+ (
+ "TrigToExp[Cos[x]]",
+ "E ^ (-I x) / 2 + E ^ (I x) / 2",
+ "TrigToExp of Cos[x]",
+ ),
+ (
+ "ExpToTrig[Exp[I x] + Exp[-I x]]",
+ "2 Cos[x]",
+ "ExpToTrig of conjugate exponential pair",
+ ),
+ # 8. LaplaceTransform, InverseLaplaceTransform, and infinite-dimensional StieltjesPadeResolvent
+ (
+ "LaplaceTransform[Sin[t], t, s]",
+ "1 / (1 + s ^ 2)",
+ "LaplaceTransform of Sin[t]",
+ ),
+ (
+ "InverseLaplaceTransform[1 / (1 + s^2), s, t]",
+ "Sin[t]",
+ "InverseLaplaceTransform of 1/(1 + s^2)",
+ ),
+ (
+ "StieltjesPadeResolvent[{1, 3, 11, 43}, s]",
+ "(-2 + s) / (4 - 5 s + s ^ 2)",
+ "Stieltjes-Pade [1/2] operator resolvent from moments {1, 3, 11, 43}",
+ ),
+ (
+ "InverseLaplaceTransform[StieltjesPadeResolvent[{1, 3, 11, 43}, s], s, t]",
+ "E ^ t / 3 + 2 E ^ (4 t) / 3",
+ "Riesz-Dunford time-evolution operator from Stieltjes-Pade resolvent",
+ ),
+ # 9. Non-circular pure-rational ProjectiveConstant for Pi, E, Log2, GoldenRatio, Lemniscate, Gamma14, Catalan, Apery, EulerGamma
+ (
+ 'Abs[ProjectiveConstant["Pi", 30] - 314159265358979323846264338328 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective Pi via Gaussian (5+i)^4(239-i) and Cayley-Pade (5,5)",
+ ),
+ (
+ 'Abs[ProjectiveConstant["E", 30] - 271828182845904523536028747135 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective E via dyadic halving and Cayley-Pade (5,5)",
+ ),
+ (
+ 'Abs[ProjectiveConstant["Log2", 30] - 693147180559945309417232121458 / 10^30] < 10^-25',
+ "True",
+ "Non-circular projective ln(2) via Heron descent and Cayley-Pade (5,5)",
+ ),
+ (
+ 'Abs[ProjectiveConstant["GoldenRatio", 30] - 161803398874989484820458683437 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective GoldenRatio via Heron iteration",
+ ),
+ (
+ 'Abs[ProjectiveConstant["Lemniscate", 30] - 262205755429211981046483958989 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective Gauss lemniscate constant varpi via AGM(1, sqrt(2))",
+ ),
+ (
+ 'Abs[ProjectiveConstant["Gamma14", 30] - 362560990822190831193068515587 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective Gamma(1/4) via Gauss AGM(1, sqrt(2))",
+ ),
+ (
+ 'Abs[ProjectiveConstant["Catalan", 30] - 915965594177219015054603514932 / 10^30] < 10^-25',
+ "True",
+ "Non-circular projective Catalan G via Ramanujan Log_P(2 + sqrt(3)) over Q(sqrt(3))",
+ ),
+ (
+ 'Abs[ProjectiveConstant["Apery", 30] - 120205690315959428539973816151 / 10^29] < 10^-25',
+ "True",
+ "Non-circular projective Apery zeta(3) via Amdeberhan-Zeilberger rational acceleration",
+ ),
+ (
+ 'Abs[ProjectiveConstant["EulerGamma", 30] - 577215664901532860606512090082 / 10^30] < 10^-25',
+ "True",
+ "Non-circular projective Euler-Mascheroni gamma via Brent-McMillan + Log_P(n)",
+ ),
+ # 10. ProjectiveRingPoint, ProjectiveQuadraticSum, ProjectiveContourWinding, ProjectiveIsotropicStencil
+ (
+ "ProjectiveRingPoint[9, 41]",
+ "{14703 / 18065, 10496 / 18065}",
+ "ProjectiveRingPoint rational S^1(Q) coordinates at m=9, phi=41",
+ ),
+ (
+ 'ProjectiveRingPoint[9, 41, "PythagoreanTriple"]',
+ "{14703, 10496, 18065}",
+ "ProjectiveRingPoint Pythagorean triple at m=9, phi=41",
+ ),
+ (
+ 'ProjectiveRingPoint[9, 41, "Character"]',
+ "{87, 41}",
+ "ProjectiveRingPoint Gray-code butterfly character {C_9(41), S_9(41)}",
+ ),
+ (
+ 'ProjectiveRingPoint[128, 9876543210123456789, "Wronskian"] == 2^126',
+ "True",
+ "ProjectiveRingPoint Wronskian invariance W_m === 2^(m-2) at m=128",
+ ),
+ (
+ "Total[ProjectiveRingPoint[256, 123456789012345678901234567890]^2] == 1",
+ "True",
+ "ProjectiveRingPoint exact unit circle x^2 + y^2 === 1 at m=256 bits",
+ ),
+ (
+ "ProjectiveRingPoint[33, 2 * 777] == ProjectiveRingPoint[32, 777]",
+ "True",
+ "ProjectiveRingPoint projective limit embedding invariance (m, phi) -> (m+1, 2*phi)",
+ ),
+ (
+ "ProjectiveQuadraticSum[9, 1]",
+ "2048 + 2048 I",
+ "ProjectiveQuadraticSum 1D at m=9",
+ ),
+ (
+ "ProjectiveQuadraticSum[4, 3]",
+ "-512 + 512 I",
+ "ProjectiveQuadraticSum 3D over (Z_16)^3",
+ ),
+ (
+ "ProjectiveQuadraticSum[9, 8]",
+ "140737488355328",
+ "ProjectiveQuadraticSum 8D Bott periodicity at m=9",
+ ),
+ (
+ "ProjectiveContourWinding[16, {0, 16385, 32770, 49155}]",
+ "1",
+ "ProjectiveContourWinding exact winding index on Z_{2^16}",
+ ),
+ (
+ "{Length[ProjectiveIsotropicStencil[3]], Length[ProjectiveIsotropicStencil[5]]}",
+ "{12, 40}",
+ "ProjectiveIsotropicStencil O_2(d) cardinality 2*d*(d-1) for d=3, 5",
+ ),
+ ],
+)
+def test_projective_calculus_builtins(
+ str_expr: str, str_expected: str, fail_msg: str
+) -> None:
+ check_evaluation(
+ str_expr,
+ str_expected,
+ to_string_expr=True,
+ to_string_expected=True,
+ hold_expected=True,
+ failure_message=fail_msg,
+ )
diff --git a/test/test_mcp_server.py b/test/test_mcp_server.py
new file mode 100644
index 000000000..95e883fe9
--- /dev/null
+++ b/test/test_mcp_server.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+"""
+Unit tests for the Mathics3 Wolfram Language MCP Server (`mathics.mcp_server`).
+"""
+
+import json
+from mathics.mcp_server import MathicsMCPServer
+
+
+def test_mcp_initialize_and_tools_list() -> None:
+ server = MathicsMCPServer()
+
+ init_resp = server.handle_request(
+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}
+ )
+ assert init_resp is not None
+ assert init_resp["id"] == 1
+ assert init_resp["result"]["serverInfo"]["name"] == "mathics3-mcp"
+
+ tools_resp = server.handle_request(
+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
+ )
+ assert tools_resp is not None
+ tool_names = {t["name"] for t in tools_resp["result"]["tools"]}
+ assert {
+ "wolfram_eval",
+ "wolfram_integrate",
+ "wolfram_contour_integrate",
+ "wolfram_residue",
+ "wolfram_pade_approximant",
+ "wolfram_reset_session",
+ }.issubset(tool_names)
+
+
+def test_mcp_tools_call_calculus_and_arbitrary_precision() -> None:
+ server = MathicsMCPServer()
+
+ # 1. Improper Fresnel integral with 60-digit precision
+ int_resp = server.handle_request(
+ {
+ "jsonrpc": "2.0",
+ "id": 10,
+ "method": "tools/call",
+ "params": {
+ "name": "wolfram_integrate",
+ "arguments": {
+ "expr": "Sin[x^2]",
+ "var": "x",
+ "lower": "0",
+ "upper": "Infinity",
+ "numeric_precision": 60,
+ },
+ },
+ }
+ )
+ assert int_resp is not None
+ assert not int_resp["result"]["isError"]
+ payload = json.loads(int_resp["result"]["content"][0]["text"])
+ assert payload["result"] == "Sqrt[2] Sqrt[Pi] / 4"
+ assert payload["numeric_value"].startswith(
+ "0.62665706865775012560394132120276131325174668515248457915748"
+ )
+
+ # 2. ContourIntegrate tool on P^1(C)
+ cnt_resp = server.handle_request(
+ {
+ "jsonrpc": "2.0",
+ "id": 11,
+ "method": "tools/call",
+ "params": {
+ "name": "wolfram_contour_integrate",
+ "arguments": {
+ "expr": "1 / (1 + z^4)",
+ "var": "z",
+ "center": "I",
+ "radius": "1",
+ },
+ },
+ }
+ )
+ assert cnt_resp is not None
+ cnt_payload = json.loads(cnt_resp["result"]["content"][0]["text"])
+ assert cnt_payload["result"] == "Sqrt[2] Pi / 2"
+
+ # 3. Residue tool at Infinity
+ res_resp = server.handle_request(
+ {
+ "jsonrpc": "2.0",
+ "id": 12,
+ "method": "tools/call",
+ "params": {
+ "name": "wolfram_residue",
+ "arguments": {
+ "expr": "1 / z",
+ "var": "z",
+ "pole": "Infinity",
+ },
+ },
+ }
+ )
+ assert res_resp is not None
+ res_payload = json.loads(res_resp["result"]["content"][0]["text"])
+ assert res_payload["result"] == "-1"
+
+ # 4. PadeApproximant tool
+ pade_resp = server.handle_request(
+ {
+ "jsonrpc": "2.0",
+ "id": 13,
+ "method": "tools/call",
+ "params": {
+ "name": "wolfram_pade_approximant",
+ "arguments": {
+ "expr": "Exp[x]",
+ "var": "x",
+ "x0": "0",
+ "m": 2,
+ "n": 2,
+ },
+ },
+ }
+ )
+ assert pade_resp is not None
+ pade_payload = json.loads(pade_resp["result"]["content"][0]["text"])
+ assert pade_payload["result"] == "(12 + 6 x + x ^ 2) / (12 - 6 x + x ^ 2)"