Repository navigation
Expand file tree
/
Copy pathsymbolic.py
More file actions
352 lines (291 loc) · 13.5 KB
/
Copy pathsymbolic.py
File metadata and controls
352 lines (291 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Trusted venv symbolic compute — runs in the user venv worker.
Host ``run_symbolic`` uses the long trusted worker budget
(``LONG_TRUSTED_WORKER_TIMEOUT_SEC``, 300 seconds) and kills the worker if
sympy does not return. This module does not add a second timer.
"""
from __future__ import annotations
import functools
import inspect
import re
from typing import Any, Callable
from plugin.scripting.helper_registry import helper
from plugin.scripting.venv.results import HelperError, error_result
from plugin.scripting.venv.trusted_dispatch import (
is_blank_param,
missing_package_error,
ok_result,
run_domain,
)
_MAX_SYMBOLIC_EXPR_CHARS = 10_000
# Cues that mean "already LaTeX". ``x_1`` is kept; ``x1`` is parsed.
_LATEX_CUES = ("=", "\\", "{", "}", "^", "_")
_CALL_NAME = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s*\(")
_SYMPY_NAMES = (
"Abs Add And E Eq Float Ge Gt I Integer Le Lt Mul Ne Not Or Pow Rational "
"Symbol binomial cos exp factorial log oo pi sin sqrt tan "
"asin acos atan atan2 sinh cosh tanh asinh acosh atanh "
"sec csc cot floor ceiling Min Max gamma erf Mod sign re im "
"Piecewise conjugate"
).split()
_KNOWN_CALL_NAMES = frozenset(_SYMPY_NAMES) | {"ln", "e"}
def _undefined_call_names(text: str) -> list[str]:
found = (match.group(1) for match in _CALL_NAME.finditer(text))
return list(dict.fromkeys(name for name in found if name not in _KNOWN_CALL_NAMES))
def _require_sympy() -> Any | None:
try:
import sympy as sp
return sp
except ImportError:
return None
def _param_text(value: Any) -> str:
"""Stringify a parameter. ``None`` becomes an empty string.
``value or ""`` would treat JSON ``0`` and ``False`` as missing, so
``expression: 0`` would be "empty expression" instead of the number zero.
"""
if value is None:
return ""
return str(value).strip()
@functools.cache
def _parse_transformations() -> tuple[Any, ...]:
# x^2 is power, not XOR, and a multi-letter name stays one symbol.
# convert_xor plus implicit_multiplication and implicit_application;
# split_symbols would break names such as price.
from sympy.parsing.sympy_parser import (
convert_xor,
implicit_application,
implicit_multiplication,
standard_transformations,
)
return standard_transformations + (convert_xor, implicit_multiplication, implicit_application)
@functools.cache
def _sympy_name_dict(sp: Any) -> dict[str, Any]:
"""Names a formula may use. Not the process globals, so parse_expr cannot import.
Cached on the sympy module. ``parse_expr`` writes ``local_dict``, not this
dict. ``__builtins__`` is empty so ``eval`` does not inject real builtins.
Callers must not mutate the dict. ``ln`` is ``sp.log``. ``e`` is ``sp.E``
(there is no ``sp.e``; storing None would hide Euler's number).
"""
return {
"__builtins__": {},
**{name: getattr(sp, name) for name in _SYMPY_NAMES},
"ln": sp.log,
"e": sp.E,
}
def _reject_unsafe_expression(text: str) -> None:
"""Reject source that ``parse_expr`` would eval.
``parse_expr`` compiles the string and evals it. A restricted global dict
still runs attribute chains such as ``(1).__class__.__subclasses__()``
before the result can be inspected. Dunder names are not math. A dot is
a decimal only when the character before it or after it is a digit
(``1.5``, ``.5``, ``1.``, ``x.5``).
"""
if "__" in text:
raise HelperError("PARSE_ERROR", "Dunder attribute access is not allowed in expressions.")
for index, char in enumerate(text):
if char != ".":
continue
prev_digit = index > 0 and text[index - 1].isdigit()
next_digit = index + 1 < len(text) and text[index + 1].isdigit()
if not prev_digit and not next_digit:
raise HelperError("PARSE_ERROR", "Attribute access is not allowed in expressions.")
def _parse_expression(sp: Any, expr: Any, *, variable: Any | None = None) -> Any:
text = _param_text(expr)
if not text:
raise HelperError("PARSE_ERROR", "empty expression")
if len(text) > _MAX_SYMBOLIC_EXPR_CHARS:
raise HelperError("PARSE_ERROR", f"expression longer than {_MAX_SYMBOLIC_EXPR_CHARS} characters")
_reject_unsafe_expression(text)
from sympy.parsing.sympy_parser import parse_expr
local_dict: dict[str, Any] = {}
if variable is not None:
var_name = str(variable)
# local_dict wins over the global name, so a variable named e stays a
# symbol instead of Euler's number.
local_dict[var_name] = sp.Symbol(var_name)
try:
parsed = parse_expr(
text,
local_dict=local_dict,
global_dict=_sympy_name_dict(sp),
transformations=_parse_transformations(),
evaluate=False,
)
except Exception as exc:
# sympy rewrites an unknown call to Function('name')(...); eval then
# raises NameError. Which name is undefined is in the source, not in
# the exception text, so do not match the message wording.
if isinstance(exc, NameError):
names = _undefined_call_names(text)
if names:
raise HelperError("PARSE_ERROR", f"Undefined function in expression: {', '.join(names)}") from exc
raise HelperError("PARSE_ERROR", f"Could not parse expression: {exc}") from exc
# parse_expr returns a Python str, list, tuple or dict for quotes, brackets
# and braces, and the Float class for 1.0.func. Those have no .atoms, so
# reject them here as PARSE_ERROR.
if not isinstance(parsed, sp.Basic):
raise HelperError("PARSE_ERROR", "Not a math expression.")
return parsed
def _parse_variable(sp: Any, name: Any) -> Any:
return sp.Symbol(_param_text(name) or "x")
def _public_signature(func: Callable[..., Any]) -> inspect.Signature:
"""Drop ``sp``. Callers and generated templates never pass the module."""
raw = inspect.signature(func)
params = [param for name, param in raw.parameters.items() if name != "sp"]
return raw.replace(parameters=params)
def _symbolic_helper(func: Callable[..., dict[str, Any]]) -> Callable[..., dict[str, Any]]:
"""Resolve sympy once and turn helper failures into result dicts.
The wrapper passes the module in, so helpers do not look it up again and
do not assert on it (asserts vanish under ``python -O``).
Parse failures raise ``HelperError`` with their own code (PARSE_ERROR).
Any other exception, such as a ``ValueError`` from simplify, integrate or
solve, becomes SYMBOLIC_ERROR, so the user can tell a bad expression from a
math failure.
"""
public_sig = _public_signature(func)
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> dict[str, Any]:
helper = func.__name__
sp = _require_sympy()
if sp is None:
return missing_package_error(helper, "sympy")
try:
return func(sp, *args, **kwargs)
except HelperError as exc:
return error_result(exc.code, str(exc), helper=helper)
except Exception as exc:
return error_result("SYMBOLIC_ERROR", str(exc), helper=helper)
# inspect.signature follows __wrapped__ unless this is set, and would
# then require `sp`. Run Python Script templates bind the public kwargs.
setattr(wrapper, "__signature__", public_sig)
return wrapper
@helper("symbolic")
@_symbolic_helper
def symbolic_simplify(sp: Any, *, expression: Any) -> dict[str, Any]:
"""Simplify a symbolic expression."""
expr = _parse_expression(sp, expression)
simplified = sp.simplify(expr)
latex = str(sp.latex(simplified))
return ok_result("symbolic_simplify", latex=latex, text=str(simplified), writer_cleanup_hints=[])
@helper("symbolic")
@_symbolic_helper
def differentiate(sp: Any, *, expression: Any, variable: Any = "x") -> dict[str, Any]:
"""Differentiate *expression* with respect to *variable* (default ``x``).
``e`` is Euler's number. A variable named ``e`` stays that symbol.
"""
sym = _parse_variable(sp, variable)
expr = _parse_expression(sp, expression, variable=sym)
result = sp.diff(expr, sym)
latex = str(sp.latex(result))
# Echo str(sym), the stripped name. The raw parameter can still contain spaces.
return ok_result("differentiate", latex=latex, text=str(result), variable=str(sym), writer_cleanup_hints=[])
@helper("symbolic")
@_symbolic_helper
def integrate(
sp: Any,
*,
expression: Any,
variable: Any = "x",
lower: Any = None,
upper: Any = None,
) -> dict[str, Any]:
"""Integrate an expression. Pass both bounds for a definite integral."""
sym = _parse_variable(sp, variable)
expr = _parse_expression(sp, expression, variable=sym)
if is_blank_param(lower, strip=True) != is_blank_param(upper, strip=True):
# Exactly one bound is MISSING_PARAM. Both absent is indefinite;
# both present is definite.
raise HelperError("MISSING_PARAM", "Both lower and upper bounds must be provided for definite integration.")
if not is_blank_param(lower, strip=True):
a = _parse_expression(sp, lower, variable=sym)
b = _parse_expression(sp, upper, variable=sym)
result = sp.integrate(expr, (sym, a, b))
else:
result = sp.integrate(expr, sym)
# integrate returns Integral(...) when it has no closed form and the
# helper must not report that object as success.
if result.has(sp.Integral):
raise HelperError("NO_CLOSED_FORM", f"No closed form: {result}")
latex = str(sp.latex(result))
return ok_result("integrate", latex=latex, text=str(result), variable=str(sym), writer_cleanup_hints=[])
@helper("symbolic")
@_symbolic_helper
def solve_equation(sp: Any, *, equation: Any, variable: Any = "x") -> dict[str, Any]:
"""Solve one equation for *variable*.
Use ``=`` or an expression equal to zero. Inequalities and ``==`` are
rejected. ``!=`` is one token, including ``n!=720``, so that is not
factorial. Factorial equations need a space before ``=`` (``n! = 720``).
SymPy may still report that it has no algorithm for those.
"""
sym = _parse_variable(sp, variable)
text = _param_text(equation)
if not text:
raise HelperError("MISSING_PARAM", "equation is required")
# Inequalities and '==' are INVALID_PARAM. split("=", 1) would cut
# '<=' and '==' into pieces parse_expr cannot accept. `!=` stays rejected:
# the tokenizer fuses it, so factorial_notation never sees a bare `!`.
if re.search(r"<=|>=|!=|==|<|>", text):
raise HelperError("INVALID_PARAM", "Inequalities and '==' are not supported in solve_equation; use '=' or expression equal to zero.")
if "=" in text:
parts = text.split("=")
if len(parts) > 2:
raise HelperError("INVALID_PARAM", "Equation cannot contain multiple '=' signs.")
lhs = _parse_expression(sp, parts[0], variable=sym)
rhs = _parse_expression(sp, parts[1], variable=sym)
target = sp.Eq(lhs, rhs)
else:
target = _parse_expression(sp, text, variable=sym)
solutions = sp.solve(target, sym)
if not isinstance(solutions, list):
solutions = [solutions]
# sp.solve returns [] when nothing is a root (exp(x), 1 = 0) and when every
# complex value works (x = x, 0), which would leave latex empty. solveset on
# that empty list separates EmptySet (NO_SOLUTION) from any other set, which
# is returned as one latex value so egress has a formula. A non-empty solve
# list is still the explicit roots (sin(x) stays 0, pi).
if not solutions:
solution_set = sp.solveset(target, sym, domain=sp.S.Complexes)
if solution_set == sp.S.EmptySet:
raise HelperError("NO_SOLUTION", "No solution.")
exprs = [solution_set]
else:
exprs = solutions
latex = ", ".join(str(sp.latex(expr)) for expr in exprs)
solution_strs = [str(expr) for expr in exprs]
text_sol = ", ".join(solution_strs)
return ok_result(
"solve_equation",
latex=latex,
text=text_sol,
solutions=solution_strs,
variable=str(sym),
writer_cleanup_hints=[],
)
@helper("symbolic")
@_symbolic_helper
def latex_to_math_object(sp: Any, *, latex: Any) -> dict[str, Any]:
"""Normalize a math string for Writer Math insert.
A LaTeX cue (``=``, ``\\``, ``{``, ``}``, ``^``, ``_``) keeps the text
unchanged as both ``latex`` and ``text``. Anything else is parsed and
re-emitted as LaTeX. ``x_1`` is kept because of ``_``. ``x1`` and ``a b``
have no cue, so they are parsed (``a b`` becomes a product).
"""
trimmed = _param_text(latex)
if not trimmed:
raise HelperError("MISSING_PARAM", "latex is required")
if len(trimmed) > _MAX_SYMBOLIC_EXPR_CHARS:
raise HelperError("PARSE_ERROR", f"latex longer than {_MAX_SYMBOLIC_EXPR_CHARS} characters")
if not any(cue in trimmed for cue in _LATEX_CUES):
expr = _parse_expression(sp, trimmed)
trimmed = str(sp.latex(expr))
return ok_result("latex_to_math_object", latex=trimmed, text=trimmed, writer_cleanup_hints=[])
def run_symbolic(
spec: dict[str, Any] | str,
data: Any = None,
context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Spec-driven dispatcher for trusted symbolic helpers."""
return run_domain("symbolic", spec, data, context=context)