Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare constraints for basinhopping optimization

I'm having trouble creating a dictionary for the constraints using scipy.optimize.basinhopping. I'm able to get my code to run (without constraints), but the answer doesn't make sense because I need to enforce some constraints. For now, I'm only trying to get one constraint working but for the final solution I need to figure out how to implement several constraints. The code I have now is:

x0 = [f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11]
args = arg1,arg2,arg3,arg4
def func(x,*args)
     #Do some math
     return result

#This is where I need help most
cons = {'type':'ineq','fun': lambda x: x[5]-x[4]}

minimizer_kwargs = {"method":"COBYLA","args":"args","constraints":"cons"}
ret = scipy.optimize.basinhopping(func,x0,minimizer_kwargs=minimizer_kwargs)

But get this error when trying to run it:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
    execfile(filename, namespace)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 66, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)
  File "C:/Python27/Scripts/SpectralResearch/mainScripts/main.py", line 121, in <module>
    ret = scipy.optimize.basinhopping(func,x0,minimizer_kwargs=minimizer_kwargs)
  File "C:\Python27\lib\site-packages\scipy\optimize\_basinhopping.py", line 605, in basinhopping
    accept_tests, disp=disp)
  File "C:\Python27\lib\site-packages\scipy\optimize\_basinhopping.py", line 72, in __init__
    minres = minimizer(self.x)
  File "C:\Python27\lib\site-packages\scipy\optimize\_basinhopping.py", line 279, in __call__
    return self.minimizer(self.func, x0, **self.kwargs)
  File "C:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 432, in minimize
    return _minimize_cobyla(fun, x0, args, constraints, **options)
  File "C:\Python27\lib\site-packages\scipy\optimize\cobyla.py", line 218, in _minimize_cobyla
    raise TypeError('Constraints must be defined using a '
TypeError: Constraints must be defined using a dictionary.

Essentially I need to enforce the constraint that certain variables are greater than others. I've been looking at the documentation([1],[2]) and articles, but haven't found anything that works. Any ideas what I could be doing wrong?

like image 738
user3199645 Avatar asked Feb 02 '26 17:02

user3199645


1 Answers

minimizer_kwargs = {"method":"COBYLA","args":args,"constraints":cons}

You passed the strings "args" and "cons" instead of the variables with those names.

like image 86
Moritz Avatar answered Feb 05 '26 06:02

Moritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!