Skip to content

Instantly share code, notes, and snippets.

@jgillis
Last active May 6, 2024 19:32
Show Gist options
  • Save jgillis/80bb594a6c8fcf55891d1d88b12b68b8 to your computer and use it in GitHub Desktop.
Save jgillis/80bb594a6c8fcf55891d1d88b12b68b8 to your computer and use it in GitHub Desktop.
Convert sympy expression to CasADi
def sympy2casadi(sympy_expr,sympy_var,casadi_var):
import casadi
assert casadi_var.is_vector()
if casadi_var.shape[1]>1:
casadi_var = casadi_var.T
casadi_var = casadi.vertsplit(casadi_var)
from sympy.utilities.lambdify import lambdify
mapping = {'ImmutableDenseMatrix': casadi.blockcat,
'MutableDenseMatrix': casadi.blockcat,
'Abs':casadi.fabs
}
f = lambdify(sympy_expr,sympy_var,modules=[mapping, casadi])
print(casadi_var)
return f(*casadi_var)
import sympy
x,y = sympy.symbols("x y")
import casadi
X = casadi.SX.sym("x")
Y = casadi.SX.sym("y")
xy = sympy.Matrix([x,y])
e = sympy.Matrix([x*sympy.sqrt(y),sympy.sin(x+y),abs(x-y)])
XY = casadi.vertcat(X,Y)
@AunSiro
Copy link

AunSiro commented Dec 3, 2019

Hello!
I run it and added sympy2casadi(e, xy, XY)at the end to check the result. I got a syntax error that could be solved by switching the order in the lambdify arguments to lambdify(sympy_var,sympy_expr,modules=[mapping, casadi]), because according to the Lambdify docstring:

lambdify(
    args,
    expr,
    modules=None,
    printer=None,
    use_imps=True,
    dummify=False,
)

I have noticed that in the second revision you made the inverse change. I am curious about why did you do that?
I am using Sympy 1.4

Thank you and have a nice day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment