Reputation: 1087
I am using fmin_cobyla for to solve a constraint optimization problem. my objective function has two parameters in the form of array and I have the following code:
import pandas as pd
import numpy as np
import scipy as sc
from scipy.optimize import fmin_cobyla
def distance (x,Weight,Initial):
dist = Weight*(Initial-x)**2
return np.sum(dist)
Weight =np.array([10, 10, 10, 10])
Initial=np.array([1. , 1.4 , 0.95, 1.2])
A = np.array([(1, -1,0,0), (0,1,-1,0), (0,0,1,-1)])
b = np.array([0,0,0])
constraints = []
for i in range(len(A)):
def f(x, i = i):
return np.dot(x,A[i])-b[i]
constraints.append(f)
res1 = fmin_cobyla(distance, Initial, constraints,args=(Weight,Initial), rhoend = 1e-7)
I ma using args=(Weight,Initial) to pass parameters to the objective function which is "distance" however I got the following error:
TypeError Traceback (most recent call last)
<ipython-input-11-fc267b7a75d8> in <module>()
20 constraints.append(f)
21
---> 22 res1 = fmin_cobyla(distance, Initial, constraints,args=(Weight,Initial), rhoend = 1e-7)
C:\Users\ameimand\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\optimize\cobyla.py in fmin_cobyla(func, x0, cons, args, consargs, rhobeg, rhoend, iprint, maxfun, disp, catol)
170
171 sol = _minimize_cobyla(func, x0, args, constraints=con,
--> 172 **opts)
173 if iprint > 0 and not sol['success']:
174 print("COBYLA failed to find a solution: %s" % (sol.message,))
C:\Users\ameimand\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\optimize\cobyla.py in _minimize_cobyla(fun, x0, args, constraints, rhobeg, tol, iprint, maxiter, disp, catol, **unknown_options)
237 cons_lengths = []
238 for c in constraints:
--> 239 f = c['fun'](x0, *c['args'])
240 try:
241 cons_length = len(f)
TypeError: f() takes from 1 to 2 positional arguments but 3 were given
It seems the error is related to passing parameters to the constraint while args() is supposed to pass them to objective function.
Thanks
Upvotes: 0
Views: 752
Reputation: 33542
The docs say:
consargs : tuple, optional
Extra arguments to pass to constraint functions (default of None means use same extra arguments as those passed to func). Use () for no extra arguments.
(annotation by me)
So in your case args=(Weight,Initial)
will be passed to f
.
Add the argument consargs=()
like:
res1 = fmin_cobyla(distance, Initial, constraints,args=(Weight,Initial),
consargs=(), rhoend = 1e-7)
This will make the code run. But i did not analyze anything else!
(Usually people use the more general minimize instead of the more low-level functions like fmin_cobyla)
Upvotes: 1