File size: 12,761 Bytes
08f8699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""Parser for agent-emitted equations of motion.

RHS is parsed via Python's ``ast`` module, then walked by a whitelist visitor
that only permits Constant / Name / UnaryOp (+/-) / BinOp (+ - * / **) /
Call (bare allowed-function name, no kwargs). Anything else — Attribute,
Subscript, Lambda, IfExp, keyword args, etc. — raises ParseError by
construction. We never call sympify on raw text, so there is no eval stage
that can crash the trainer with an AttributeError.

Pre-transforms before AST parse:
- ``^`` → ``**`` (physics power notation)
- ``dx/dt`` / bare ``dx`` → ``vx`` when the system pairs x with vx
"""

from __future__ import annotations

import ast
import re

import sympy as sp
from pydantic import BaseModel, ConfigDict


class ParseError(ValueError):
    """Raised when the agent's text payload violates the equation grammar."""


ALLOWED_FUNCTIONS: dict[str, sp.Function] = {
    "sin": sp.sin,
    "cos": sp.cos,
    "tan": sp.tan,
    "exp": sp.exp,
    "log": sp.log,
    "sqrt": sp.sqrt,
    "abs": sp.Abs,
    "Abs": sp.Abs,
}


def _build_grammar_hint() -> str:
    funcs = sorted({name.lower() for name in ALLOWED_FUNCTIONS})
    return (
        "The 'equation' field is an infix ODE in plain ASCII. "
        "LHS form: 'dN<var>/dtN' where N is 1 or 2 (omit N for first "
        "order, e.g. 'dy/dt' or 'd2y/dt2'). "
        "RHS uses operators + - * / ** (or ^ for power), parentheses, "
        "the state variables listed under STATE_VARIABLES, and any "
        "names you declare in 'params'. "
        f"Allowed functions: {' '.join(funcs)}. "
        "Velocity convention: when STATE_VARIABLES lists both 'x' and 'vx' "
        "(or 'y'/'vy', etc.), use the 'vx' name on the RHS to refer to the "
        "first time-derivative of x. The aliases 'dx/dt' and bare 'dx' are "
        "also accepted for that case. The system is autonomous: time 't' is "
        "not a valid RHS symbol. "
        "No LaTeX, no \\frac, no array indexing, no library prefixes "
        "(write 'sqrt(x)', not 'np.sqrt(x)'), no keyword arguments. "
        "Working examples appear in the HISTORY block of each subsequent turn."
    )


GRAMMAR_HINT: str = _build_grammar_hint()


_LHS_PATTERN = re.compile(
    r"""
    ^\s*
    d(?P<order>\d*)
    (?P<var>[A-Za-z_][A-Za-z0-9_]*)
    /
    d t
    (?P<order2>\d*)
    \s*$
    """,
    re.VERBOSE,
)

_BIN_OP_TO_SYMPY: dict[type, "callable"] = {
    ast.Add: lambda a, b: a + b,
    ast.Sub: lambda a, b: a - b,
    ast.Mult: lambda a, b: a * b,
    ast.Div: lambda a, b: a / b,
    ast.Pow: lambda a, b: a**b,
}


class Equation(BaseModel):
    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)

    var: str
    order: int
    rhs: sp.Expr


class ParsedEquation(BaseModel):
    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)

    equations: tuple[Equation, ...]
    free_symbols: frozenset[str]
    operator_count: int


def parse_equation(
    text: str,
    state_variables: tuple[str, ...],
    parameter_names: frozenset[str],
) -> ParsedEquation:
    """Parse and validate the agent's equation payload.

    Only ParseError ever escapes — callers convert it to r_format=0.
    """
    if not text or not text.strip():
        raise ParseError("Empty equation payload.")

    raw_equations = _split_equations(text)
    if not raw_equations:
        raise ParseError("No equations found in payload.")

    allowed_symbols = frozenset(state_variables) | parameter_names

    parsed: list[Equation] = []
    free_symbol_names: set[str] = set()
    operator_count = 0

    for raw in raw_equations:
        eq = _parse_one(raw, allowed_symbols, state_variables)
        parsed.append(eq)
        free_symbol_names.update(s.name for s in eq.rhs.free_symbols)
        operator_count += _count_operators(eq.rhs)

    return ParsedEquation(
        equations=tuple(parsed),
        free_symbols=frozenset(free_symbol_names),
        operator_count=operator_count,
    )


def _split_equations(text: str) -> list[str]:
    parts = re.split(r"[;\n]+", text)
    return [p.strip() for p in parts if p.strip()]


def _parse_one(
    raw: str,
    allowed_symbols: frozenset[str],
    state_variables: tuple[str, ...],
) -> Equation:
    if "=" not in raw:
        raise ParseError(f"Equation has no '=' sign: {raw!r}")
    lhs_text, rhs_text = raw.split("=", 1)
    var, order = _parse_lhs(lhs_text)
    rhs_expr = _parse_rhs(rhs_text, allowed_symbols, state_variables)
    return Equation(var=var, order=order, rhs=rhs_expr)


def _parse_lhs(lhs: str) -> tuple[str, int]:
    match = _LHS_PATTERN.match(lhs)
    if not match:
        raise ParseError(
            f"Cannot parse LHS {lhs!r}. Expected 'dN<var>/dtN' where N is "
            "1 or 2 (or empty for first order)."
        )
    order_top = match.group("order")
    order_bot = match.group("order2")
    var = match.group("var")
    if order_top != order_bot:
        raise ParseError(
            f"LHS order mismatch in {lhs!r}: top order {order_top!r} vs "
            f"bottom order {order_bot!r}."
        )
    if order_top == "":
        order = 1
    elif order_top in {"1", "2"}:
        order = int(order_top)
    else:
        raise ParseError(f"Only orders 1 and 2 are supported. Got {order_top!r}.")
    return var, order


def _parse_rhs(
    rhs: str,
    allowed_symbols: frozenset[str],
    state_variables: tuple[str, ...],
) -> sp.Expr:
    rhs = rhs.strip()
    if not rhs:
        raise ParseError("Empty RHS.")
    rhs = rhs.replace("^", "**")
    rhs = _apply_velocity_alias(rhs, state_variables)
    try:
        tree = ast.parse(rhs, mode="eval")
    except SyntaxError as exc:
        raise ParseError(
            f"Syntax error in RHS {rhs!r}: {exc.msg}. "
            "Expected an infix expression like '-k*x + c*vx'."
        ) from exc
    return _ast_to_sympy(tree.body, allowed_symbols, state_variables)


def _ast_to_sympy(
    node: ast.AST,
    allowed_symbols: frozenset[str],
    state_variables: tuple[str, ...],
) -> sp.Expr:
    if isinstance(node, ast.Constant):
        if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
            raise ParseError(
                f"Only numeric literals allowed on RHS; got "
                f"{node.value!r} ({type(node.value).__name__})."
            )
        return sp.Number(node.value)

    if isinstance(node, ast.Name):
        return _name_to_sympy(node.id, allowed_symbols, state_variables)

    if isinstance(node, ast.UnaryOp):
        operand = _ast_to_sympy(node.operand, allowed_symbols, state_variables)
        if isinstance(node.op, ast.UAdd):
            return +operand
        if isinstance(node.op, ast.USub):
            return -operand
        raise ParseError(
            f"Unsupported unary operator {type(node.op).__name__}. "
            "Allowed: + (positive), - (negation)."
        )

    if isinstance(node, ast.BinOp):
        op_fn = _BIN_OP_TO_SYMPY.get(type(node.op))
        if op_fn is None:
            raise ParseError(
                f"Unsupported binary operator {type(node.op).__name__}. "
                "Allowed: + - * / ** (also '^' as a power synonym)."
            )
        left = _ast_to_sympy(node.left, allowed_symbols, state_variables)
        right = _ast_to_sympy(node.right, allowed_symbols, state_variables)
        return op_fn(left, right)

    if isinstance(node, ast.Call):
        return _call_to_sympy(node, allowed_symbols, state_variables)

    if isinstance(node, ast.Attribute):
        raise ParseError(
            "Attribute access is not allowed in equation RHS "
            f"(saw '.{node.attr}'). Use bare function names like "
            "'sqrt(x)' or 'sin(theta)', not 'np.sqrt(x)'."
        )

    if isinstance(node, ast.Subscript):
        raise ParseError(
            "Array indexing is not allowed in equation RHS. "
            "Use named scalars declared in 'params'."
        )

    if isinstance(node, ast.Compare):
        raise ParseError(
            "Comparisons (==, <, >, etc.) are not allowed in equation RHS."
        )

    if isinstance(node, ast.BoolOp):
        raise ParseError(
            "Boolean operators ('and', 'or') are not allowed in equation RHS."
        )

    if isinstance(node, ast.IfExp):
        raise ParseError(
            "Conditional expressions ('a if cond else b') are not allowed in "
            "equation RHS."
        )

    if isinstance(node, ast.Lambda):
        raise ParseError("Lambda expressions are not allowed in equation RHS.")

    if isinstance(node, (ast.Tuple, ast.List, ast.Set, ast.Dict)):
        raise ParseError(
            f"Collection literal ({type(node).__name__}) is not allowed in "
            "equation RHS."
        )

    raise ParseError(
        f"Unsupported expression construct {type(node).__name__}. "
        "The grammar accepts: numeric literals, allowed identifiers, "
        f"+ - * / **, parentheses, and {sorted(ALLOWED_FUNCTIONS)}."
    )


def _name_to_sympy(
    name: str,
    allowed_symbols: frozenset[str],
    state_variables: tuple[str, ...],
) -> sp.Symbol:
    if name in ALLOWED_FUNCTIONS:
        raise ParseError(
            f"{name!r} is a function and must be called with parentheses, "
            f"e.g. {name}(x)."
        )
    if name not in allowed_symbols:
        hint = _explain_unknown_symbol(name, state_variables)
        suffix = f" {hint}" if hint else ""
        raise ParseError(
            f"Unknown symbol {name!r}; allowed {sorted(allowed_symbols)!r}."
            f"{suffix}"
        )
    return sp.Symbol(name)


def _call_to_sympy(
    node: ast.Call,
    allowed_symbols: frozenset[str],
    state_variables: tuple[str, ...],
) -> sp.Expr:
    if node.keywords:
        raise ParseError(
            "Keyword arguments are not allowed in function calls "
            "(e.g. 'sin(theta=0.1)'). Pass positional arguments only."
        )
    for arg in node.args:
        if isinstance(arg, ast.Starred):
            raise ParseError("Star-arg / unpacking ('*args') is not allowed.")

    if isinstance(node.func, ast.Attribute):
        raise ParseError(
            "Attribute access is not allowed in equation RHS "
            f"(saw '.{node.func.attr}'). Use bare function names like "
            "'sqrt(x)' or 'sin(theta)', not 'np.sqrt(x)'."
        )

    if not isinstance(node.func, ast.Name):
        raise ParseError(
            "Only direct calls to named functions are allowed. "
            f"Use one of {sorted(ALLOWED_FUNCTIONS)}, not a computed-name call."
        )

    func_name = node.func.id
    if func_name not in ALLOWED_FUNCTIONS:
        raise ParseError(
            f"Unknown function {func_name!r}; "
            f"allowed: {sorted(ALLOWED_FUNCTIONS)}."
        )

    args = [_ast_to_sympy(a, allowed_symbols, state_variables) for a in node.args]
    return ALLOWED_FUNCTIONS[func_name](*args)


def _apply_velocity_alias(rhs: str, state_variables: tuple[str, ...]) -> str:
    aliases = _velocity_aliases(state_variables)
    if not aliases:
        return rhs
    out = rhs
    for var, velocity in aliases:
        slash_pattern = rf"\bd{re.escape(var)}\s*/\s*dt\b"
        out = re.sub(slash_pattern, velocity, out)
        bare_pattern = rf"\bd{re.escape(var)}\b"
        out = re.sub(bare_pattern, velocity, out)
    return out


def _velocity_aliases(state_variables: tuple[str, ...]) -> list[tuple[str, str]]:
    state_set = set(state_variables)
    out: list[tuple[str, str]] = []
    for var in state_variables:
        if not var or var.startswith(("d", "v")):
            continue
        velocity = f"v{var}"
        if velocity in state_set:
            out.append((var, velocity))
    return out


def _explain_unknown_symbol(name: str, state_variables: tuple[str, ...]) -> str:
    state_set = set(state_variables)
    if name == "t":
        return (
            "'t' is not allowed — the equation must be autonomous "
            "(express forces via state variables only, no explicit time)."
        )
    if name.startswith("d") and len(name) > 1:
        base = name[1:]
        velocity = f"v{base}"
        if velocity in state_set:
            return (
                f"Did you mean '{velocity}'? "
                f"Use '{velocity}' for the velocity of '{base}'."
            )
        if base in state_set:
            return (
                f"'{name}' looks like a derivative; this system has no "
                f"separate velocity name, write '{base}' on the RHS."
            )
    return ""


def _count_operators(expr: sp.Expr) -> int:
    count = 0
    for node in sp.preorder_traversal(expr):
        if not isinstance(node, (sp.Symbol, sp.Number)):
            count += 1
    return count