Convert sympy expression to CasADi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
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 tolambdify(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