Optimize a symbolic problem #22257
Replies: 1 comment 2 replies
-
I don't know opty or cvxpy so I'm not sure how to use those but most optimisation libraries just expect you to provide a callable objective function in some way and the way to make an efficient callable from a sympy expression is by using Here's an example: In [30]: x, y = symbols('x, y')
In [31]: expr = (x - 1)**2 + (y - 2)**2
In [32]: expr
Out[32]:
2 2
(x - 1) + (y - 2)
In [33]: f = lambdify(((x, y,),), expr, 'numpy')
In [34]: from scipy.optimize import minimize
In [35]: minimize(f, [0, 0])
Out[35]:
fun: 1.705780445775116e-16
hess_inv: array([[ 0.9, -0.2],
[-0.2, 0.6]])
jac: array([ 3.21944782e-09, -8.46226644e-09])
message: 'Optimization terminated successfully.'
nfev: 9
nit: 2
njev: 3
status: 0
success: True
x: array([0.99999999, 1.99999999]) The slightly tricky part is that at least for scipy's In [42]: import inspect
In [43]: print(inspect.getsource(f))
def _lambdifygenerated(_Dummy_88):
[x, y] = _Dummy_88
return (x - 1)**2 + (y - 2)**2 You can improve this by computing the gradient of the function and passing that to In [46]: jac = lambdify(((x, y),), Array([expr.diff(x), expr.diff(y)]))
In [47]: minimize(f, [0, 0], jac=jac)
Out[47]:
fun: 0.0
hess_inv: array([[ 0.9, -0.2],
[-0.2, 0.6]])
jac: array([0., 0.])
message: 'Optimization terminated successfully.'
nfev: 3
nit: 2
njev: 3
status: 0
success: True
x: array([1., 2.]) Being able to compute the derivatives symbolically like this is typically the reason for wanting to use SymPy rather than just defining |
Beta Was this translation helpful? Give feedback.
-
Hi SymPy team,
I am using sympy for getting the equations of motion of a manipulator in symbolic form.
Then I want to solve a trajectory tracking problem, the idea is to set as objective function the difference between the initial and desired configuration and to use an optimization tool (e.g. opty or cvxpy) to minimise it.
Is sympy compatible with any optimization tool?
Is there any example of such tool applied to an objective function written in symbolic form with sympy?
Beta Was this translation helpful? Give feedback.
All reactions