I know that this question should be handled in the manual of scipy.optimize, but I don't understand it well enough. Maybe you can help
I have a function (this is just an example, not the real function, but I need to understand it at this level):
Edit (better example):
Let's suppose I have a matrix
arr = array([[0.8, 0.2],[-0.1, 0.14]])
with a target function
def matr_t(t): return array([[t[0], 0],[t[2]+complex(0,1)*t[3], t[1]]] def target(t): arr2 = matr_t(t) ret = 0 for i, v1 in enumerate(arr): for j, v2 in enumerate(v1): ret += abs(arr[i][j]-arr2[i][j])**2 return ret
now I want to minimize this target function under the assumption that the t[i] are real numbers, and something like t[0]+t[1]=1
A simple application of the Nelder-Mead method is: >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6) >>> res. x array([ 1., 1., 1., 1., 1.]) It should converge to the theoretical solution (1.4 ,1.7).
SciPy optimize provides functions for minimizing (or maximizing) objective functions, possibly subject to constraints. It includes solvers for nonlinear problems (with support for both local and global optimization algorithms), linear programing, constrained and nonlinear least-squares, root finding, and curve fitting.
Sequential Least SQuares Programming optimizer. SLSQP minimizes a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft.
This constraint
t[0] + t[1] = 1
would be an equality (type='eq'
) constraint, where you make a function that must equal zero:
def con(t): return t[0] + t[1] - 1
Then you make a dict
of your constraint (list of dicts if more than one):
cons = {'type':'eq', 'fun': con}
I've never tried it, but I believe that to keep t
real, you could use:
con_real(t): return np.sum(np.iscomplex(t))
And make your cons
include both constraints:
cons = [{'type':'eq', 'fun': con}, {'type':'eq', 'fun': con_real}]
Then you feed cons
into minimize
as:
scipy.optimize.minimize(func, x0, constraints=cons)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With