Skip to content

Instantly share code, notes, and snippets.

Last active September 17, 2023 21:01
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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,
f = lambdify(sympy_expr,sympy_var,modules=[mapping, casadi])
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)
Copy link

AunSiro commented Dec 3, 2019

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:


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

Copy link

is there any support for casadi to sympy?

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