Python minimize function: passing additional arguments to constraint dictionary

2024/10/5 19:16:53

I don't know how to pass additional arguments through the minimize function to the constraint dictionary. I can successfully pass additional arguments to the objective function.

Documentation on minimize function is here: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize

The constraints argument is a dict that has a field 'args', where args is a sequence. I'm sure this is where I need to pass in the additional arguments but I don't know the syntax. The closest I have got is below:

from scipy.optimize import minimize
def f_to_min (x, p):return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])f_to_min([1,2],[1,1,1]) # test function to minimizep=[] # define additional args to be passed to objective function
f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)}) # define constraintp0=np.array([1,1,1])
minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)

I get the following error

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-19-571500063c9e> in <module>()1 p0=np.array([1,1,1])
----> 2 minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)C:\Python27\lib\site-packages\scipy\optimize\_minimize.pyc in minimize(fun, x0, args,     method, jac, hess, hessp, bounds, constraints, tol, callback, options)356     elif meth == 'slsqp':357         return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 358                                constraints, **options)359     else:360         raise ValueError('Unknown solver %s' % method)C:\Python27\lib\site-packages\scipy\optimize\slsqp.pyc in _minimize_slsqp(func, x0,     args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, **unknown_options)298     # meq, mieq: number of equality and inequality constraints299     meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in     cons['eq']]))
--> 300     mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in     cons['ineq']]))301     # m = The total number of constraints302     m = meq + mieq<ipython-input-18-163ef1a4f6fb> in <lambda>(x, p)
----> 1 f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)})IndexError: list index out of range

I'm accessing the first element of the additional parameter so I shouldn't have an out of range error.

If you remove the constraints=f_to_min_cons argument from the minimize function then the code above works.

Answer

The answer simply, is that p = [] has no elements and no length, and so p[0] is out of bounds.

The following, where we set p = [0], runs without error. What p should actually hold is of course, not something that we can answer with the information given.

import numpy as npfrom scipy.optimize import minimize
def f_to_min (x, p):return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])f_to_min([1,2],[1,1,1]) # test function to minimizep=[0] # define additional args to be passed to the constraint
f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)},) # define constraintp0=np.array([1,1,1]) # args to be passed to the objective function
minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)
https://en.xdnf.cn/q/70446.html

Related Q&A

PyQt5 triggering a paintEvent() with keyPressEvent()

I am trying to learn PyQt vector painting. Currently I am stuck in trying to pass information to paintEvent() method which I guess, should call other methods:I am trying to paint different numbers to a…

A python regex that matches the regional indicator character class

I am using python 2.7.10 on a Mac. Flags in emoji are indicated by a pair of Regional Indicator Symbols. I would like to write a python regex to insert spaces between a string of emoji flags.For exampl…

Importing modules from a sibling directory for use with py.test

I am having problems importing anything into my testing files that I intend to run with py.test.I have a project structure as follows:/ProjectName | |-- /Title | |-- file1.py | |-- file2.py | …

Uploading and processing a csv file in django using ModelForm

I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code. This is my html form (upload_csv1.html):<form action="{% url myapp:upload_csv %}" me…

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

I am trying to get my head around matplotlibs state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should…

libclang: add compiler system include path (Python in Windows)

Following this question and Andrews suggestions, I am trying to have liblang add the compiler system include paths (in Windows) in order for my Python codeimport clang.cindexdef parse_decl(node):refere…

Pako not able to deflate gzip files generated in python

Im generating gzip files from python using the following code: (using python 3)file = gzip.open(output.json.gzip, wb)dataToWrite = json.dumps(data).encode(utf-8)file.write(dataToWrite)file.close()Howev…

Best way to have a python script copy itself?

I am using python for scientific applications. I run simulations with various parameters, my script outputs the data to an appropriate directory for that parameter set. Later I use that data. However s…

How to convert dictionary to matrix in python?

I have a dictionary like this:{device1 : (news1, news2, ...), device2 : (news 2, news 4, ...)...}How to convert them into a 2-D 0-1 matrix in python? Looks like this:news1 news2 news3 news4 device1 …

Ubuntu 16.04 - Why I cannot install libtiff4-dev?

Following this tutorial, I am trying to install the OpenCV 3 with Python on Ubuntu 16.04.At the step of entering $ sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-devI got this me…