Repository navigation
specifying casadi expressions in TOML (strings to casadi) #4471
Replies: 2 comments
|
CasADi has no parser for expression strings that I could find. I'd walk Python's import ast
import operator as op
import casadi as cs
BINOPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow}
CMPOPS = {ast.Lt: op.lt, ast.LtE: op.le, ast.Gt: op.gt, ast.GtE: op.ge}
FUNCS = {name: getattr(cs, name) for name in (
"sin", "cos", "tan", "exp", "log", "sqrt", "tanh", "fmax", "fmin",
"if_else", "vertcat", "horzcat", "sum1", "dot", "mtimes")}
FUNCS["abs"] = cs.fabs
def parse_expr(src, names, funcs=FUNCS, max_len=10_000):
"""Build a CasADi expression from a string without eval/exec.
names: dict of allowed variables (CasADi symbols or numbers).
funcs: dict of allowed functions. Anything else raises ValueError.
"""
if len(src) > max_len:
raise ValueError("expression too long")
def index(n): # integer literals and slices only
if isinstance(n, ast.Slice):
return slice(*(None if p is None else index(p)
for p in (n.lower, n.upper, n.step)))
if isinstance(n, ast.Tuple):
return tuple(index(e) for e in n.elts)
if isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.USub):
return -index(n.operand)
if isinstance(n, ast.Constant) and type(n.value) is int:
return n.value
raise ValueError(f"bad index: {ast.unparse(n)}")
def ev(n):
if isinstance(n, ast.Constant) and type(n.value) in (int, float):
return float(n.value) # floats overflow instead of hanging on 9**9**9
if isinstance(n, ast.Name):
if n.id not in names:
raise ValueError(f"unknown name '{n.id}'")
return names[n.id]
if isinstance(n, ast.BinOp) and type(n.op) in BINOPS:
return BINOPS[type(n.op)](ev(n.left), ev(n.right))
if isinstance(n, ast.UnaryOp) and type(n.op) in (ast.USub, ast.UAdd):
return -ev(n.operand) if isinstance(n.op, ast.USub) else ev(n.operand)
if isinstance(n, ast.Compare) and len(n.ops) == 1 and type(n.ops[0]) in CMPOPS:
return CMPOPS[type(n.ops[0])](ev(n.left), ev(n.comparators[0]))
if isinstance(n, ast.List): # [a, b, c] -> column vector
return cs.vertcat(*map(ev, n.elts))
if isinstance(n, ast.Subscript):
return ev(n.value)[index(n.slice)]
if (isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
and n.func.id in funcs and not n.keywords):
return funcs[n.func.id](*map(ev, n.args))
raise ValueError(f"not allowed: {ast.unparse(n)}")
return ev(ast.parse(src, mode="eval").body)Users drop the import tomllib
cfg = tomllib.loads("""
[constants]
g = 9.8
[expressions]
L = ""
E = "tfs"
e = "vertcat(x0s - [0, 0, 0], xfs[0:2] - [1e3, 1])"
f = "[xs[2]*sin(us), xs[2]*cos(us), g*cos(us)]"
h = ""
""")
# the same symbols Syms(nx=3, nu=1) creates
ts, xs, us = cs.SX.sym("ts"), cs.SX.sym("xs", 3), cs.SX.sym("us", 1)
t0s, tfs, x0s, xfs = cs.SX.sym("t0s"), cs.SX.sym("tfs"), cs.SX.sym("x0s", 3), cs.SX.sym("xfs", 3)
c = cfg["constants"]
path_ns = dict(ts=ts, xs=xs, us=us, **c)
event_ns = dict(t0s=t0s, tfs=tfs, x0s=x0s, xfs=xfs, **c)
exprs = {k: parse_expr(v, path_ns if k in ("L", "f", "h") else event_ns)
for k, v in cfg["expressions"].items() if v}
for k, v in exprs.items():
print(k, "=", v)
for bad in ("__import__('os').system('ls')", "x0s[0] + us"):
try:
parse_expr(bad, path_ns)
except ValueError as err:
print(err)I tried this with casadi 3.8.2 on your brachistochrone. On sympy:
For bigger files, a |
|
Thanks. I didn't try this idea out but realized a much bigger problem of specifying as strings within toml. For small toy problems this is easy to specify. But let's say you derive the equation using from Lagrangian or RNEA or complex manipulation of the state and control variables. This specification as string and maintaining a parsing system will become painful which is an aspect i didn't think about. The practice choice I've now adopted is use of a separate script for the casadi expressions and a string in toml to link the script. This gets the job done. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I developed a open-source multiple shooting and direct collocation package called pytrajopt for multiphase OCPs (casadi in backend for AD and opti for solving the NLP). It strictly checks the OCP and NLP obtained post transcription to rule out errors. As a result user can infer from the OCP what's wrong than looking at output from casadi. Except for the symbolic manipulation of the expressions needed everything else related to casadi is kept hidden by design from user.
The library solves variety of examples. I want it to be extended to a TOML file. The problem is TOML has support for specific data types. I am doing complex symbolic manipulations of certain variables. Specifying them in TOML seems a bit challenging.
The python file specifying the OCP and a sample TOML file is given below.
evalwith predefined namespace, but due to security issues I have put that idea aside.I am in need of some ideas to be explored. If there's already a text to casadi parser or similar project please do highlihg
Sample TOML file
All reactions