I have the following 'issue' with sympy at the moment:
I have a symbolic expression like M = matrix([pi*a, sin(1)*b])
which I want to lambdify
and pass to a numerical optimizer. The issue is that the optimizer needs the function to input/output numpy arrays of shape (n,)
and specifically NOT (n,1)
.
Now I have been able to achieve this with the following code (MWE):
import numpy as np
import sympy as sp
a, b = sp.symbols('a, b')
M = sp.Matrix([2*a, b])
f_tmp = sp.lambdify([[a,b]], M, 'numpy')
fun = lambda x: np.reshape( f_tmp(x), (2,))
Now, this is of course extremely ugly, since the reshape needs to be applied every time fun
is evaluated (which might be LOTS of times). Is there a way to avoid this problem? The Matrix
class is by definition always 2 dimensional. I tried using sympy
's MutableDenseNDimArray
-class, but they don't work in conjunction with lambdify. (symbolic variables don't get recognized)